/phpMyAdmin/libraries/tcpdf/tcpdf.php

https://bitbucket.org/izubizarreta/https-bitbucket.org-bityvip · PHP · 28807 lines · 20023 code · 753 blank · 8031 comment · 4302 complexity · 5961b6a722f3607ac94f56fe976b534d MD5 · raw file

  1. <?php
  2. //============================================================+
  3. // File name : tcpdf.php
  4. // Version : 5.9.145
  5. // Begin : 2002-08-03
  6. // Last Update : 2012-01-28
  7. // Author : Nicola Asuni - Tecnick.com LTD - Manor Coach House, Church Hill, Aldershot, Hants, GU12 4RQ, UK - www.tecnick.com - info@tecnick.com
  8. // License : http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT GNU-LGPLv3
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2002-2012 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 ImagMagick (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 Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, 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/kerning);
  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. // THANKS TO:
  71. //
  72. // Olivier Plathey (http://www.fpdf.org) for original FPDF.
  73. // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
  74. // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
  75. // Warren Sherliker (wsherliker@gmail.com) for better image handling.
  76. // dullus for text Justification.
  77. // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
  78. // Patrick Benny for text stretch suggestion on Cell().
  79. // Johannes Güntert for JavaScript support.
  80. // Denis Van Nuffelen for Dynamic Form.
  81. // Jacek Czekaj for multibyte justification
  82. // Anthony Ferrara for the reintroduction of legacy image methods.
  83. // Sourceforge user 1707880 (hucste) for line-trough mode.
  84. // Larry Stanbery for page groups.
  85. // Martin Hall-May for transparency.
  86. // Aaron C. Spike for Polycurve method.
  87. // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
  88. // Moritz Wagner and Andreas Wurmser for graphic functions.
  89. // Andrew Whitehead for core fonts support.
  90. // Esteban Joël Marín for OpenType font conversion.
  91. // Teus Hagen for several suggestions and fixes.
  92. // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
  93. // Kosmas Papachristos for some CSS improvements.
  94. // Marcel Partap for some fixes.
  95. // Won Kyu Park for several suggestions, fixes and patches.
  96. // Dominik Dzienia for QR-code support.
  97. // Laurent Minguet for some suggestions.
  98. // Christian Deligant for some suggestions and fixes.
  99. // Travis Harris for crop mark suggestion.
  100. // Anyone that has reported a bug or sent a suggestion.
  101. //============================================================+
  102. /**
  103. * @file
  104. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  105. * 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>
  106. * <h3>TCPDF main features are:</h3>
  107. * <ul>
  108. * <li>no external libraries are required for the basic functions;</li>
  109. * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
  110. * <li>UTF-8 Unicode and Right-To-Left languages;</li>
  111. * <li>TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
  112. * <li>font subsetting;</li>
  113. * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
  114. * <li>images, graphic (geometric figures) and transformation methods;
  115. * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)</li>
  116. * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;</li>
  117. * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
  118. * <li>automatic page header and footer management;</li>
  119. * <li>document encryption up to 256 bit and digital signature certifications;</li>
  120. * <li>transactions to UNDO commands;</li>
  121. * <li>PDF annotations, including links, text and file attachments;</li>
  122. * <li>text rendering modes (fill, stroke and clipping);</li>
  123. * <li>multiple columns mode;</li>
  124. * <li>no-write page regions;</li>
  125. * <li>bookmarks, named destinations and table of content;</li>
  126. * <li>text hyphenation;</li>
  127. * <li>text stretching and spacing (tracking/kerning);</li>
  128. * <li>automatic page break, line break and text alignments including justification;</li>
  129. * <li>automatic page numbering and page groups;</li>
  130. * <li>move and delete pages;</li>
  131. * <li>page compression (requires php-zlib extension);</li>
  132. * <li>XOBject Templates;</li>
  133. * <li>Layers and object visibility;</li>
  134. * <li>PDF/A-1b support.</li>
  135. * </ul>
  136. * Tools to encode your unicode fonts are on fonts/utils directory.</p>
  137. * @package com.tecnick.tcpdf
  138. * @author Nicola Asuni
  139. * @version 5.9.145
  140. */
  141. // Main configuration file. Define the K_TCPDF_EXTERNAL_CONFIG constant to skip this file.
  142. require_once(dirname(__FILE__).'/config/tcpdf_config.php');
  143. /**
  144. * @class TCPDF
  145. * PHP class for generating PDF documents without requiring external extensions.
  146. * 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>
  147. * @package com.tecnick.tcpdf
  148. * @brief PHP class for generating PDF documents without requiring external extensions.
  149. * @version 5.9.145
  150. * @author Nicola Asuni - info@tecnick.com
  151. */
  152. class TCPDF {
  153. // private properties
  154. /**
  155. * Current TCPDF version.
  156. * @private
  157. */
  158. private $tcpdf_version = '5.9.145';
  159. // Protected properties
  160. /**
  161. * Current page number.
  162. * @protected
  163. */
  164. protected $page;
  165. /**
  166. * Current object number.
  167. * @protected
  168. */
  169. protected $n;
  170. /**
  171. * Array of object offsets.
  172. * @protected
  173. */
  174. protected $offsets;
  175. /**
  176. * Buffer holding in-memory PDF.
  177. * @protected
  178. */
  179. protected $buffer;
  180. /**
  181. * Array containing pages.
  182. * @protected
  183. */
  184. protected $pages = array();
  185. /**
  186. * Current document state.
  187. * @protected
  188. */
  189. protected $state;
  190. /**
  191. * Compression flag.
  192. * @protected
  193. */
  194. protected $compress;
  195. /**
  196. * Current page orientation (P = Portrait, L = Landscape).
  197. * @protected
  198. */
  199. protected $CurOrientation;
  200. /**
  201. * Page dimensions.
  202. * @protected
  203. */
  204. protected $pagedim = array();
  205. /**
  206. * Scale factor (number of points in user unit).
  207. * @protected
  208. */
  209. protected $k;
  210. /**
  211. * Width of page format in points.
  212. * @protected
  213. */
  214. protected $fwPt;
  215. /**
  216. * Height of page format in points.
  217. * @protected
  218. */
  219. protected $fhPt;
  220. /**
  221. * Current width of page in points.
  222. * @protected
  223. */
  224. protected $wPt;
  225. /**
  226. * Current height of page in points.
  227. * @protected
  228. */
  229. protected $hPt;
  230. /**
  231. * Current width of page in user unit.
  232. * @protected
  233. */
  234. protected $w;
  235. /**
  236. * Current height of page in user unit.
  237. * @protected
  238. */
  239. protected $h;
  240. /**
  241. * Left margin.
  242. * @protected
  243. */
  244. protected $lMargin;
  245. /**
  246. * Top margin.
  247. * @protected
  248. */
  249. protected $tMargin;
  250. /**
  251. * Right margin.
  252. * @protected
  253. */
  254. protected $rMargin;
  255. /**
  256. * Page break margin.
  257. * @protected
  258. */
  259. protected $bMargin;
  260. /**
  261. * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  262. * @since 5.9.000 (2010-10-03)
  263. * @protected
  264. */
  265. protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  266. /**
  267. * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  268. * @since 5.9.000 (2010-10-04)
  269. * @protected
  270. */
  271. protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  272. /**
  273. * Current horizontal position in user unit for cell positioning.
  274. * @protected
  275. */
  276. protected $x;
  277. /**
  278. * Current vertical position in user unit for cell positioning.
  279. * @protected
  280. */
  281. protected $y;
  282. /**
  283. * Height of last cell printed.
  284. * @protected
  285. */
  286. protected $lasth;
  287. /**
  288. * Line width in user unit.
  289. * @protected
  290. */
  291. protected $LineWidth;
  292. /**
  293. * Array of standard font names.
  294. * @protected
  295. */
  296. protected $CoreFonts;
  297. /**
  298. * Array of used fonts.
  299. * @protected
  300. */
  301. protected $fonts = array();
  302. /**
  303. * Array of font files.
  304. * @protected
  305. */
  306. protected $FontFiles = array();
  307. /**
  308. * Array of encoding differences.
  309. * @protected
  310. */
  311. protected $diffs = array();
  312. /**
  313. * Array of used images.
  314. * @protected
  315. */
  316. protected $images = array();
  317. /**
  318. * Array of Annotations in pages.
  319. * @protected
  320. */
  321. protected $PageAnnots = array();
  322. /**
  323. * Array of internal links.
  324. * @protected
  325. */
  326. protected $links = array();
  327. /**
  328. * Current font family.
  329. * @protected
  330. */
  331. protected $FontFamily;
  332. /**
  333. * Current font style.
  334. * @protected
  335. */
  336. protected $FontStyle;
  337. /**
  338. * Current font ascent (distance between font top and baseline).
  339. * @protected
  340. * @since 2.8.000 (2007-03-29)
  341. */
  342. protected $FontAscent;
  343. /**
  344. * Current font descent (distance between font bottom and baseline).
  345. * @protected
  346. * @since 2.8.000 (2007-03-29)
  347. */
  348. protected $FontDescent;
  349. /**
  350. * Underlining flag.
  351. * @protected
  352. */
  353. protected $underline;
  354. /**
  355. * Overlining flag.
  356. * @protected
  357. */
  358. protected $overline;
  359. /**
  360. * Current font info.
  361. * @protected
  362. */
  363. protected $CurrentFont;
  364. /**
  365. * Current font size in points.
  366. * @protected
  367. */
  368. protected $FontSizePt;
  369. /**
  370. * Current font size in user unit.
  371. * @protected
  372. */
  373. protected $FontSize;
  374. /**
  375. * Commands for drawing color.
  376. * @protected
  377. */
  378. protected $DrawColor;
  379. /**
  380. * Commands for filling color.
  381. * @protected
  382. */
  383. protected $FillColor;
  384. /**
  385. * Commands for text color.
  386. * @protected
  387. */
  388. protected $TextColor;
  389. /**
  390. * Indicates whether fill and text colors are different.
  391. * @protected
  392. */
  393. protected $ColorFlag;
  394. /**
  395. * Automatic page breaking.
  396. * @protected
  397. */
  398. protected $AutoPageBreak;
  399. /**
  400. * Threshold used to trigger page breaks.
  401. * @protected
  402. */
  403. protected $PageBreakTrigger;
  404. /**
  405. * Flag set when processing page header.
  406. * @protected
  407. */
  408. protected $InHeader = false;
  409. /**
  410. * Flag set when processing page footer.
  411. * @protected
  412. */
  413. protected $InFooter = false;
  414. /**
  415. * Zoom display mode.
  416. * @protected
  417. */
  418. protected $ZoomMode;
  419. /**
  420. * Layout display mode.
  421. * @protected
  422. */
  423. protected $LayoutMode;
  424. /**
  425. * If true set the document information dictionary in Unicode.
  426. * @protected
  427. */
  428. protected $docinfounicode = true;
  429. /**
  430. * Document title.
  431. * @protected
  432. */
  433. protected $title = '';
  434. /**
  435. * Document subject.
  436. * @protected
  437. */
  438. protected $subject = '';
  439. /**
  440. * Document author.
  441. * @protected
  442. */
  443. protected $author = '';
  444. /**
  445. * Document keywords.
  446. * @protected
  447. */
  448. protected $keywords = '';
  449. /**
  450. * Document creator.
  451. * @protected
  452. */
  453. protected $creator = '';
  454. /**
  455. * Starting page number.
  456. * @protected
  457. */
  458. protected $starting_page_number = 1;
  459. /**
  460. * String alias for total number of pages.
  461. * @protected
  462. */
  463. protected $alias_tot_pages = '{:ptp:}';
  464. /**
  465. * String alias for page number.
  466. * @protected
  467. */
  468. protected $alias_num_page = '{:pnp:}';
  469. /**
  470. * String alias for total number of pages in a single group.
  471. * @protected
  472. */
  473. protected $alias_group_tot_pages = '{:ptg:}';
  474. /**
  475. * String alias for group page number.
  476. * @protected
  477. */
  478. protected $alias_group_num_page = '{:png:}';
  479. /**
  480. * String alias for right shift compensation used to correctly align page numbers on the right.
  481. * @protected
  482. */
  483. protected $alias_right_shift = '{rsc:';
  484. /**
  485. * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
  486. * @since 2002-07-31
  487. * @author Nicola Asuni
  488. * @protected
  489. */
  490. protected $img_rb_x;
  491. /**
  492. * The right-bottom corner Y coordinate of last inserted image.
  493. * @since 2002-07-31
  494. * @author Nicola Asuni
  495. * @protected
  496. */
  497. protected $img_rb_y;
  498. /**
  499. * Adjusting factor to convert pixels to user units.
  500. * @since 2004-06-14
  501. * @author Nicola Asuni
  502. * @protected
  503. */
  504. protected $imgscale = 1;
  505. /**
  506. * Boolean flag set to true when the input text is unicode (require unicode fonts).
  507. * @since 2005-01-02
  508. * @author Nicola Asuni
  509. * @protected
  510. */
  511. protected $isunicode = false;
  512. /**
  513. * Object containing unicode data.
  514. * @since 5.9.004 (2010-10-18)
  515. * @author Nicola Asuni
  516. * @protected
  517. */
  518. protected $unicode;
  519. /**
  520. * Object containing font encoding maps.
  521. * @since 5.9.123 (2011-10-01)
  522. * @author Nicola Asuni
  523. * @protected
  524. */
  525. protected $encmaps;
  526. /**
  527. * PDF version.
  528. * @since 1.5.3
  529. * @protected
  530. */
  531. protected $PDFVersion = '1.7';
  532. /**
  533. * ID of the stored default header template (-1 = not set).
  534. * @protected
  535. */
  536. protected $header_xobjid = -1;
  537. /**
  538. * If true reset the Header Xobject template at each page
  539. * @protected
  540. */
  541. protected $header_xobj_autoreset = false;
  542. /**
  543. * Minimum distance between header and top page margin.
  544. * @protected
  545. */
  546. protected $header_margin;
  547. /**
  548. * Minimum distance between footer and bottom page margin.
  549. * @protected
  550. */
  551. protected $footer_margin;
  552. /**
  553. * Original left margin value.
  554. * @protected
  555. * @since 1.53.0.TC013
  556. */
  557. protected $original_lMargin;
  558. /**
  559. * Original right margin value.
  560. * @protected
  561. * @since 1.53.0.TC013
  562. */
  563. protected $original_rMargin;
  564. /**
  565. * Default font used on page header.
  566. * @protected
  567. */
  568. protected $header_font;
  569. /**
  570. * Default font used on page footer.
  571. * @protected
  572. */
  573. protected $footer_font;
  574. /**
  575. * Language templates.
  576. * @protected
  577. */
  578. protected $l;
  579. /**
  580. * Barcode to print on page footer (only if set).
  581. * @protected
  582. */
  583. protected $barcode = false;
  584. /**
  585. * Boolean flag to print/hide page header.
  586. * @protected
  587. */
  588. protected $print_header = true;
  589. /**
  590. * Boolean flag to print/hide page footer.
  591. * @protected
  592. */
  593. protected $print_footer = true;
  594. /**
  595. * Header image logo.
  596. * @protected
  597. */
  598. protected $header_logo = '';
  599. /**
  600. * Width of header image logo in user units.
  601. * @protected
  602. */
  603. protected $header_logo_width = 30;
  604. /**
  605. * Title to be printed on default page header.
  606. * @protected
  607. */
  608. protected $header_title = '';
  609. /**
  610. * String to pring on page header after title.
  611. * @protected
  612. */
  613. protected $header_string = '';
  614. /**
  615. * Default number of columns for html table.
  616. * @protected
  617. */
  618. protected $default_table_columns = 4;
  619. // variables for html parser
  620. /**
  621. * HTML PARSER: array to store current link and rendering styles.
  622. * @protected
  623. */
  624. protected $HREF = array();
  625. /**
  626. * List of available fonts on filesystem.
  627. * @protected
  628. */
  629. protected $fontlist = array();
  630. /**
  631. * Current foreground color.
  632. * @protected
  633. */
  634. protected $fgcolor;
  635. /**
  636. * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
  637. * @protected
  638. */
  639. protected $listordered = array();
  640. /**
  641. * HTML PARSER: array count list items on nested lists.
  642. * @protected
  643. */
  644. protected $listcount = array();
  645. /**
  646. * HTML PARSER: current list nesting level.
  647. * @protected
  648. */
  649. protected $listnum = 0;
  650. /**
  651. * HTML PARSER: indent amount for lists.
  652. * @protected
  653. */
  654. protected $listindent = 0;
  655. /**
  656. * HTML PARSER: current list indententation level.
  657. * @protected
  658. */
  659. protected $listindentlevel = 0;
  660. /**
  661. * Current background color.
  662. * @protected
  663. */
  664. protected $bgcolor;
  665. /**
  666. * Temporary font size in points.
  667. * @protected
  668. */
  669. protected $tempfontsize = 10;
  670. /**
  671. * Spacer string for LI tags.
  672. * @protected
  673. */
  674. protected $lispacer = '';
  675. /**
  676. * Default encoding.
  677. * @protected
  678. * @since 1.53.0.TC010
  679. */
  680. protected $encoding = 'UTF-8';
  681. /**
  682. * PHP internal encoding.
  683. * @protected
  684. * @since 1.53.0.TC016
  685. */
  686. protected $internal_encoding;
  687. /**
  688. * Boolean flag to indicate if the document language is Right-To-Left.
  689. * @protected
  690. * @since 2.0.000
  691. */
  692. protected $rtl = false;
  693. /**
  694. * Boolean flag used to force RTL or LTR string direction.
  695. * @protected
  696. * @since 2.0.000
  697. */
  698. protected $tmprtl = false;
  699. // --- Variables used for document encryption:
  700. /**
  701. * IBoolean flag indicating whether document is protected.
  702. * @protected
  703. * @since 2.0.000 (2008-01-02)
  704. */
  705. protected $encrypted;
  706. /**
  707. * Array containing encryption settings.
  708. * @protected
  709. * @since 5.0.005 (2010-05-11)
  710. */
  711. protected $encryptdata = array();
  712. /**
  713. * Last RC4 key encrypted (cached for optimisation).
  714. * @protected
  715. * @since 2.0.000 (2008-01-02)
  716. */
  717. protected $last_enc_key;
  718. /**
  719. * Last RC4 computed key.
  720. * @protected
  721. * @since 2.0.000 (2008-01-02)
  722. */
  723. protected $last_enc_key_c;
  724. /**
  725. * Encryption padding string.
  726. * @protected
  727. */
  728. protected $enc_padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
  729. /**
  730. * File ID (used on document trailer).
  731. * @protected
  732. * @since 5.0.005 (2010-05-12)
  733. */
  734. protected $file_id;
  735. // --- bookmark ---
  736. /**
  737. * Outlines for bookmark.
  738. * @protected
  739. * @since 2.1.002 (2008-02-12)
  740. */
  741. protected $outlines = array();
  742. /**
  743. * Outline root for bookmark.
  744. * @protected
  745. * @since 2.1.002 (2008-02-12)
  746. */
  747. protected $OutlineRoot;
  748. // --- javascript and form ---
  749. /**
  750. * Javascript code.
  751. * @protected
  752. * @since 2.1.002 (2008-02-12)
  753. */
  754. protected $javascript = '';
  755. /**
  756. * Javascript counter.
  757. * @protected
  758. * @since 2.1.002 (2008-02-12)
  759. */
  760. protected $n_js;
  761. /**
  762. * line trough state
  763. * @protected
  764. * @since 2.8.000 (2008-03-19)
  765. */
  766. protected $linethrough;
  767. /**
  768. * Array with additional document-wide usage rights for the document.
  769. * @protected
  770. * @since 5.8.014 (2010-08-23)
  771. */
  772. protected $ur = array();
  773. /**
  774. * DPI (Dot Per Inch) Document Resolution (do not change).
  775. * @protected
  776. * @since 3.0.000 (2008-03-27)
  777. */
  778. protected $dpi = 72;
  779. /**
  780. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  781. * @protected
  782. * @since 3.0.000 (2008-03-27)
  783. */
  784. protected $newpagegroup = array();
  785. /**
  786. * Array that contains the number of pages in each page group.
  787. * @protected
  788. * @since 3.0.000 (2008-03-27)
  789. */
  790. protected $pagegroups = array();
  791. /**
  792. * Current page group number.
  793. * @protected
  794. * @since 3.0.000 (2008-03-27)
  795. */
  796. protected $currpagegroup = 0;
  797. /**
  798. * Array of transparency objects and parameters.
  799. * @protected
  800. * @since 3.0.000 (2008-03-27)
  801. */
  802. protected $extgstates;
  803. /**
  804. * Set the default JPEG compression quality (1-100).
  805. * @protected
  806. * @since 3.0.000 (2008-03-27)
  807. */
  808. protected $jpeg_quality;
  809. /**
  810. * Default cell height ratio.
  811. * @protected
  812. * @since 3.0.014 (2008-05-23)
  813. */
  814. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  815. /**
  816. * PDF viewer preferences.
  817. * @protected
  818. * @since 3.1.000 (2008-06-09)
  819. */
  820. protected $viewer_preferences;
  821. /**
  822. * A name object specifying how the document should be displayed when opened.
  823. * @protected
  824. * @since 3.1.000 (2008-06-09)
  825. */
  826. protected $PageMode;
  827. /**
  828. * Array for storing gradient information.
  829. * @protected
  830. * @since 3.1.000 (2008-06-09)
  831. */
  832. protected $gradients = array();
  833. /**
  834. * Array used to store positions inside the pages buffer (keys are the page numbers).
  835. * @protected
  836. * @since 3.2.000 (2008-06-26)
  837. */
  838. protected $intmrk = array();
  839. /**
  840. * Array used to store positions inside the pages buffer (keys are the page numbers).
  841. * @protected
  842. * @since 5.7.000 (2010-08-03)
  843. */
  844. protected $bordermrk = array();
  845. /**
  846. * Array used to store page positions to track empty pages (keys are the page numbers).
  847. * @protected
  848. * @since 5.8.007 (2010-08-18)
  849. */
  850. protected $emptypagemrk = array();
  851. /**
  852. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  853. * @protected
  854. * @since 4.6.021 (2009-07-20)
  855. */
  856. protected $cntmrk = array();
  857. /**
  858. * Array used to store footer positions of each page.
  859. * @protected
  860. * @since 3.2.000 (2008-07-01)
  861. */
  862. protected $footerpos = array();
  863. /**
  864. * Array used to store footer length of each page.
  865. * @protected
  866. * @since 4.0.014 (2008-07-29)
  867. */
  868. protected $footerlen = array();
  869. /**
  870. * Boolean flag to indicate if a new line is created.
  871. * @protected
  872. * @since 3.2.000 (2008-07-01)
  873. */
  874. protected $newline = true;
  875. /**
  876. * End position of the latest inserted line.
  877. * @protected
  878. * @since 3.2.000 (2008-07-01)
  879. */
  880. protected $endlinex = 0;
  881. /**
  882. * PDF string for width value of the last line.
  883. * @protected
  884. * @since 4.0.006 (2008-07-16)
  885. */
  886. protected $linestyleWidth = '';
  887. /**
  888. * PDF string for CAP value of the last line.
  889. * @protected
  890. * @since 4.0.006 (2008-07-16)
  891. */
  892. protected $linestyleCap = '0 J';
  893. /**
  894. * PDF string for join value of the last line.
  895. * @protected
  896. * @since 4.0.006 (2008-07-16)
  897. */
  898. protected $linestyleJoin = '0 j';
  899. /**
  900. * PDF string for dash value of the last line.
  901. * @protected
  902. * @since 4.0.006 (2008-07-16)
  903. */
  904. protected $linestyleDash = '[] 0 d';
  905. /**
  906. * Boolean flag to indicate if marked-content sequence is open.
  907. * @protected
  908. * @since 4.0.013 (2008-07-28)
  909. */
  910. protected $openMarkedContent = false;
  911. /**
  912. * Count the latest inserted vertical spaces on HTML.
  913. * @protected
  914. * @since 4.0.021 (2008-08-24)
  915. */
  916. protected $htmlvspace = 0;
  917. /**
  918. * Array of Spot colors.
  919. * @protected
  920. * @since 4.0.024 (2008-09-12)
  921. */
  922. protected $spot_colors = array();
  923. /**
  924. * Symbol used for HTML unordered list items.
  925. * @protected
  926. * @since 4.0.028 (2008-09-26)
  927. */
  928. protected $lisymbol = '';
  929. /**
  930. * String used to mark the beginning and end of EPS image blocks.
  931. * @protected
  932. * @since 4.1.000 (2008-10-18)
  933. */
  934. protected $epsmarker = 'x#!#EPS#!#x';
  935. /**
  936. * Array of transformation matrix.
  937. * @protected
  938. * @since 4.2.000 (2008-10-29)
  939. */
  940. protected $transfmatrix = array();
  941. /**
  942. * Current key for transformation matrix.
  943. * @protected
  944. * @since 4.8.005 (2009-09-17)
  945. */
  946. protected $transfmatrix_key = 0;
  947. /**
  948. * Booklet mode for double-sided pages.
  949. * @protected
  950. * @since 4.2.000 (2008-10-29)
  951. */
  952. protected $booklet = false;
  953. /**
  954. * Epsilon value used for float calculations.
  955. * @protected
  956. * @since 4.2.000 (2008-10-29)
  957. */
  958. protected $feps = 0.005;
  959. /**
  960. * Array used for custom vertical spaces for HTML tags.
  961. * @protected
  962. * @since 4.2.001 (2008-10-30)
  963. */
  964. protected $tagvspaces = array();
  965. /**
  966. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  967. * @protected
  968. * @since 4.2.007 (2008-11-12)
  969. */
  970. protected $customlistindent = -1;
  971. /**
  972. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  973. * @protected
  974. * @since 4.2.010 (2008-11-14)
  975. */
  976. protected $opencell = true;
  977. /**
  978. * Array of files to embedd.
  979. * @protected
  980. * @since 4.4.000 (2008-12-07)
  981. */
  982. protected $embeddedfiles = array();
  983. /**
  984. * Boolean flag to indicate if we are inside a PRE tag.
  985. * @protected
  986. * @since 4.4.001 (2008-12-08)
  987. */
  988. protected $premode = false;
  989. /**
  990. * Array used to store positions of graphics transformation blocks inside the page buffer.
  991. * keys are the page numbers
  992. * @protected
  993. * @since 4.4.002 (2008-12-09)
  994. */
  995. protected $transfmrk = array();
  996. /**
  997. * Default color for html links.
  998. * @protected
  999. * @since 4.4.003 (2008-12-09)
  1000. */
  1001. protected $htmlLinkColorArray = array(0, 0, 255);
  1002. /**
  1003. * Default font style to add to html links.
  1004. * @protected
  1005. * @since 4.4.003 (2008-12-09)
  1006. */
  1007. protected $htmlLinkFontStyle = 'U';
  1008. /**
  1009. * Counts the number of pages.
  1010. * @protected
  1011. * @since 4.5.000 (2008-12-31)
  1012. */
  1013. protected $numpages = 0;
  1014. /**
  1015. * Array containing page lengths in bytes.
  1016. * @protected
  1017. * @since 4.5.000 (2008-12-31)
  1018. */
  1019. protected $pagelen = array();
  1020. /**
  1021. * Counts the number of pages.
  1022. * @protected
  1023. * @since 4.5.000 (2008-12-31)
  1024. */
  1025. protected $numimages = 0;
  1026. /**
  1027. * Store the image keys.
  1028. * @protected
  1029. * @since 4.5.000 (2008-12-31)
  1030. */
  1031. protected $imagekeys = array();
  1032. /**
  1033. * Length of the buffer in bytes.
  1034. * @protected
  1035. * @since 4.5.000 (2008-12-31)
  1036. */
  1037. protected $bufferlen = 0;
  1038. /**
  1039. * If true enables disk caching.
  1040. * @protected
  1041. * @since 4.5.000 (2008-12-31)
  1042. */
  1043. protected $diskcache = false;
  1044. /**
  1045. * Counts the number of fonts.
  1046. * @protected
  1047. * @since 4.5.000 (2009-01-02)
  1048. */
  1049. protected $numfonts = 0;
  1050. /**
  1051. * Store the font keys.
  1052. * @protected
  1053. * @since 4.5.000 (2009-01-02)
  1054. */
  1055. protected $fontkeys = array();
  1056. /**
  1057. * Store the font object IDs.
  1058. * @protected
  1059. * @since 4.8.001 (2009-09-09)
  1060. */
  1061. protected $font_obj_ids = array();
  1062. /**
  1063. * Store the fage status (true when opened, false when closed).
  1064. * @protected
  1065. * @since 4.5.000 (2009-01-02)
  1066. */
  1067. protected $pageopen = array();
  1068. /**
  1069. * Default monospace font.
  1070. * @protected
  1071. * @since 4.5.025 (2009-03-10)
  1072. */
  1073. protected $default_monospaced_font = 'courier';
  1074. /**
  1075. * Cloned copy of the current class object.
  1076. * @protected
  1077. * @since 4.5.029 (2009-03-19)
  1078. */
  1079. protected $objcopy;
  1080. /**
  1081. * Array used to store the lengths of cache files.
  1082. * @protected
  1083. * @since 4.5.029 (2009-03-19)
  1084. */
  1085. protected $cache_file_length = array();
  1086. /**
  1087. * Table header content to be repeated on each new page.
  1088. * @protected
  1089. * @since 4.5.030 (2009-03-20)
  1090. */
  1091. protected $thead = '';
  1092. /**
  1093. * Margins used for table header.
  1094. * @protected
  1095. * @since 4.5.030 (2009-03-20)
  1096. */
  1097. protected $theadMargins = array();
  1098. /**
  1099. * Cache array for UTF8StringToArray() method.
  1100. * @protected
  1101. * @since 4.5.037 (2009-04-07)
  1102. */
  1103. protected $cache_UTF8StringToArray = array();
  1104. /**
  1105. * Maximum size of cache array used for UTF8StringToArray() method.
  1106. * @protected
  1107. * @since 4.5.037 (2009-04-07)
  1108. */
  1109. protected $cache_maxsize_UTF8StringToArray = 8;
  1110. /**
  1111. * Current size of cache array used for UTF8StringToArray() method.
  1112. * @protected
  1113. * @since 4.5.037 (2009-04-07)
  1114. */
  1115. protected $cache_size_UTF8StringToArray = 0;
  1116. /**
  1117. * Boolean flag to enable document digital signature.
  1118. * @protected
  1119. * @since 4.6.005 (2009-04-24)
  1120. */
  1121. protected $sign = false;
  1122. /**
  1123. * Digital signature data.
  1124. * @protected
  1125. * @since 4.6.005 (2009-04-24)
  1126. */
  1127. protected $signature_data = array();
  1128. /**
  1129. * Digital signature max length.
  1130. * @protected
  1131. * @since 4.6.005 (2009-04-24)
  1132. */
  1133. protected $signature_max_length = 11742;
  1134. /**
  1135. * Data for digital signature appearance.
  1136. * @protected
  1137. * @since 5.3.011 (2010-06-16)
  1138. */
  1139. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1140. /**
  1141. * Array of empty digital signature appearances.
  1142. * @protected
  1143. * @since 5.9.101 (2011-07-06)
  1144. */
  1145. protected $empty_signature_appearance = array();
  1146. /**
  1147. * Regular expression used to find blank characters (required for word-wrapping).
  1148. * @protected
  1149. * @since 4.6.006 (2009-04-28)
  1150. */
  1151. protected $re_spaces = '/[^\S\xa0]/';
  1152. /**
  1153. * Array of $re_spaces parts.
  1154. * @protected
  1155. * @since 5.5.011 (2010-07-09)
  1156. */
  1157. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1158. /**
  1159. * Digital signature object ID.
  1160. * @protected
  1161. * @since 4.6.022 (2009-06-23)
  1162. */
  1163. protected $sig_obj_id = 0;
  1164. /**
  1165. * ByteRange placemark used during digital signature process.
  1166. * @protected
  1167. * @since 4.6.028 (2009-08-25)
  1168. */
  1169. protected $byterange_string = '/ByteRange[0 ********** ********** **********]';
  1170. /**
  1171. * Placemark used during digital signature process.
  1172. * @protected
  1173. * @since 4.6.028 (2009-08-25)
  1174. */
  1175. protected $sig_annot_ref = '***SIGANNREF*** 0 R';
  1176. /**
  1177. * ID of page objects.
  1178. * @protected
  1179. * @since 4.7.000 (2009-08-29)
  1180. */
  1181. protected $page_obj_id = array();
  1182. /**
  1183. * List of form annotations IDs.
  1184. * @protected
  1185. * @since 4.8.000 (2009-09-07)
  1186. */
  1187. protected $form_obj_id = array();
  1188. /**
  1189. * 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.
  1190. * @protected
  1191. * @since 4.8.000 (2009-09-07)
  1192. */
  1193. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1194. /**
  1195. * Javascript objects array.
  1196. * @protected
  1197. * @since 4.8.000 (2009-09-07)
  1198. */
  1199. protected $js_objects = array();
  1200. /**
  1201. * Current form action (used during XHTML rendering).
  1202. * @protected
  1203. * @since 4.8.000 (2009-09-07)
  1204. */
  1205. protected $form_action = '';
  1206. /**
  1207. * Current form encryption type (used during XHTML rendering).
  1208. * @protected
  1209. * @since 4.8.000 (2009-09-07)
  1210. */
  1211. protected $form_enctype = 'application/x-www-form-urlencoded';
  1212. /**
  1213. * Current method to submit forms.
  1214. * @protected
  1215. * @since 4.8.000 (2009-09-07)
  1216. */
  1217. protected $form_mode = 'post';
  1218. /**
  1219. * List of fonts used on form fields (fontname => fontkey).
  1220. * @protected
  1221. * @since 4.8.001 (2009-09-09)
  1222. */
  1223. protected $annotation_fonts = array();
  1224. /**
  1225. * List of radio buttons parent objects.
  1226. * @protected
  1227. * @since 4.8.001 (2009-09-09)
  1228. */
  1229. protected $radiobutton_groups = array();
  1230. /**
  1231. * List of radio group objects IDs.
  1232. * @protected
  1233. * @since 4.8.001 (2009-09-09)
  1234. */
  1235. protected $radio_groups = array();
  1236. /**
  1237. * Text indentation value (used for text-indent CSS attribute).
  1238. * @protected
  1239. * @since 4.8.006 (2009-09-23)
  1240. */
  1241. protected $textindent = 0;
  1242. /**
  1243. * Store page number when startTransaction() is called.
  1244. * @protected
  1245. * @since 4.8.006 (2009-09-23)
  1246. */
  1247. protected $start_transaction_page = 0;
  1248. /**
  1249. * Store Y position when startTransaction() is called.
  1250. * @protected
  1251. * @since 4.9.001 (2010-03-28)
  1252. */
  1253. protected $start_transaction_y = 0;
  1254. /**
  1255. * True when we are printing the thead section on a new page.
  1256. * @protected
  1257. * @since 4.8.027 (2010-01-25)
  1258. */
  1259. protected $inthead = false;
  1260. /**
  1261. * Array of column measures (width, space, starting Y position).
  1262. * @protected
  1263. * @since 4.9.001 (2010-03-28)
  1264. */
  1265. protected $columns = array();
  1266. /**
  1267. * Number of colums.
  1268. * @protected
  1269. * @since 4.9.001 (2010-03-28)
  1270. */
  1271. protected $num_columns = 1;
  1272. /**
  1273. * Current column number.
  1274. * @protected
  1275. * @since 4.9.001 (2010-03-28)
  1276. */
  1277. protected $current_column = 0;
  1278. /**
  1279. * Starting page for columns.
  1280. * @protected
  1281. * @since 4.9.001 (2010-03-28)
  1282. */
  1283. protected $column_start_page = 0;
  1284. /**
  1285. * Maximum page and column selected.
  1286. * @protected
  1287. * @since 5.8.000 (2010-08-11)
  1288. */
  1289. protected $maxselcol = array('page' => 0, 'column' => 0);
  1290. /**
  1291. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1292. * @protected
  1293. * @since 5.8.000 (2010-08-11)
  1294. */
  1295. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1296. /**
  1297. * 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.
  1298. * @protected
  1299. * @since 4.9.008 (2010-04-03)
  1300. */
  1301. protected $textrendermode = 0;
  1302. /**
  1303. * Text stroke width in doc units.
  1304. * @protected
  1305. * @since 4.9.008 (2010-04-03)
  1306. */
  1307. protected $textstrokewidth = 0;
  1308. /**
  1309. * Current stroke color.
  1310. * @protected
  1311. * @since 4.9.008 (2010-04-03)
  1312. */
  1313. protected $strokecolor;
  1314. /**
  1315. * Default unit of measure for document.
  1316. * @protected
  1317. * @since 5.0.000 (2010-04-22)
  1318. */
  1319. protected $pdfunit = 'mm';
  1320. /**
  1321. * Boolean flag true when we are on TOC (Table Of Content) page.
  1322. * @protected
  1323. */
  1324. protected $tocpage = false;
  1325. /**
  1326. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1327. * @protected
  1328. * @since 5.0.000 (2010-04-26)
  1329. */
  1330. protected $rasterize_vector_images = false;
  1331. /**
  1332. * Boolean flag: if true enables font subsetting by default.
  1333. * @protected
  1334. * @since 5.3.002 (2010-06-07)
  1335. */
  1336. protected $font_subsetting = true;
  1337. /**
  1338. * Array of default graphic settings.
  1339. * @protected
  1340. * @since 5.5.008 (2010-07-02)
  1341. */
  1342. protected $default_graphic_vars = array();
  1343. /**
  1344. * Array of XObjects.
  1345. * @protected
  1346. * @since 5.8.014 (2010-08-23)
  1347. */
  1348. protected $xobjects = array();
  1349. /**
  1350. * Boolean value true when we are inside an XObject.
  1351. * @protected
  1352. * @since 5.8.017 (2010-08-24)
  1353. */
  1354. protected $inxobj = false;
  1355. /**
  1356. * Current XObject ID.
  1357. * @protected
  1358. * @since 5.8.017 (2010-08-24)
  1359. */
  1360. protected $xobjid = '';
  1361. /**
  1362. * Percentage of character stretching.
  1363. * @protected
  1364. * @since 5.9.000 (2010-09-29)
  1365. */
  1366. protected $font_stretching = 100;
  1367. /**
  1368. * Increases or decreases the space between characters in a text by the specified amount (tracking/kerning).
  1369. * @protected
  1370. * @since 5.9.000 (2010-09-29)
  1371. */
  1372. protected $font_spacing = 0;
  1373. /**
  1374. * Array of no-write regions.
  1375. * ('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)
  1376. * @protected
  1377. * @since 5.9.003 (2010-10-14)
  1378. */
  1379. protected $page_regions = array();
  1380. /**
  1381. * Array containing HTML color names and values.
  1382. * @protected
  1383. * @since 5.9.004 (2010-10-18)
  1384. */
  1385. protected $webcolor = array();
  1386. /**
  1387. * Array containing spot color names and values.
  1388. * @protected
  1389. * @since 5.9.012 (2010-11-11)
  1390. */
  1391. protected $spotcolor = array();
  1392. /**
  1393. * Array of PDF layers data.
  1394. * @protected
  1395. * @since 5.9.102 (2011-07-13)
  1396. */
  1397. protected $pdflayers = array();
  1398. /**
  1399. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1400. * @protected
  1401. * @since 5.9.097 (2011-06-23)
  1402. */
  1403. protected $dests = array();
  1404. /**
  1405. * Object ID for Named Destinations
  1406. * @protected
  1407. * @since 5.9.097 (2011-06-23)
  1408. */
  1409. protected $n_dests;
  1410. /**
  1411. * Directory used for the last SVG image.
  1412. * @protected
  1413. * @since 5.0.000 (2010-05-05)
  1414. */
  1415. protected $svgdir = '';
  1416. /**
  1417. * Deafult unit of measure for SVG.
  1418. * @protected
  1419. * @since 5.0.000 (2010-05-02)
  1420. */
  1421. protected $svgunit = 'px';
  1422. /**
  1423. * Array of SVG gradients.
  1424. * @protected
  1425. * @since 5.0.000 (2010-05-02)
  1426. */
  1427. protected $svggradients = array();
  1428. /**
  1429. * ID of last SVG gradient.
  1430. * @protected
  1431. * @since 5.0.000 (2010-05-02)
  1432. */
  1433. protected $svggradientid = 0;
  1434. /**
  1435. * Boolean value true when in SVG defs group.
  1436. * @protected
  1437. * @since 5.0.000 (2010-05-02)
  1438. */
  1439. protected $svgdefsmode = false;
  1440. /**
  1441. * Array of SVG defs.
  1442. * @protected
  1443. * @since 5.0.000 (2010-05-02)
  1444. */
  1445. protected $svgdefs = array();
  1446. /**
  1447. * Boolean value true when in SVG clipPath tag.
  1448. * @protected
  1449. * @since 5.0.000 (2010-04-26)
  1450. */
  1451. protected $svgclipmode = false;
  1452. /**
  1453. * Array of SVG clipPath commands.
  1454. * @protected
  1455. * @since 5.0.000 (2010-05-02)
  1456. */
  1457. protected $svgclippaths = array();
  1458. /**
  1459. * Array of SVG clipPath tranformation matrix.
  1460. * @protected
  1461. * @since 5.8.022 (2010-08-31)
  1462. */
  1463. protected $svgcliptm = array();
  1464. /**
  1465. * ID of last SVG clipPath.
  1466. * @protected
  1467. * @since 5.0.000 (2010-05-02)
  1468. */
  1469. protected $svgclipid = 0;
  1470. /**
  1471. * SVG text.
  1472. * @protected
  1473. * @since 5.0.000 (2010-05-02)
  1474. */
  1475. protected $svgtext = '';
  1476. /**
  1477. * SVG text properties.
  1478. * @protected
  1479. * @since 5.8.013 (2010-08-23)
  1480. */
  1481. protected $svgtextmode = array();
  1482. /**
  1483. * Array of hinheritable SVG properties.
  1484. * @protected
  1485. * @since 5.0.000 (2010-05-02)
  1486. */
  1487. protected $svginheritprop = array('clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cursor', 'direction', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'image-rendering', 'kerning', 'letter-spacing', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode');
  1488. /**
  1489. * Array of SVG properties.
  1490. * @protected
  1491. * @since 5.0.000 (2010-05-02)
  1492. */
  1493. protected $svgstyles = array(array(
  1494. 'alignment-baseline' => 'auto',
  1495. 'baseline-shift' => 'baseline',
  1496. 'clip' => 'auto',
  1497. 'clip-path' => 'none',
  1498. 'clip-rule' => 'nonzero',
  1499. 'color' => 'black',
  1500. 'color-interpolation' => 'sRGB',
  1501. 'color-interpolation-filters' => 'linearRGB',
  1502. 'color-profile' => 'auto',
  1503. 'color-rendering' => 'auto',
  1504. 'cursor' => 'auto',
  1505. 'direction' => 'ltr',
  1506. 'display' => 'inline',
  1507. 'dominant-baseline' => 'auto',
  1508. 'enable-background' => 'accumulate',
  1509. 'fill' => 'black',
  1510. 'fill-opacity' => 1,
  1511. 'fill-rule' => 'nonzero',
  1512. 'filter' => 'none',
  1513. 'flood-color' => 'black',
  1514. 'flood-opacity' => 1,
  1515. 'font' => '',
  1516. 'font-family' => 'helvetica',
  1517. 'font-size' => 'medium',
  1518. 'font-size-adjust' => 'none',
  1519. 'font-stretch' => 'normal',
  1520. 'font-style' => 'normal',
  1521. 'font-variant' => 'normal',
  1522. 'font-weight' => 'normal',
  1523. 'glyph-orientation-horizontal' => '0deg',
  1524. 'glyph-orientation-vertical' => 'auto',
  1525. 'image-rendering' => 'auto',
  1526. 'kerning' => 'auto',
  1527. 'letter-spacing' => 'normal',
  1528. 'lighting-color' => 'white',
  1529. 'marker' => '',
  1530. 'marker-end' => 'none',
  1531. 'marker-mid' => 'none',
  1532. 'marker-start' => 'none',
  1533. 'mask' => 'none',
  1534. 'opacity' => 1,
  1535. 'overflow' => 'auto',
  1536. 'pointer-events' => 'visiblePainted',
  1537. 'shape-rendering' => 'auto',
  1538. 'stop-color' => 'black',
  1539. 'stop-opacity' => 1,
  1540. 'stroke' => 'none',
  1541. 'stroke-dasharray' => 'none',
  1542. 'stroke-dashoffset' => 0,
  1543. 'stroke-linecap' => 'butt',
  1544. 'stroke-linejoin' => 'miter',
  1545. 'stroke-miterlimit' => 4,
  1546. 'stroke-opacity' => 1,
  1547. 'stroke-width' => 1,
  1548. 'text-anchor' => 'start',
  1549. 'text-decoration' => 'none',
  1550. 'text-rendering' => 'auto',
  1551. 'unicode-bidi' => 'normal',
  1552. 'visibility' => 'visible',
  1553. 'word-spacing' => 'normal',
  1554. 'writing-mode' => 'lr-tb',
  1555. 'text-color' => 'black',
  1556. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1557. ));
  1558. /**
  1559. * If true force sRGB color profile for all document.
  1560. * @protected
  1561. * @since 5.9.121 (2011-09-28)
  1562. */
  1563. protected $force_srgb = false;
  1564. /**
  1565. * If true set the document to PDF/A mode.
  1566. * @protected
  1567. * @since 5.9.121 (2011-09-27)
  1568. */
  1569. protected $pdfa_mode = false;
  1570. /**
  1571. * Document creation date
  1572. * @protected
  1573. * @since 5.9.121 (2011-09-28)
  1574. */
  1575. protected $doc_date;
  1576. /**
  1577. * Custom XMP data.
  1578. * @protected
  1579. * @since 5.9.128 (2011-10-06)
  1580. */
  1581. protected $custom_xmp = '';
  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. * @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>
  1589. * @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.
  1590. * @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().
  1591. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1592. * @param $encoding (string) Charset encoding; default is UTF-8.
  1593. * @param $diskcache (boolean) If TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
  1594. * @param $pdfa (boolean) If TRUE set the document to PDF/A mode.
  1595. * @public
  1596. * @see getPageSizeFromFormat(), setPageFormat()
  1597. */
  1598. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1599. /* Set internal character encoding to ASCII */
  1600. if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
  1601. $this->internal_encoding = mb_internal_encoding();
  1602. mb_internal_encoding('ASCII');
  1603. }
  1604. // get array of HTML colors
  1605. require(dirname(__FILE__).'/htmlcolors.php');
  1606. $this->webcolor = $webcolor;
  1607. // get array of custom spot colors
  1608. if (file_exists(dirname(__FILE__).'/spotcolors.php')) {
  1609. require(dirname(__FILE__).'/spotcolors.php');
  1610. $this->spotcolor = $spotcolor;
  1611. } else {
  1612. $this->spotcolor = array();
  1613. }
  1614. require_once(dirname(__FILE__).'/unicode_data.php');
  1615. $this->unicode = new TCPDF_UNICODE_DATA();
  1616. require_once(dirname(__FILE__).'/encodings_maps.php');
  1617. $this->encmaps = new TCPDF_ENCODING_MAPS();
  1618. $this->font_obj_ids = array();
  1619. $this->page_obj_id = array();
  1620. $this->form_obj_id = array();
  1621. // set pdf/a mode
  1622. $this->pdfa_mode = $pdfa;
  1623. $this->force_srgb = false;
  1624. // set disk caching
  1625. $this->diskcache = $diskcache ? true : false;
  1626. // set language direction
  1627. $this->rtl = false;
  1628. $this->tmprtl = false;
  1629. // some checks
  1630. $this->_dochecks();
  1631. // initialization of properties
  1632. $this->isunicode = $unicode;
  1633. $this->page = 0;
  1634. $this->transfmrk[0] = array();
  1635. $this->pagedim = array();
  1636. $this->n = 2;
  1637. $this->buffer = '';
  1638. $this->pages = array();
  1639. $this->state = 0;
  1640. $this->fonts = array();
  1641. $this->FontFiles = array();
  1642. $this->diffs = array();
  1643. $this->images = array();
  1644. $this->links = array();
  1645. $this->gradients = array();
  1646. $this->InFooter = false;
  1647. $this->lasth = 0;
  1648. $this->FontFamily = 'helvetica';
  1649. $this->FontStyle = '';
  1650. $this->FontSizePt = 12;
  1651. $this->underline = false;
  1652. $this->overline = false;
  1653. $this->linethrough = false;
  1654. $this->DrawColor = '0 G';
  1655. $this->FillColor = '0 g';
  1656. $this->TextColor = '0 g';
  1657. $this->ColorFlag = false;
  1658. $this->pdflayers = array();
  1659. // encryption values
  1660. $this->encrypted = false;
  1661. $this->last_enc_key = '';
  1662. // standard Unicode fonts
  1663. $this->CoreFonts = array(
  1664. 'courier'=>'Courier',
  1665. 'courierB'=>'Courier-Bold',
  1666. 'courierI'=>'Courier-Oblique',
  1667. 'courierBI'=>'Courier-BoldOblique',
  1668. 'helvetica'=>'Helvetica',
  1669. 'helveticaB'=>'Helvetica-Bold',
  1670. 'helveticaI'=>'Helvetica-Oblique',
  1671. 'helveticaBI'=>'Helvetica-BoldOblique',
  1672. 'times'=>'Times-Roman',
  1673. 'timesB'=>'Times-Bold',
  1674. 'timesI'=>'Times-Italic',
  1675. 'timesBI'=>'Times-BoldItalic',
  1676. 'symbol'=>'Symbol',
  1677. 'zapfdingbats'=>'ZapfDingbats'
  1678. );
  1679. // set scale factor
  1680. $this->setPageUnit($unit);
  1681. // set page format and orientation
  1682. $this->setPageFormat($format, $orientation);
  1683. // page margins (1 cm)
  1684. $margin = 28.35 / $this->k;
  1685. $this->SetMargins($margin, $margin);
  1686. // internal cell padding
  1687. $cpadding = $margin / 10;
  1688. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1689. // cell margins
  1690. $this->setCellMargins(0, 0, 0, 0);
  1691. // line width (0.2 mm)
  1692. $this->LineWidth = 0.57 / $this->k;
  1693. $this->linestyleWidth = sprintf('%.2F w', ($this->LineWidth * $this->k));
  1694. $this->linestyleCap = '0 J';
  1695. $this->linestyleJoin = '0 j';
  1696. $this->linestyleDash = '[] 0 d';
  1697. // automatic page break
  1698. $this->SetAutoPageBreak(true, (2 * $margin));
  1699. // full width display mode
  1700. $this->SetDisplayMode('fullwidth');
  1701. // compression
  1702. $this->SetCompression();
  1703. // set default PDF version number
  1704. $this->setPDFVersion();
  1705. $this->encoding = $encoding;
  1706. $this->HREF = array();
  1707. $this->getFontsList();
  1708. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1709. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1710. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1711. $this->extgstates = array();
  1712. // user's rights
  1713. $this->sign = false;
  1714. $this->ur['enabled'] = false;
  1715. $this->ur['document'] = '/FullSave';
  1716. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1717. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1718. $this->ur['signature'] = '/Modify';
  1719. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1720. $this->ur['formex'] = '';
  1721. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1722. $this->empty_signature_appearance = array();
  1723. // set default JPEG quality
  1724. $this->jpeg_quality = 75;
  1725. // initialize some settings
  1726. $this->utf8Bidi(array(''), '');
  1727. // set default font
  1728. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1729. // check if PCRE Unicode support is enabled
  1730. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1731. // PCRE unicode support is turned ON
  1732. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  1733. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  1734. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  1735. //$this->setSpacesRE('/[^\S\P{Z}\P{Lo}\xa0]/u');
  1736. $this->setSpacesRE('/[^\S\P{Z}\xa0]/u');
  1737. } else {
  1738. // PCRE unicode support is turned OFF
  1739. $this->setSpacesRE('/[^\S\xa0]/');
  1740. }
  1741. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1742. // set file ID for trailer
  1743. $this->file_id = md5($this->getRandomSeed('TCPDF'.$orientation.$unit.$format.$encoding));
  1744. // set document date
  1745. $this->doc_date = substr_replace(date('YmdHisO'), '\'', (0 - 2), 0).'\'';
  1746. // get default graphic vars
  1747. $this->default_graphic_vars = $this->getGraphicVars();
  1748. $this->header_xobj_autoreset = false;
  1749. $this->custom_xmp = '';
  1750. }
  1751. /**
  1752. * Default destructor.
  1753. * @public
  1754. * @since 1.53.0.TC016
  1755. */
  1756. public function __destruct() {
  1757. // restore internal encoding
  1758. if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
  1759. mb_internal_encoding($this->internal_encoding);
  1760. }
  1761. // unset all class variables
  1762. $this->_destroy(true);
  1763. }
  1764. /**
  1765. * Return the current TCPDF version.
  1766. * @return TCPDF version string
  1767. * @public
  1768. * @since 5.9.012 (2010-11-10)
  1769. */
  1770. public function getTCPDFVersion() {
  1771. return $this->tcpdf_version;
  1772. }
  1773. /**
  1774. * Set the units of measure for the document.
  1775. * @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.
  1776. * @public
  1777. * @since 3.0.015 (2008-06-06)
  1778. */
  1779. public function setPageUnit($unit) {
  1780. $unit = strtolower($unit);
  1781. //Set scale factor
  1782. switch ($unit) {
  1783. // points
  1784. case 'px':
  1785. case 'pt': {
  1786. $this->k = 1;
  1787. break;
  1788. }
  1789. // millimeters
  1790. case 'mm': {
  1791. $this->k = $this->dpi / 25.4;
  1792. break;
  1793. }
  1794. // centimeters
  1795. case 'cm': {
  1796. $this->k = $this->dpi / 2.54;
  1797. break;
  1798. }
  1799. // inches
  1800. case 'in': {
  1801. $this->k = $this->dpi;
  1802. break;
  1803. }
  1804. // unsupported unit
  1805. default : {
  1806. $this->Error('Incorrect unit: '.$unit);
  1807. break;
  1808. }
  1809. }
  1810. $this->pdfunit = $unit;
  1811. if (isset($this->CurOrientation)) {
  1812. $this->setPageOrientation($this->CurOrientation);
  1813. }
  1814. }
  1815. /**
  1816. * Get page dimensions from format name.
  1817. * @param $format (mixed) The format name. It can be: <ul>
  1818. * <li><b>ISO 216 A Series + 2 SIS 014711 extensions</b></li>
  1819. * <li>A0 (841x1189 mm ; 33.11x46.81 in)</li>
  1820. * <li>A1 (594x841 mm ; 23.39x33.11 in)</li>
  1821. * <li>A2 (420x594 mm ; 16.54x23.39 in)</li>
  1822. * <li>A3 (297x420 mm ; 11.69x16.54 in)</li>
  1823. * <li>A4 (210x297 mm ; 8.27x11.69 in)</li>
  1824. * <li>A5 (148x210 mm ; 5.83x8.27 in)</li>
  1825. * <li>A6 (105x148 mm ; 4.13x5.83 in)</li>
  1826. * <li>A7 (74x105 mm ; 2.91x4.13 in)</li>
  1827. * <li>A8 (52x74 mm ; 2.05x2.91 in)</li>
  1828. * <li>A9 (37x52 mm ; 1.46x2.05 in)</li>
  1829. * <li>A10 (26x37 mm ; 1.02x1.46 in)</li>
  1830. * <li>A11 (18x26 mm ; 0.71x1.02 in)</li>
  1831. * <li>A12 (13x18 mm ; 0.51x0.71 in)</li>
  1832. * <li><b>ISO 216 B Series + 2 SIS 014711 extensions</b></li>
  1833. * <li>B0 (1000x1414 mm ; 39.37x55.67 in)</li>
  1834. * <li>B1 (707x1000 mm ; 27.83x39.37 in)</li>
  1835. * <li>B2 (500x707 mm ; 19.69x27.83 in)</li>
  1836. * <li>B3 (353x500 mm ; 13.90x19.69 in)</li>
  1837. * <li>B4 (250x353 mm ; 9.84x13.90 in)</li>
  1838. * <li>B5 (176x250 mm ; 6.93x9.84 in)</li>
  1839. * <li>B6 (125x176 mm ; 4.92x6.93 in)</li>
  1840. * <li>B7 (88x125 mm ; 3.46x4.92 in)</li>
  1841. * <li>B8 (62x88 mm ; 2.44x3.46 in)</li>
  1842. * <li>B9 (44x62 mm ; 1.73x2.44 in)</li>
  1843. * <li>B10 (31x44 mm ; 1.22x1.73 in)</li>
  1844. * <li>B11 (22x31 mm ; 0.87x1.22 in)</li>
  1845. * <li>B12 (15x22 mm ; 0.59x0.87 in)</li>
  1846. * <li><b>ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION</b></li>
  1847. * <li>C0 (917x1297 mm ; 36.10x51.06 in)</li>
  1848. * <li>C1 (648x917 mm ; 25.51x36.10 in)</li>
  1849. * <li>C2 (458x648 mm ; 18.03x25.51 in)</li>
  1850. * <li>C3 (324x458 mm ; 12.76x18.03 in)</li>
  1851. * <li>C4 (229x324 mm ; 9.02x12.76 in)</li>
  1852. * <li>C5 (162x229 mm ; 6.38x9.02 in)</li>
  1853. * <li>C6 (114x162 mm ; 4.49x6.38 in)</li>
  1854. * <li>C7 (81x114 mm ; 3.19x4.49 in)</li>
  1855. * <li>C8 (57x81 mm ; 2.24x3.19 in)</li>
  1856. * <li>C9 (40x57 mm ; 1.57x2.24 in)</li>
  1857. * <li>C10 (28x40 mm ; 1.10x1.57 in)</li>
  1858. * <li>C11 (20x28 mm ; 0.79x1.10 in)</li>
  1859. * <li>C12 (14x20 mm ; 0.55x0.79 in)</li>
  1860. * <li>C76 (81x162 mm ; 3.19x6.38 in)</li>
  1861. * <li>DL (110x220 mm ; 4.33x8.66 in)</li>
  1862. * <li><b>SIS 014711 E Series</b></li>
  1863. * <li>E0 (879x1241 mm ; 34.61x48.86 in)</li>
  1864. * <li>E1 (620x879 mm ; 24.41x34.61 in)</li>
  1865. * <li>E2 (440x620 mm ; 17.32x24.41 in)</li>
  1866. * <li>E3 (310x440 mm ; 12.20x17.32 in)</li>
  1867. * <li>E4 (220x310 mm ; 8.66x12.20 in)</li>
  1868. * <li>E5 (155x220 mm ; 6.10x8.66 in)</li>
  1869. * <li>E6 (110x155 mm ; 4.33x6.10 in)</li>
  1870. * <li>E7 (78x110 mm ; 3.07x4.33 in)</li>
  1871. * <li>E8 (55x78 mm ; 2.17x3.07 in)</li>
  1872. * <li>E9 (39x55 mm ; 1.54x2.17 in)</li>
  1873. * <li>E10 (27x39 mm ; 1.06x1.54 in)</li>
  1874. * <li>E11 (19x27 mm ; 0.75x1.06 in)</li>
  1875. * <li>E12 (13x19 mm ; 0.51x0.75 in)</li>
  1876. * <li><b>SIS 014711 G Series</b></li>
  1877. * <li>G0 (958x1354 mm ; 37.72x53.31 in)</li>
  1878. * <li>G1 (677x958 mm ; 26.65x37.72 in)</li>
  1879. * <li>G2 (479x677 mm ; 18.86x26.65 in)</li>
  1880. * <li>G3 (338x479 mm ; 13.31x18.86 in)</li>
  1881. * <li>G4 (239x338 mm ; 9.41x13.31 in)</li>
  1882. * <li>G5 (169x239 mm ; 6.65x9.41 in)</li>
  1883. * <li>G6 (119x169 mm ; 4.69x6.65 in)</li>
  1884. * <li>G7 (84x119 mm ; 3.31x4.69 in)</li>
  1885. * <li>G8 (59x84 mm ; 2.32x3.31 in)</li>
  1886. * <li>G9 (42x59 mm ; 1.65x2.32 in)</li>
  1887. * <li>G10 (29x42 mm ; 1.14x1.65 in)</li>
  1888. * <li>G11 (21x29 mm ; 0.83x1.14 in)</li>
  1889. * <li>G12 (14x21 mm ; 0.55x0.83 in)</li>
  1890. * <li><b>ISO Press</b></li>
  1891. * <li>RA0 (860x1220 mm ; 33.86x48.03 in)</li>
  1892. * <li>RA1 (610x860 mm ; 24.02x33.86 in)</li>
  1893. * <li>RA2 (430x610 mm ; 16.93x24.02 in)</li>
  1894. * <li>RA3 (305x430 mm ; 12.01x16.93 in)</li>
  1895. * <li>RA4 (215x305 mm ; 8.46x12.01 in)</li>
  1896. * <li>SRA0 (900x1280 mm ; 35.43x50.39 in)</li>
  1897. * <li>SRA1 (640x900 mm ; 25.20x35.43 in)</li>
  1898. * <li>SRA2 (450x640 mm ; 17.72x25.20 in)</li>
  1899. * <li>SRA3 (320x450 mm ; 12.60x17.72 in)</li>
  1900. * <li>SRA4 (225x320 mm ; 8.86x12.60 in)</li>
  1901. * <li><b>German DIN 476</b></li>
  1902. * <li>4A0 (1682x2378 mm ; 66.22x93.62 in)</li>
  1903. * <li>2A0 (1189x1682 mm ; 46.81x66.22 in)</li>
  1904. * <li><b>Variations on the ISO Standard</b></li>
  1905. * <li>A2_EXTRA (445x619 mm ; 17.52x24.37 in)</li>
  1906. * <li>A3+ (329x483 mm ; 12.95x19.02 in)</li>
  1907. * <li>A3_EXTRA (322x445 mm ; 12.68x17.52 in)</li>
  1908. * <li>A3_SUPER (305x508 mm ; 12.01x20.00 in)</li>
  1909. * <li>SUPER_A3 (305x487 mm ; 12.01x19.17 in)</li>
  1910. * <li>A4_EXTRA (235x322 mm ; 9.25x12.68 in)</li>
  1911. * <li>A4_SUPER (229x322 mm ; 9.02x12.68 in)</li>
  1912. * <li>SUPER_A4 (227x356 mm ; 8.94x14.02 in)</li>
  1913. * <li>A4_LONG (210x348 mm ; 8.27x13.70 in)</li>
  1914. * <li>F4 (210x330 mm ; 8.27x12.99 in)</li>
  1915. * <li>SO_B5_EXTRA (202x276 mm ; 7.95x10.87 in)</li>
  1916. * <li>A5_EXTRA (173x235 mm ; 6.81x9.25 in)</li>
  1917. * <li><b>ANSI Series</b></li>
  1918. * <li>ANSI_E (864x1118 mm ; 34.00x44.00 in)</li>
  1919. * <li>ANSI_D (559x864 mm ; 22.00x34.00 in)</li>
  1920. * <li>ANSI_C (432x559 mm ; 17.00x22.00 in)</li>
  1921. * <li>ANSI_B (279x432 mm ; 11.00x17.00 in)</li>
  1922. * <li>ANSI_A (216x279 mm ; 8.50x11.00 in)</li>
  1923. * <li><b>Traditional 'Loose' North American Paper Sizes</b></li>
  1924. * <li>LEDGER, USLEDGER (432x279 mm ; 17.00x11.00 in)</li>
  1925. * <li>TABLOID, USTABLOID, BIBLE, ORGANIZERK (279x432 mm ; 11.00x17.00 in)</li>
  1926. * <li>LETTER, USLETTER, ORGANIZERM (216x279 mm ; 8.50x11.00 in)</li>
  1927. * <li>LEGAL, USLEGAL (216x356 mm ; 8.50x14.00 in)</li>
  1928. * <li>GLETTER, GOVERNMENTLETTER (203x267 mm ; 8.00x10.50 in)</li>
  1929. * <li>JLEGAL, JUNIORLEGAL (203x127 mm ; 8.00x5.00 in)</li>
  1930. * <li><b>Other North American Paper Sizes</b></li>
  1931. * <li>QUADDEMY (889x1143 mm ; 35.00x45.00 in)</li>
  1932. * <li>SUPER_B (330x483 mm ; 13.00x19.00 in)</li>
  1933. * <li>QUARTO (229x279 mm ; 9.00x11.00 in)</li>
  1934. * <li>FOLIO, GOVERNMENTLEGAL (216x330 mm ; 8.50x13.00 in)</li>
  1935. * <li>EXECUTIVE, MONARCH (184x267 mm ; 7.25x10.50 in)</li>
  1936. * <li>MEMO, STATEMENT, ORGANIZERL (140x216 mm ; 5.50x8.50 in)</li>
  1937. * <li>FOOLSCAP (210x330 mm ; 8.27x13.00 in)</li>
  1938. * <li>COMPACT (108x171 mm ; 4.25x6.75 in)</li>
  1939. * <li>ORGANIZERJ (70x127 mm ; 2.75x5.00 in)</li>
  1940. * <li><b>Canadian standard CAN 2-9.60M</b></li>
  1941. * <li>P1 (560x860 mm ; 22.05x33.86 in)</li>
  1942. * <li>P2 (430x560 mm ; 16.93x22.05 in)</li>
  1943. * <li>P3 (280x430 mm ; 11.02x16.93 in)</li>
  1944. * <li>P4 (215x280 mm ; 8.46x11.02 in)</li>
  1945. * <li>P5 (140x215 mm ; 5.51x8.46 in)</li>
  1946. * <li>P6 (107x140 mm ; 4.21x5.51 in)</li>
  1947. * <li><b>North American Architectural Sizes</b></li>
  1948. * <li>ARCH_E (914x1219 mm ; 36.00x48.00 in)</li>
  1949. * <li>ARCH_E1 (762x1067 mm ; 30.00x42.00 in)</li>
  1950. * <li>ARCH_D (610x914 mm ; 24.00x36.00 in)</li>
  1951. * <li>ARCH_C, BROADSHEET (457x610 mm ; 18.00x24.00 in)</li>
  1952. * <li>ARCH_B (305x457 mm ; 12.00x18.00 in)</li>
  1953. * <li>ARCH_A (229x305 mm ; 9.00x12.00 in)</li>
  1954. * <li><b>Announcement Envelopes</b></li>
  1955. * <li>ANNENV_A2 (111x146 mm ; 4.37x5.75 in)</li>
  1956. * <li>ANNENV_A6 (121x165 mm ; 4.75x6.50 in)</li>
  1957. * <li>ANNENV_A7 (133x184 mm ; 5.25x7.25 in)</li>
  1958. * <li>ANNENV_A8 (140x206 mm ; 5.50x8.12 in)</li>
  1959. * <li>ANNENV_A10 (159x244 mm ; 6.25x9.62 in)</li>
  1960. * <li>ANNENV_SLIM (98x225 mm ; 3.87x8.87 in)</li>
  1961. * <li><b>Commercial Envelopes</b></li>
  1962. * <li>COMMENV_N6_1/4 (89x152 mm ; 3.50x6.00 in)</li>
  1963. * <li>COMMENV_N6_3/4 (92x165 mm ; 3.62x6.50 in)</li>
  1964. * <li>COMMENV_N8 (98x191 mm ; 3.87x7.50 in)</li>
  1965. * <li>COMMENV_N9 (98x225 mm ; 3.87x8.87 in)</li>
  1966. * <li>COMMENV_N10 (105x241 mm ; 4.12x9.50 in)</li>
  1967. * <li>COMMENV_N11 (114x263 mm ; 4.50x10.37 in)</li>
  1968. * <li>COMMENV_N12 (121x279 mm ; 4.75x11.00 in)</li>
  1969. * <li>COMMENV_N14 (127x292 mm ; 5.00x11.50 in)</li>
  1970. * <li><b>Catalogue Envelopes</b></li>
  1971. * <li>CATENV_N1 (152x229 mm ; 6.00x9.00 in)</li>
  1972. * <li>CATENV_N1_3/4 (165x241 mm ; 6.50x9.50 in)</li>
  1973. * <li>CATENV_N2 (165x254 mm ; 6.50x10.00 in)</li>
  1974. * <li>CATENV_N3 (178x254 mm ; 7.00x10.00 in)</li>
  1975. * <li>CATENV_N6 (191x267 mm ; 7.50x10.50 in)</li>
  1976. * <li>CATENV_N7 (203x279 mm ; 8.00x11.00 in)</li>
  1977. * <li>CATENV_N8 (210x286 mm ; 8.25x11.25 in)</li>
  1978. * <li>CATENV_N9_1/2 (216x267 mm ; 8.50x10.50 in)</li>
  1979. * <li>CATENV_N9_3/4 (222x286 mm ; 8.75x11.25 in)</li>
  1980. * <li>CATENV_N10_1/2 (229x305 mm ; 9.00x12.00 in)</li>
  1981. * <li>CATENV_N12_1/2 (241x318 mm ; 9.50x12.50 in)</li>
  1982. * <li>CATENV_N13_1/2 (254x330 mm ; 10.00x13.00 in)</li>
  1983. * <li>CATENV_N14_1/4 (286x311 mm ; 11.25x12.25 in)</li>
  1984. * <li>CATENV_N14_1/2 (292x368 mm ; 11.50x14.50 in)</li>
  1985. * <li><b>Japanese (JIS P 0138-61) Standard B-Series</b></li>
  1986. * <li>JIS_B0 (1030x1456 mm ; 40.55x57.32 in)</li>
  1987. * <li>JIS_B1 (728x1030 mm ; 28.66x40.55 in)</li>
  1988. * <li>JIS_B2 (515x728 mm ; 20.28x28.66 in)</li>
  1989. * <li>JIS_B3 (364x515 mm ; 14.33x20.28 in)</li>
  1990. * <li>JIS_B4 (257x364 mm ; 10.12x14.33 in)</li>
  1991. * <li>JIS_B5 (182x257 mm ; 7.17x10.12 in)</li>
  1992. * <li>JIS_B6 (128x182 mm ; 5.04x7.17 in)</li>
  1993. * <li>JIS_B7 (91x128 mm ; 3.58x5.04 in)</li>
  1994. * <li>JIS_B8 (64x91 mm ; 2.52x3.58 in)</li>
  1995. * <li>JIS_B9 (45x64 mm ; 1.77x2.52 in)</li>
  1996. * <li>JIS_B10 (32x45 mm ; 1.26x1.77 in)</li>
  1997. * <li>JIS_B11 (22x32 mm ; 0.87x1.26 in)</li>
  1998. * <li>JIS_B12 (16x22 mm ; 0.63x0.87 in)</li>
  1999. * <li><b>PA Series</b></li>
  2000. * <li>PA0 (840x1120 mm ; 33.07x44.09 in)</li>
  2001. * <li>PA1 (560x840 mm ; 22.05x33.07 in)</li>
  2002. * <li>PA2 (420x560 mm ; 16.54x22.05 in)</li>
  2003. * <li>PA3 (280x420 mm ; 11.02x16.54 in)</li>
  2004. * <li>PA4 (210x280 mm ; 8.27x11.02 in)</li>
  2005. * <li>PA5 (140x210 mm ; 5.51x8.27 in)</li>
  2006. * <li>PA6 (105x140 mm ; 4.13x5.51 in)</li>
  2007. * <li>PA7 (70x105 mm ; 2.76x4.13 in)</li>
  2008. * <li>PA8 (52x70 mm ; 2.05x2.76 in)</li>
  2009. * <li>PA9 (35x52 mm ; 1.38x2.05 in)</li>
  2010. * <li>PA10 (26x35 mm ; 1.02x1.38 in)</li>
  2011. * <li><b>Standard Photographic Print Sizes</b></li>
  2012. * <li>PASSPORT_PHOTO (35x45 mm ; 1.38x1.77 in)</li>
  2013. * <li>E (82x120 mm ; 3.25x4.72 in)</li>
  2014. * <li>3R, L (89x127 mm ; 3.50x5.00 in)</li>
  2015. * <li>4R, KG (102x152 mm ; 4.02x5.98 in)</li>
  2016. * <li>4D (120x152 mm ; 4.72x5.98 in)</li>
  2017. * <li>5R, 2L (127x178 mm ; 5.00x7.01 in)</li>
  2018. * <li>6R, 8P (152x203 mm ; 5.98x7.99 in)</li>
  2019. * <li>8R, 6P (203x254 mm ; 7.99x10.00 in)</li>
  2020. * <li>S8R, 6PW (203x305 mm ; 7.99x12.01 in)</li>
  2021. * <li>10R, 4P (254x305 mm ; 10.00x12.01 in)</li>
  2022. * <li>S10R, 4PW (254x381 mm ; 10.00x15.00 in)</li>
  2023. * <li>11R (279x356 mm ; 10.98x14.02 in)</li>
  2024. * <li>S11R (279x432 mm ; 10.98x17.01 in)</li>
  2025. * <li>12R (305x381 mm ; 12.01x15.00 in)</li>
  2026. * <li>S12R (305x456 mm ; 12.01x17.95 in)</li>
  2027. * <li><b>Common Newspaper Sizes</b></li>
  2028. * <li>NEWSPAPER_BROADSHEET (750x600 mm ; 29.53x23.62 in)</li>
  2029. * <li>NEWSPAPER_BERLINER (470x315 mm ; 18.50x12.40 in)</li>
  2030. * <li>NEWSPAPER_COMPACT, NEWSPAPER_TABLOID (430x280 mm ; 16.93x11.02 in)</li>
  2031. * <li><b>Business Cards</b></li>
  2032. * <li>CREDIT_CARD, BUSINESS_CARD, BUSINESS_CARD_ISO7810 (54x86 mm ; 2.13x3.37 in)</li>
  2033. * <li>BUSINESS_CARD_ISO216 (52x74 mm ; 2.05x2.91 in)</li>
  2034. * <li>BUSINESS_CARD_IT, BUSINESS_CARD_UK, BUSINESS_CARD_FR, BUSINESS_CARD_DE, BUSINESS_CARD_ES (55x85 mm ; 2.17x3.35 in)</li>
  2035. * <li>BUSINESS_CARD_US, BUSINESS_CARD_CA (51x89 mm ; 2.01x3.50 in)</li>
  2036. * <li>BUSINESS_CARD_JP (55x91 mm ; 2.17x3.58 in)</li>
  2037. * <li>BUSINESS_CARD_HK (54x90 mm ; 2.13x3.54 in)</li>
  2038. * <li>BUSINESS_CARD_AU, BUSINESS_CARD_DK, BUSINESS_CARD_SE (55x90 mm ; 2.17x3.54 in)</li>
  2039. * <li>BUSINESS_CARD_RU, BUSINESS_CARD_CZ, BUSINESS_CARD_FI, BUSINESS_CARD_HU, BUSINESS_CARD_IL (50x90 mm ; 1.97x3.54 in)</li>
  2040. * <li><b>Billboards</b></li>
  2041. * <li>4SHEET (1016x1524 mm ; 40.00x60.00 in)</li>
  2042. * <li>6SHEET (1200x1800 mm ; 47.24x70.87 in)</li>
  2043. * <li>12SHEET (3048x1524 mm ; 120.00x60.00 in)</li>
  2044. * <li>16SHEET (2032x3048 mm ; 80.00x120.00 in)</li>
  2045. * <li>32SHEET (4064x3048 mm ; 160.00x120.00 in)</li>
  2046. * <li>48SHEET (6096x3048 mm ; 240.00x120.00 in)</li>
  2047. * <li>64SHEET (8128x3048 mm ; 320.00x120.00 in)</li>
  2048. * <li>96SHEET (12192x3048 mm ; 480.00x120.00 in)</li>
  2049. * <li><b>Old Imperial English (some are still used in USA)</b></li>
  2050. * <li>EN_EMPEROR (1219x1829 mm ; 48.00x72.00 in)</li>
  2051. * <li>EN_ANTIQUARIAN (787x1346 mm ; 31.00x53.00 in)</li>
  2052. * <li>EN_GRAND_EAGLE (730x1067 mm ; 28.75x42.00 in)</li>
  2053. * <li>EN_DOUBLE_ELEPHANT (679x1016 mm ; 26.75x40.00 in)</li>
  2054. * <li>EN_ATLAS (660x864 mm ; 26.00x34.00 in)</li>
  2055. * <li>EN_COLOMBIER (597x876 mm ; 23.50x34.50 in)</li>
  2056. * <li>EN_ELEPHANT (584x711 mm ; 23.00x28.00 in)</li>
  2057. * <li>EN_DOUBLE_DEMY (572x902 mm ; 22.50x35.50 in)</li>
  2058. * <li>EN_IMPERIAL (559x762 mm ; 22.00x30.00 in)</li>
  2059. * <li>EN_PRINCESS (546x711 mm ; 21.50x28.00 in)</li>
  2060. * <li>EN_CARTRIDGE (533x660 mm ; 21.00x26.00 in)</li>
  2061. * <li>EN_DOUBLE_LARGE_POST (533x838 mm ; 21.00x33.00 in)</li>
  2062. * <li>EN_ROYAL (508x635 mm ; 20.00x25.00 in)</li>
  2063. * <li>EN_SHEET, EN_HALF_POST (495x597 mm ; 19.50x23.50 in)</li>
  2064. * <li>EN_SUPER_ROYAL (483x686 mm ; 19.00x27.00 in)</li>
  2065. * <li>EN_DOUBLE_POST (483x775 mm ; 19.00x30.50 in)</li>
  2066. * <li>EN_MEDIUM (445x584 mm ; 17.50x23.00 in)</li>
  2067. * <li>EN_DEMY (445x572 mm ; 17.50x22.50 in)</li>
  2068. * <li>EN_LARGE_POST (419x533 mm ; 16.50x21.00 in)</li>
  2069. * <li>EN_COPY_DRAUGHT (406x508 mm ; 16.00x20.00 in)</li>
  2070. * <li>EN_POST (394x489 mm ; 15.50x19.25 in)</li>
  2071. * <li>EN_CROWN (381x508 mm ; 15.00x20.00 in)</li>
  2072. * <li>EN_PINCHED_POST (375x470 mm ; 14.75x18.50 in)</li>
  2073. * <li>EN_BRIEF (343x406 mm ; 13.50x16.00 in)</li>
  2074. * <li>EN_FOOLSCAP (343x432 mm ; 13.50x17.00 in)</li>
  2075. * <li>EN_SMALL_FOOLSCAP (337x419 mm ; 13.25x16.50 in)</li>
  2076. * <li>EN_POTT (318x381 mm ; 12.50x15.00 in)</li>
  2077. * <li><b>Old Imperial Belgian</b></li>
  2078. * <li>BE_GRAND_AIGLE (700x1040 mm ; 27.56x40.94 in)</li>
  2079. * <li>BE_COLOMBIER (620x850 mm ; 24.41x33.46 in)</li>
  2080. * <li>BE_DOUBLE_CARRE (620x920 mm ; 24.41x36.22 in)</li>
  2081. * <li>BE_ELEPHANT (616x770 mm ; 24.25x30.31 in)</li>
  2082. * <li>BE_PETIT_AIGLE (600x840 mm ; 23.62x33.07 in)</li>
  2083. * <li>BE_GRAND_JESUS (550x730 mm ; 21.65x28.74 in)</li>
  2084. * <li>BE_JESUS (540x730 mm ; 21.26x28.74 in)</li>
  2085. * <li>BE_RAISIN (500x650 mm ; 19.69x25.59 in)</li>
  2086. * <li>BE_GRAND_MEDIAN (460x605 mm ; 18.11x23.82 in)</li>
  2087. * <li>BE_DOUBLE_POSTE (435x565 mm ; 17.13x22.24 in)</li>
  2088. * <li>BE_COQUILLE (430x560 mm ; 16.93x22.05 in)</li>
  2089. * <li>BE_PETIT_MEDIAN (415x530 mm ; 16.34x20.87 in)</li>
  2090. * <li>BE_RUCHE (360x460 mm ; 14.17x18.11 in)</li>
  2091. * <li>BE_PROPATRIA (345x430 mm ; 13.58x16.93 in)</li>
  2092. * <li>BE_LYS (317x397 mm ; 12.48x15.63 in)</li>
  2093. * <li>BE_POT (307x384 mm ; 12.09x15.12 in)</li>
  2094. * <li>BE_ROSETTE (270x347 mm ; 10.63x13.66 in)</li>
  2095. * <li><b>Old Imperial French</b></li>
  2096. * <li>FR_UNIVERS (1000x1300 mm ; 39.37x51.18 in)</li>
  2097. * <li>FR_DOUBLE_COLOMBIER (900x1260 mm ; 35.43x49.61 in)</li>
  2098. * <li>FR_GRANDE_MONDE (900x1260 mm ; 35.43x49.61 in)</li>
  2099. * <li>FR_DOUBLE_SOLEIL (800x1200 mm ; 31.50x47.24 in)</li>
  2100. * <li>FR_DOUBLE_JESUS (760x1120 mm ; 29.92x44.09 in)</li>
  2101. * <li>FR_GRAND_AIGLE (750x1060 mm ; 29.53x41.73 in)</li>
  2102. * <li>FR_PETIT_AIGLE (700x940 mm ; 27.56x37.01 in)</li>
  2103. * <li>FR_DOUBLE_RAISIN (650x1000 mm ; 25.59x39.37 in)</li>
  2104. * <li>FR_JOURNAL (650x940 mm ; 25.59x37.01 in)</li>
  2105. * <li>FR_COLOMBIER_AFFICHE (630x900 mm ; 24.80x35.43 in)</li>
  2106. * <li>FR_DOUBLE_CAVALIER (620x920 mm ; 24.41x36.22 in)</li>
  2107. * <li>FR_CLOCHE (600x800 mm ; 23.62x31.50 in)</li>
  2108. * <li>FR_SOLEIL (600x800 mm ; 23.62x31.50 in)</li>
  2109. * <li>FR_DOUBLE_CARRE (560x900 mm ; 22.05x35.43 in)</li>
  2110. * <li>FR_DOUBLE_COQUILLE (560x880 mm ; 22.05x34.65 in)</li>
  2111. * <li>FR_JESUS (560x760 mm ; 22.05x29.92 in)</li>
  2112. * <li>FR_RAISIN (500x650 mm ; 19.69x25.59 in)</li>
  2113. * <li>FR_CAVALIER (460x620 mm ; 18.11x24.41 in)</li>
  2114. * <li>FR_DOUBLE_COURONNE (460x720 mm ; 18.11x28.35 in)</li>
  2115. * <li>FR_CARRE (450x560 mm ; 17.72x22.05 in)</li>
  2116. * <li>FR_COQUILLE (440x560 mm ; 17.32x22.05 in)</li>
  2117. * <li>FR_DOUBLE_TELLIERE (440x680 mm ; 17.32x26.77 in)</li>
  2118. * <li>FR_DOUBLE_CLOCHE (400x600 mm ; 15.75x23.62 in)</li>
  2119. * <li>FR_DOUBLE_POT (400x620 mm ; 15.75x24.41 in)</li>
  2120. * <li>FR_ECU (400x520 mm ; 15.75x20.47 in)</li>
  2121. * <li>FR_COURONNE (360x460 mm ; 14.17x18.11 in)</li>
  2122. * <li>FR_TELLIERE (340x440 mm ; 13.39x17.32 in)</li>
  2123. * <li>FR_POT (310x400 mm ; 12.20x15.75 in)</li>
  2124. * </ul>
  2125. * @return array containing page width and height in points
  2126. * @public
  2127. * @since 5.0.010 (2010-05-17)
  2128. */
  2129. public function getPageSizeFromFormat($format) {
  2130. // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 25.4 mm)
  2131. switch (strtoupper($format)) {
  2132. // ISO 216 A Series + 2 SIS 014711 extensions
  2133. case 'A0' : {$pf = array( 2383.937, 3370.394); break;}
  2134. case 'A1' : {$pf = array( 1683.780, 2383.937); break;}
  2135. case 'A2' : {$pf = array( 1190.551, 1683.780); break;}
  2136. case 'A3' : {$pf = array( 841.890, 1190.551); break;}
  2137. case 'A4' : {$pf = array( 595.276, 841.890); break;}
  2138. case 'A5' : {$pf = array( 419.528, 595.276); break;}
  2139. case 'A6' : {$pf = array( 297.638, 419.528); break;}
  2140. case 'A7' : {$pf = array( 209.764, 297.638); break;}
  2141. case 'A8' : {$pf = array( 147.402, 209.764); break;}
  2142. case 'A9' : {$pf = array( 104.882, 147.402); break;}
  2143. case 'A10': {$pf = array( 73.701, 104.882); break;}
  2144. case 'A11': {$pf = array( 51.024, 73.701); break;}
  2145. case 'A12': {$pf = array( 36.850, 51.024); break;}
  2146. // ISO 216 B Series + 2 SIS 014711 extensions
  2147. case 'B0' : {$pf = array( 2834.646, 4008.189); break;}
  2148. case 'B1' : {$pf = array( 2004.094, 2834.646); break;}
  2149. case 'B2' : {$pf = array( 1417.323, 2004.094); break;}
  2150. case 'B3' : {$pf = array( 1000.630, 1417.323); break;}
  2151. case 'B4' : {$pf = array( 708.661, 1000.630); break;}
  2152. case 'B5' : {$pf = array( 498.898, 708.661); break;}
  2153. case 'B6' : {$pf = array( 354.331, 498.898); break;}
  2154. case 'B7' : {$pf = array( 249.449, 354.331); break;}
  2155. case 'B8' : {$pf = array( 175.748, 249.449); break;}
  2156. case 'B9' : {$pf = array( 124.724, 175.748); break;}
  2157. case 'B10': {$pf = array( 87.874, 124.724); break;}
  2158. case 'B11': {$pf = array( 62.362, 87.874); break;}
  2159. case 'B12': {$pf = array( 42.520, 62.362); break;}
  2160. // ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION
  2161. case 'C0' : {$pf = array( 2599.370, 3676.535); break;}
  2162. case 'C1' : {$pf = array( 1836.850, 2599.370); break;}
  2163. case 'C2' : {$pf = array( 1298.268, 1836.850); break;}
  2164. case 'C3' : {$pf = array( 918.425, 1298.268); break;}
  2165. case 'C4' : {$pf = array( 649.134, 918.425); break;}
  2166. case 'C5' : {$pf = array( 459.213, 649.134); break;}
  2167. case 'C6' : {$pf = array( 323.150, 459.213); break;}
  2168. case 'C7' : {$pf = array( 229.606, 323.150); break;}
  2169. case 'C8' : {$pf = array( 161.575, 229.606); break;}
  2170. case 'C9' : {$pf = array( 113.386, 161.575); break;}
  2171. case 'C10': {$pf = array( 79.370, 113.386); break;}
  2172. case 'C11': {$pf = array( 56.693, 79.370); break;}
  2173. case 'C12': {$pf = array( 39.685, 56.693); break;}
  2174. case 'C76': {$pf = array( 229.606, 459.213); break;}
  2175. case 'DL' : {$pf = array( 311.811, 623.622); break;}
  2176. // SIS 014711 E Series
  2177. case 'E0' : {$pf = array( 2491.654, 3517.795); break;}
  2178. case 'E1' : {$pf = array( 1757.480, 2491.654); break;}
  2179. case 'E2' : {$pf = array( 1247.244, 1757.480); break;}
  2180. case 'E3' : {$pf = array( 878.740, 1247.244); break;}
  2181. case 'E4' : {$pf = array( 623.622, 878.740); break;}
  2182. case 'E5' : {$pf = array( 439.370, 623.622); break;}
  2183. case 'E6' : {$pf = array( 311.811, 439.370); break;}
  2184. case 'E7' : {$pf = array( 221.102, 311.811); break;}
  2185. case 'E8' : {$pf = array( 155.906, 221.102); break;}
  2186. case 'E9' : {$pf = array( 110.551, 155.906); break;}
  2187. case 'E10': {$pf = array( 76.535, 110.551); break;}
  2188. case 'E11': {$pf = array( 53.858, 76.535); break;}
  2189. case 'E12': {$pf = array( 36.850, 53.858); break;}
  2190. // SIS 014711 G Series
  2191. case 'G0' : {$pf = array( 2715.591, 3838.110); break;}
  2192. case 'G1' : {$pf = array( 1919.055, 2715.591); break;}
  2193. case 'G2' : {$pf = array( 1357.795, 1919.055); break;}
  2194. case 'G3' : {$pf = array( 958.110, 1357.795); break;}
  2195. case 'G4' : {$pf = array( 677.480, 958.110); break;}
  2196. case 'G5' : {$pf = array( 479.055, 677.480); break;}
  2197. case 'G6' : {$pf = array( 337.323, 479.055); break;}
  2198. case 'G7' : {$pf = array( 238.110, 337.323); break;}
  2199. case 'G8' : {$pf = array( 167.244, 238.110); break;}
  2200. case 'G9' : {$pf = array( 119.055, 167.244); break;}
  2201. case 'G10': {$pf = array( 82.205, 119.055); break;}
  2202. case 'G11': {$pf = array( 59.528, 82.205); break;}
  2203. case 'G12': {$pf = array( 39.685, 59.528); break;}
  2204. // ISO Press
  2205. case 'RA0': {$pf = array( 2437.795, 3458.268); break;}
  2206. case 'RA1': {$pf = array( 1729.134, 2437.795); break;}
  2207. case 'RA2': {$pf = array( 1218.898, 1729.134); break;}
  2208. case 'RA3': {$pf = array( 864.567, 1218.898); break;}
  2209. case 'RA4': {$pf = array( 609.449, 864.567); break;}
  2210. case 'SRA0': {$pf = array( 2551.181, 3628.346); break;}
  2211. case 'SRA1': {$pf = array( 1814.173, 2551.181); break;}
  2212. case 'SRA2': {$pf = array( 1275.591, 1814.173); break;}
  2213. case 'SRA3': {$pf = array( 907.087, 1275.591); break;}
  2214. case 'SRA4': {$pf = array( 637.795, 907.087); break;}
  2215. // German DIN 476
  2216. case '4A0': {$pf = array( 4767.874, 6740.787); break;}
  2217. case '2A0': {$pf = array( 3370.394, 4767.874); break;}
  2218. // Variations on the ISO Standard
  2219. case 'A2_EXTRA' : {$pf = array( 1261.417, 1754.646); break;}
  2220. case 'A3+' : {$pf = array( 932.598, 1369.134); break;}
  2221. case 'A3_EXTRA' : {$pf = array( 912.756, 1261.417); break;}
  2222. case 'A3_SUPER' : {$pf = array( 864.567, 1440.000); break;}
  2223. case 'SUPER_A3' : {$pf = array( 864.567, 1380.472); break;}
  2224. case 'A4_EXTRA' : {$pf = array( 666.142, 912.756); break;}
  2225. case 'A4_SUPER' : {$pf = array( 649.134, 912.756); break;}
  2226. case 'SUPER_A4' : {$pf = array( 643.465, 1009.134); break;}
  2227. case 'A4_LONG' : {$pf = array( 595.276, 986.457); break;}
  2228. case 'F4' : {$pf = array( 595.276, 935.433); break;}
  2229. case 'SO_B5_EXTRA': {$pf = array( 572.598, 782.362); break;}
  2230. case 'A5_EXTRA' : {$pf = array( 490.394, 666.142); break;}
  2231. // ANSI Series
  2232. case 'ANSI_E': {$pf = array( 2448.000, 3168.000); break;}
  2233. case 'ANSI_D': {$pf = array( 1584.000, 2448.000); break;}
  2234. case 'ANSI_C': {$pf = array( 1224.000, 1584.000); break;}
  2235. case 'ANSI_B': {$pf = array( 792.000, 1224.000); break;}
  2236. case 'ANSI_A': {$pf = array( 612.000, 792.000); break;}
  2237. // Traditional 'Loose' North American Paper Sizes
  2238. case 'USLEDGER':
  2239. case 'LEDGER' : {$pf = array( 1224.000, 792.000); break;}
  2240. case 'ORGANIZERK':
  2241. case 'BIBLE':
  2242. case 'USTABLOID':
  2243. case 'TABLOID': {$pf = array( 792.000, 1224.000); break;}
  2244. case 'ORGANIZERM':
  2245. case 'USLETTER':
  2246. case 'LETTER' : {$pf = array( 612.000, 792.000); break;}
  2247. case 'USLEGAL':
  2248. case 'LEGAL' : {$pf = array( 612.000, 1008.000); break;}
  2249. case 'GOVERNMENTLETTER':
  2250. case 'GLETTER': {$pf = array( 576.000, 756.000); break;}
  2251. case 'JUNIORLEGAL':
  2252. case 'JLEGAL' : {$pf = array( 576.000, 360.000); break;}
  2253. // Other North American Paper Sizes
  2254. case 'QUADDEMY': {$pf = array( 2520.000, 3240.000); break;}
  2255. case 'SUPER_B': {$pf = array( 936.000, 1368.000); break;}
  2256. case 'QUARTO': {$pf = array( 648.000, 792.000); break;}
  2257. case 'GOVERNMENTLEGAL':
  2258. case 'FOLIO': {$pf = array( 612.000, 936.000); break;}
  2259. case 'MONARCH':
  2260. case 'EXECUTIVE': {$pf = array( 522.000, 756.000); break;}
  2261. case 'ORGANIZERL':
  2262. case 'STATEMENT':
  2263. case 'MEMO': {$pf = array( 396.000, 612.000); break;}
  2264. case 'FOOLSCAP': {$pf = array( 595.440, 936.000); break;}
  2265. case 'COMPACT': {$pf = array( 306.000, 486.000); break;}
  2266. case 'ORGANIZERJ': {$pf = array( 198.000, 360.000); break;}
  2267. // Canadian standard CAN 2-9.60M
  2268. case 'P1': {$pf = array( 1587.402, 2437.795); break;}
  2269. case 'P2': {$pf = array( 1218.898, 1587.402); break;}
  2270. case 'P3': {$pf = array( 793.701, 1218.898); break;}
  2271. case 'P4': {$pf = array( 609.449, 793.701); break;}
  2272. case 'P5': {$pf = array( 396.850, 609.449); break;}
  2273. case 'P6': {$pf = array( 303.307, 396.850); break;}
  2274. // North American Architectural Sizes
  2275. case 'ARCH_E' : {$pf = array( 2592.000, 3456.000); break;}
  2276. case 'ARCH_E1': {$pf = array( 2160.000, 3024.000); break;}
  2277. case 'ARCH_D' : {$pf = array( 1728.000, 2592.000); break;}
  2278. case 'BROADSHEET':
  2279. case 'ARCH_C' : {$pf = array( 1296.000, 1728.000); break;}
  2280. case 'ARCH_B' : {$pf = array( 864.000, 1296.000); break;}
  2281. case 'ARCH_A' : {$pf = array( 648.000, 864.000); break;}
  2282. // --- North American Envelope Sizes ---
  2283. // - Announcement Envelopes
  2284. case 'ANNENV_A2' : {$pf = array( 314.640, 414.000); break;}
  2285. case 'ANNENV_A6' : {$pf = array( 342.000, 468.000); break;}
  2286. case 'ANNENV_A7' : {$pf = array( 378.000, 522.000); break;}
  2287. case 'ANNENV_A8' : {$pf = array( 396.000, 584.640); break;}
  2288. case 'ANNENV_A10' : {$pf = array( 450.000, 692.640); break;}
  2289. case 'ANNENV_SLIM': {$pf = array( 278.640, 638.640); break;}
  2290. // - Commercial Envelopes
  2291. case 'COMMENV_N6_1/4': {$pf = array( 252.000, 432.000); break;}
  2292. case 'COMMENV_N6_3/4': {$pf = array( 260.640, 468.000); break;}
  2293. case 'COMMENV_N8' : {$pf = array( 278.640, 540.000); break;}
  2294. case 'COMMENV_N9' : {$pf = array( 278.640, 638.640); break;}
  2295. case 'COMMENV_N10' : {$pf = array( 296.640, 684.000); break;}
  2296. case 'COMMENV_N11' : {$pf = array( 324.000, 746.640); break;}
  2297. case 'COMMENV_N12' : {$pf = array( 342.000, 792.000); break;}
  2298. case 'COMMENV_N14' : {$pf = array( 360.000, 828.000); break;}
  2299. // - Catalogue Envelopes
  2300. case 'CATENV_N1' : {$pf = array( 432.000, 648.000); break;}
  2301. case 'CATENV_N1_3/4' : {$pf = array( 468.000, 684.000); break;}
  2302. case 'CATENV_N2' : {$pf = array( 468.000, 720.000); break;}
  2303. case 'CATENV_N3' : {$pf = array( 504.000, 720.000); break;}
  2304. case 'CATENV_N6' : {$pf = array( 540.000, 756.000); break;}
  2305. case 'CATENV_N7' : {$pf = array( 576.000, 792.000); break;}
  2306. case 'CATENV_N8' : {$pf = array( 594.000, 810.000); break;}
  2307. case 'CATENV_N9_1/2' : {$pf = array( 612.000, 756.000); break;}
  2308. case 'CATENV_N9_3/4' : {$pf = array( 630.000, 810.000); break;}
  2309. case 'CATENV_N10_1/2': {$pf = array( 648.000, 864.000); break;}
  2310. case 'CATENV_N12_1/2': {$pf = array( 684.000, 900.000); break;}
  2311. case 'CATENV_N13_1/2': {$pf = array( 720.000, 936.000); break;}
  2312. case 'CATENV_N14_1/4': {$pf = array( 810.000, 882.000); break;}
  2313. case 'CATENV_N14_1/2': {$pf = array( 828.000, 1044.000); break;}
  2314. // Japanese (JIS P 0138-61) Standard B-Series
  2315. case 'JIS_B0' : {$pf = array( 2919.685, 4127.244); break;}
  2316. case 'JIS_B1' : {$pf = array( 2063.622, 2919.685); break;}
  2317. case 'JIS_B2' : {$pf = array( 1459.843, 2063.622); break;}
  2318. case 'JIS_B3' : {$pf = array( 1031.811, 1459.843); break;}
  2319. case 'JIS_B4' : {$pf = array( 728.504, 1031.811); break;}
  2320. case 'JIS_B5' : {$pf = array( 515.906, 728.504); break;}
  2321. case 'JIS_B6' : {$pf = array( 362.835, 515.906); break;}
  2322. case 'JIS_B7' : {$pf = array( 257.953, 362.835); break;}
  2323. case 'JIS_B8' : {$pf = array( 181.417, 257.953); break;}
  2324. case 'JIS_B9' : {$pf = array( 127.559, 181.417); break;}
  2325. case 'JIS_B10': {$pf = array( 90.709, 127.559); break;}
  2326. case 'JIS_B11': {$pf = array( 62.362, 90.709); break;}
  2327. case 'JIS_B12': {$pf = array( 45.354, 62.362); break;}
  2328. // PA Series
  2329. case 'PA0' : {$pf = array( 2381.102, 3174.803,); break;}
  2330. case 'PA1' : {$pf = array( 1587.402, 2381.102); break;}
  2331. case 'PA2' : {$pf = array( 1190.551, 1587.402); break;}
  2332. case 'PA3' : {$pf = array( 793.701, 1190.551); break;}
  2333. case 'PA4' : {$pf = array( 595.276, 793.701); break;}
  2334. case 'PA5' : {$pf = array( 396.850, 595.276); break;}
  2335. case 'PA6' : {$pf = array( 297.638, 396.850); break;}
  2336. case 'PA7' : {$pf = array( 198.425, 297.638); break;}
  2337. case 'PA8' : {$pf = array( 147.402, 198.425); break;}
  2338. case 'PA9' : {$pf = array( 99.213, 147.402); break;}
  2339. case 'PA10': {$pf = array( 73.701, 99.213); break;}
  2340. // Standard Photographic Print Sizes
  2341. case 'PASSPORT_PHOTO': {$pf = array( 99.213, 127.559); break;}
  2342. case 'E' : {$pf = array( 233.858, 340.157); break;}
  2343. case 'L':
  2344. case '3R' : {$pf = array( 252.283, 360.000); break;}
  2345. case 'KG':
  2346. case '4R' : {$pf = array( 289.134, 430.866); break;}
  2347. case '4D' : {$pf = array( 340.157, 430.866); break;}
  2348. case '2L':
  2349. case '5R' : {$pf = array( 360.000, 504.567); break;}
  2350. case '8P':
  2351. case '6R' : {$pf = array( 430.866, 575.433); break;}
  2352. case '6P':
  2353. case '8R' : {$pf = array( 575.433, 720.000); break;}
  2354. case '6PW':
  2355. case 'S8R' : {$pf = array( 575.433, 864.567); break;}
  2356. case '4P':
  2357. case '10R' : {$pf = array( 720.000, 864.567); break;}
  2358. case '4PW':
  2359. case 'S10R': {$pf = array( 720.000, 1080.000); break;}
  2360. case '11R' : {$pf = array( 790.866, 1009.134); break;}
  2361. case 'S11R': {$pf = array( 790.866, 1224.567); break;}
  2362. case '12R' : {$pf = array( 864.567, 1080.000); break;}
  2363. case 'S12R': {$pf = array( 864.567, 1292.598); break;}
  2364. // Common Newspaper Sizes
  2365. case 'NEWSPAPER_BROADSHEET': {$pf = array( 2125.984, 1700.787); break;}
  2366. case 'NEWSPAPER_BERLINER' : {$pf = array( 1332.283, 892.913); break;}
  2367. case 'NEWSPAPER_TABLOID':
  2368. case 'NEWSPAPER_COMPACT' : {$pf = array( 1218.898, 793.701); break;}
  2369. // Business Cards
  2370. case 'CREDIT_CARD':
  2371. case 'BUSINESS_CARD':
  2372. case 'BUSINESS_CARD_ISO7810': {$pf = array( 153.014, 242.646); break;}
  2373. case 'BUSINESS_CARD_ISO216' : {$pf = array( 147.402, 209.764); break;}
  2374. case 'BUSINESS_CARD_IT':
  2375. case 'BUSINESS_CARD_UK':
  2376. case 'BUSINESS_CARD_FR':
  2377. case 'BUSINESS_CARD_DE':
  2378. case 'BUSINESS_CARD_ES' : {$pf = array( 155.906, 240.945); break;}
  2379. case 'BUSINESS_CARD_CA':
  2380. case 'BUSINESS_CARD_US' : {$pf = array( 144.567, 252.283); break;}
  2381. case 'BUSINESS_CARD_JP' : {$pf = array( 155.906, 257.953); break;}
  2382. case 'BUSINESS_CARD_HK' : {$pf = array( 153.071, 255.118); break;}
  2383. case 'BUSINESS_CARD_AU':
  2384. case 'BUSINESS_CARD_DK':
  2385. case 'BUSINESS_CARD_SE' : {$pf = array( 155.906, 255.118); break;}
  2386. case 'BUSINESS_CARD_RU':
  2387. case 'BUSINESS_CARD_CZ':
  2388. case 'BUSINESS_CARD_FI':
  2389. case 'BUSINESS_CARD_HU':
  2390. case 'BUSINESS_CARD_IL' : {$pf = array( 141.732, 255.118); break;}
  2391. // Billboards
  2392. case '4SHEET' : {$pf = array( 2880.000, 4320.000); break;}
  2393. case '6SHEET' : {$pf = array( 3401.575, 5102.362); break;}
  2394. case '12SHEET': {$pf = array( 8640.000, 4320.000); break;}
  2395. case '16SHEET': {$pf = array( 5760.000, 8640.000); break;}
  2396. case '32SHEET': {$pf = array(11520.000, 8640.000); break;}
  2397. case '48SHEET': {$pf = array(17280.000, 8640.000); break;}
  2398. case '64SHEET': {$pf = array(23040.000, 8640.000); break;}
  2399. case '96SHEET': {$pf = array(34560.000, 8640.000); break;}
  2400. // Old European Sizes
  2401. // - Old Imperial English Sizes
  2402. case 'EN_EMPEROR' : {$pf = array( 3456.000, 5184.000); break;}
  2403. case 'EN_ANTIQUARIAN' : {$pf = array( 2232.000, 3816.000); break;}
  2404. case 'EN_GRAND_EAGLE' : {$pf = array( 2070.000, 3024.000); break;}
  2405. case 'EN_DOUBLE_ELEPHANT' : {$pf = array( 1926.000, 2880.000); break;}
  2406. case 'EN_ATLAS' : {$pf = array( 1872.000, 2448.000); break;}
  2407. case 'EN_COLOMBIER' : {$pf = array( 1692.000, 2484.000); break;}
  2408. case 'EN_ELEPHANT' : {$pf = array( 1656.000, 2016.000); break;}
  2409. case 'EN_DOUBLE_DEMY' : {$pf = array( 1620.000, 2556.000); break;}
  2410. case 'EN_IMPERIAL' : {$pf = array( 1584.000, 2160.000); break;}
  2411. case 'EN_PRINCESS' : {$pf = array( 1548.000, 2016.000); break;}
  2412. case 'EN_CARTRIDGE' : {$pf = array( 1512.000, 1872.000); break;}
  2413. case 'EN_DOUBLE_LARGE_POST': {$pf = array( 1512.000, 2376.000); break;}
  2414. case 'EN_ROYAL' : {$pf = array( 1440.000, 1800.000); break;}
  2415. case 'EN_SHEET':
  2416. case 'EN_HALF_POST' : {$pf = array( 1404.000, 1692.000); break;}
  2417. case 'EN_SUPER_ROYAL' : {$pf = array( 1368.000, 1944.000); break;}
  2418. case 'EN_DOUBLE_POST' : {$pf = array( 1368.000, 2196.000); break;}
  2419. case 'EN_MEDIUM' : {$pf = array( 1260.000, 1656.000); break;}
  2420. case 'EN_DEMY' : {$pf = array( 1260.000, 1620.000); break;}
  2421. case 'EN_LARGE_POST' : {$pf = array( 1188.000, 1512.000); break;}
  2422. case 'EN_COPY_DRAUGHT' : {$pf = array( 1152.000, 1440.000); break;}
  2423. case 'EN_POST' : {$pf = array( 1116.000, 1386.000); break;}
  2424. case 'EN_CROWN' : {$pf = array( 1080.000, 1440.000); break;}
  2425. case 'EN_PINCHED_POST' : {$pf = array( 1062.000, 1332.000); break;}
  2426. case 'EN_BRIEF' : {$pf = array( 972.000, 1152.000); break;}
  2427. case 'EN_FOOLSCAP' : {$pf = array( 972.000, 1224.000); break;}
  2428. case 'EN_SMALL_FOOLSCAP' : {$pf = array( 954.000, 1188.000); break;}
  2429. case 'EN_POTT' : {$pf = array( 900.000, 1080.000); break;}
  2430. // - Old Imperial Belgian Sizes
  2431. case 'BE_GRAND_AIGLE' : {$pf = array( 1984.252, 2948.031); break;}
  2432. case 'BE_COLOMBIER' : {$pf = array( 1757.480, 2409.449); break;}
  2433. case 'BE_DOUBLE_CARRE': {$pf = array( 1757.480, 2607.874); break;}
  2434. case 'BE_ELEPHANT' : {$pf = array( 1746.142, 2182.677); break;}
  2435. case 'BE_PETIT_AIGLE' : {$pf = array( 1700.787, 2381.102); break;}
  2436. case 'BE_GRAND_JESUS' : {$pf = array( 1559.055, 2069.291); break;}
  2437. case 'BE_JESUS' : {$pf = array( 1530.709, 2069.291); break;}
  2438. case 'BE_RAISIN' : {$pf = array( 1417.323, 1842.520); break;}
  2439. case 'BE_GRAND_MEDIAN': {$pf = array( 1303.937, 1714.961); break;}
  2440. case 'BE_DOUBLE_POSTE': {$pf = array( 1233.071, 1601.575); break;}
  2441. case 'BE_COQUILLE' : {$pf = array( 1218.898, 1587.402); break;}
  2442. case 'BE_PETIT_MEDIAN': {$pf = array( 1176.378, 1502.362); break;}
  2443. case 'BE_RUCHE' : {$pf = array( 1020.472, 1303.937); break;}
  2444. case 'BE_PROPATRIA' : {$pf = array( 977.953, 1218.898); break;}
  2445. case 'BE_LYS' : {$pf = array( 898.583, 1125.354); break;}
  2446. case 'BE_POT' : {$pf = array( 870.236, 1088.504); break;}
  2447. case 'BE_ROSETTE' : {$pf = array( 765.354, 983.622); break;}
  2448. // - Old Imperial French Sizes
  2449. case 'FR_UNIVERS' : {$pf = array( 2834.646, 3685.039); break;}
  2450. case 'FR_DOUBLE_COLOMBIER' : {$pf = array( 2551.181, 3571.654); break;}
  2451. case 'FR_GRANDE_MONDE' : {$pf = array( 2551.181, 3571.654); break;}
  2452. case 'FR_DOUBLE_SOLEIL' : {$pf = array( 2267.717, 3401.575); break;}
  2453. case 'FR_DOUBLE_JESUS' : {$pf = array( 2154.331, 3174.803); break;}
  2454. case 'FR_GRAND_AIGLE' : {$pf = array( 2125.984, 3004.724); break;}
  2455. case 'FR_PETIT_AIGLE' : {$pf = array( 1984.252, 2664.567); break;}
  2456. case 'FR_DOUBLE_RAISIN' : {$pf = array( 1842.520, 2834.646); break;}
  2457. case 'FR_JOURNAL' : {$pf = array( 1842.520, 2664.567); break;}
  2458. case 'FR_COLOMBIER_AFFICHE': {$pf = array( 1785.827, 2551.181); break;}
  2459. case 'FR_DOUBLE_CAVALIER' : {$pf = array( 1757.480, 2607.874); break;}
  2460. case 'FR_CLOCHE' : {$pf = array( 1700.787, 2267.717); break;}
  2461. case 'FR_SOLEIL' : {$pf = array( 1700.787, 2267.717); break;}
  2462. case 'FR_DOUBLE_CARRE' : {$pf = array( 1587.402, 2551.181); break;}
  2463. case 'FR_DOUBLE_COQUILLE' : {$pf = array( 1587.402, 2494.488); break;}
  2464. case 'FR_JESUS' : {$pf = array( 1587.402, 2154.331); break;}
  2465. case 'FR_RAISIN' : {$pf = array( 1417.323, 1842.520); break;}
  2466. case 'FR_CAVALIER' : {$pf = array( 1303.937, 1757.480); break;}
  2467. case 'FR_DOUBLE_COURONNE' : {$pf = array( 1303.937, 2040.945); break;}
  2468. case 'FR_CARRE' : {$pf = array( 1275.591, 1587.402); break;}
  2469. case 'FR_COQUILLE' : {$pf = array( 1247.244, 1587.402); break;}
  2470. case 'FR_DOUBLE_TELLIERE' : {$pf = array( 1247.244, 1927.559); break;}
  2471. case 'FR_DOUBLE_CLOCHE' : {$pf = array( 1133.858, 1700.787); break;}
  2472. case 'FR_DOUBLE_POT' : {$pf = array( 1133.858, 1757.480); break;}
  2473. case 'FR_ECU' : {$pf = array( 1133.858, 1474.016); break;}
  2474. case 'FR_COURONNE' : {$pf = array( 1020.472, 1303.937); break;}
  2475. case 'FR_TELLIERE' : {$pf = array( 963.780, 1247.244); break;}
  2476. case 'FR_POT' : {$pf = array( 878.740, 1133.858); break;}
  2477. // DEFAULT ISO A4
  2478. default: {$pf = array( 595.276, 841.890); break;}
  2479. }
  2480. return $pf;
  2481. }
  2482. /**
  2483. * Change the format of the current page
  2484. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numners (width, height) or an array containing the following measures and options:<ul>
  2485. * <li>['format'] = page format name (one of the above);</li>
  2486. * <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>
  2487. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  2488. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  2489. * <li>['MediaBox']['llx'] : lower-left x coordinate in points</li>
  2490. * <li>['MediaBox']['lly'] : lower-left y coordinate in points</li>
  2491. * <li>['MediaBox']['urx'] : upper-right x coordinate in points</li>
  2492. * <li>['MediaBox']['ury'] : upper-right y coordinate in points</li>
  2493. * <li>['CropBox'] : the visible region of default user space:</li>
  2494. * <li>['CropBox']['llx'] : lower-left x coordinate in points</li>
  2495. * <li>['CropBox']['lly'] : lower-left y coordinate in points</li>
  2496. * <li>['CropBox']['urx'] : upper-right x coordinate in points</li>
  2497. * <li>['CropBox']['ury'] : upper-right y coordinate in points</li>
  2498. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  2499. * <li>['BleedBox']['llx'] : lower-left x coordinate in points</li>
  2500. * <li>['BleedBox']['lly'] : lower-left y coordinate in points</li>
  2501. * <li>['BleedBox']['urx'] : upper-right x coordinate in points</li>
  2502. * <li>['BleedBox']['ury'] : upper-right y coordinate in points</li>
  2503. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  2504. * <li>['TrimBox']['llx'] : lower-left x coordinate in points</li>
  2505. * <li>['TrimBox']['lly'] : lower-left y coordinate in points</li>
  2506. * <li>['TrimBox']['urx'] : upper-right x coordinate in points</li>
  2507. * <li>['TrimBox']['ury'] : upper-right y coordinate in points</li>
  2508. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  2509. * <li>['ArtBox']['llx'] : lower-left x coordinate in points</li>
  2510. * <li>['ArtBox']['lly'] : lower-left y coordinate in points</li>
  2511. * <li>['ArtBox']['urx'] : upper-right x coordinate in points</li>
  2512. * <li>['ArtBox']['ury'] : upper-right y coordinate in points</li>
  2513. * <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>
  2514. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  2515. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  2516. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  2517. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  2518. * <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>
  2519. * <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>
  2520. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  2521. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  2522. * <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>
  2523. * <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>
  2524. * <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>
  2525. * <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>
  2526. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  2527. * </ul>
  2528. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  2529. * <li>P or Portrait (default)</li>
  2530. * <li>L or Landscape</li>
  2531. * <li>'' (empty string) for automatic orientation</li>
  2532. * </ul>
  2533. * @protected
  2534. * @since 3.0.015 (2008-06-06)
  2535. * @see getPageSizeFromFormat()
  2536. */
  2537. protected function setPageFormat($format, $orientation='P') {
  2538. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  2539. // remove inherited values
  2540. unset($this->pagedim[$this->page]);
  2541. }
  2542. if (is_string($format)) {
  2543. // get page measures from format name
  2544. $pf = $this->getPageSizeFromFormat($format);
  2545. $this->fwPt = $pf[0];
  2546. $this->fhPt = $pf[1];
  2547. } else {
  2548. // the boundaries of the physical medium on which the page shall be displayed or printed
  2549. if (isset($format['MediaBox'])) {
  2550. $this->setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false);
  2551. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  2552. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  2553. } else {
  2554. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  2555. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  2556. } else {
  2557. if (!isset($format['format'])) {
  2558. // default value
  2559. $format['format'] = 'A4';
  2560. }
  2561. $pf = $this->getPageSizeFromFormat($format['format']);
  2562. }
  2563. $this->fwPt = $pf[0];
  2564. $this->fhPt = $pf[1];
  2565. $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true);
  2566. }
  2567. // the visible region of default user space
  2568. if (isset($format['CropBox'])) {
  2569. $this->setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false);
  2570. }
  2571. // the region to which the contents of the page shall be clipped when output in a production environment
  2572. if (isset($format['BleedBox'])) {
  2573. $this->setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false);
  2574. }
  2575. // the intended dimensions of the finished page after trimming
  2576. if (isset($format['TrimBox'])) {
  2577. $this->setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false);
  2578. }
  2579. // the page's meaningful content (including potential white space)
  2580. if (isset($format['ArtBox'])) {
  2581. $this->setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false);
  2582. }
  2583. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  2584. if (isset($format['BoxColorInfo'])) {
  2585. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  2586. }
  2587. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  2588. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2589. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  2590. }
  2591. if (isset($format['PZ'])) {
  2592. // The page's preferred zoom (magnification) factor
  2593. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  2594. }
  2595. if (isset($format['trans'])) {
  2596. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  2597. if (isset($format['trans']['Dur'])) {
  2598. // The page's display duration
  2599. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  2600. }
  2601. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  2602. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  2603. // The transition style that shall be used when moving to this page from another during a presentation
  2604. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  2605. $valid_effect = array('Split', 'Blinds');
  2606. $valid_vals = array('H', 'V');
  2607. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  2608. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  2609. }
  2610. $valid_effect = array('Split', 'Box', 'Fly');
  2611. $valid_vals = array('I', 'O');
  2612. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  2613. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  2614. }
  2615. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  2616. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  2617. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  2618. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  2619. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  2620. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  2621. }
  2622. }
  2623. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  2624. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  2625. }
  2626. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  2627. $this->pagedim[$this->page]['trans']['B'] = 'true';
  2628. }
  2629. } else {
  2630. $this->pagedim[$this->page]['trans']['S'] = 'R';
  2631. }
  2632. if (isset($format['trans']['D'])) {
  2633. // The duration of the transition effect, in seconds
  2634. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  2635. } else {
  2636. $this->pagedim[$this->page]['trans']['D'] = 1;
  2637. }
  2638. }
  2639. }
  2640. $this->setPageOrientation($orientation);
  2641. }
  2642. /**
  2643. * Set page boundaries.
  2644. * @param $page (int) page number
  2645. * @param $type (string) valid values are: <ul><li>'MediaBox' : the boundaries of the physical medium on which the page shall be displayed or printed;</li><li>'CropBox' : the visible region of default user space;</li><li>'BleedBox' : the region to which the contents of the page shall be clipped when output in a production environment;</li><li>'TrimBox' : the intended dimensions of the finished page after trimming;</li><li>'ArtBox' : the page's meaningful content (including potential white space).</li></ul>
  2646. * @param $llx (float) lower-left x coordinate in user units
  2647. * @param $lly (float) lower-left y coordinate in user units
  2648. * @param $urx (float) upper-right x coordinate in user units
  2649. * @param $ury (float) upper-right y coordinate in user units
  2650. * @param $points (boolean) if true uses user units as unit of measure, otherwise uses PDF points
  2651. * @public
  2652. * @since 5.0.010 (2010-05-17)
  2653. */
  2654. public function setPageBoxes($page, $type, $llx, $lly, $urx, $ury, $points=false) {
  2655. if (!isset($this->pagedim[$page])) {
  2656. // initialize array
  2657. $this->pagedim[$page] = array();
  2658. }
  2659. $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  2660. if (!in_array($type, $pageboxes)) {
  2661. return;
  2662. }
  2663. if ($points) {
  2664. $k = 1;
  2665. } else {
  2666. $k = $this->k;
  2667. }
  2668. $this->pagedim[$page][$type]['llx'] = ($llx * $k);
  2669. $this->pagedim[$page][$type]['lly'] = ($lly * $k);
  2670. $this->pagedim[$page][$type]['urx'] = ($urx * $k);
  2671. $this->pagedim[$page][$type]['ury'] = ($ury * $k);
  2672. }
  2673. /**
  2674. * Swap X and Y coordinates of page boxes (change page boxes orientation).
  2675. * @param $page (int) page number
  2676. * @protected
  2677. * @since 5.0.010 (2010-05-17)
  2678. */
  2679. protected function swapPageBoxCoordinates($page) {
  2680. $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  2681. foreach ($pageboxes as $type) {
  2682. // swap X and Y coordinates
  2683. if (isset($this->pagedim[$page][$type])) {
  2684. $tmp = $this->pagedim[$page][$type]['llx'];
  2685. $this->pagedim[$page][$type]['llx'] = $this->pagedim[$page][$type]['lly'];
  2686. $this->pagedim[$page][$type]['lly'] = $tmp;
  2687. $tmp = $this->pagedim[$page][$type]['urx'];
  2688. $this->pagedim[$page][$type]['urx'] = $this->pagedim[$page][$type]['ury'];
  2689. $this->pagedim[$page][$type]['ury'] = $tmp;
  2690. }
  2691. }
  2692. }
  2693. /**
  2694. * Set page orientation.
  2695. * @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>
  2696. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  2697. * @param $bottommargin (float) bottom margin of the page.
  2698. * @public
  2699. * @since 3.0.015 (2008-06-06)
  2700. */
  2701. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  2702. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  2703. // the boundaries of the physical medium on which the page shall be displayed or printed
  2704. $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true);
  2705. }
  2706. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  2707. // the visible region of default user space
  2708. $this->setPageBoxes($this->page, 'CropBox', $this->pagedim[$this->page]['MediaBox']['llx'], $this->pagedim[$this->page]['MediaBox']['lly'], $this->pagedim[$this->page]['MediaBox']['urx'], $this->pagedim[$this->page]['MediaBox']['ury'], true);
  2709. }
  2710. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  2711. // the region to which the contents of the page shall be clipped when output in a production environment
  2712. $this->setPageBoxes($this->page, 'BleedBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true);
  2713. }
  2714. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  2715. // the intended dimensions of the finished page after trimming
  2716. $this->setPageBoxes($this->page, 'TrimBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true);
  2717. }
  2718. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  2719. // the page's meaningful content (including potential white space)
  2720. $this->setPageBoxes($this->page, 'ArtBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true);
  2721. }
  2722. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  2723. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2724. $this->pagedim[$this->page]['Rotate'] = 0;
  2725. }
  2726. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2727. // The page's preferred zoom (magnification) factor
  2728. $this->pagedim[$this->page]['PZ'] = 1;
  2729. }
  2730. if ($this->fwPt > $this->fhPt) {
  2731. // landscape
  2732. $default_orientation = 'L';
  2733. } else {
  2734. // portrait
  2735. $default_orientation = 'P';
  2736. }
  2737. $valid_orientations = array('P', 'L');
  2738. if (empty($orientation)) {
  2739. $orientation = $default_orientation;
  2740. } else {
  2741. $orientation = strtoupper($orientation{0});
  2742. }
  2743. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2744. $this->CurOrientation = $orientation;
  2745. $this->wPt = $this->fhPt;
  2746. $this->hPt = $this->fwPt;
  2747. } else {
  2748. $this->CurOrientation = $default_orientation;
  2749. $this->wPt = $this->fwPt;
  2750. $this->hPt = $this->fhPt;
  2751. }
  2752. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2753. // swap X and Y coordinates (change page orientation)
  2754. $this->swapPageBoxCoordinates($this->page);
  2755. }
  2756. $this->w = $this->wPt / $this->k;
  2757. $this->h = $this->hPt / $this->k;
  2758. if ($this->empty_string($autopagebreak)) {
  2759. if (isset($this->AutoPageBreak)) {
  2760. $autopagebreak = $this->AutoPageBreak;
  2761. } else {
  2762. $autopagebreak = true;
  2763. }
  2764. }
  2765. if ($this->empty_string($bottommargin)) {
  2766. if (isset($this->bMargin)) {
  2767. $bottommargin = $this->bMargin;
  2768. } else {
  2769. // default value = 2 cm
  2770. $bottommargin = 2 * 28.35 / $this->k;
  2771. }
  2772. }
  2773. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2774. // store page dimensions
  2775. $this->pagedim[$this->page]['w'] = $this->wPt;
  2776. $this->pagedim[$this->page]['h'] = $this->hPt;
  2777. $this->pagedim[$this->page]['wk'] = $this->w;
  2778. $this->pagedim[$this->page]['hk'] = $this->h;
  2779. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2780. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2781. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2782. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2783. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2784. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2785. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2786. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2787. }
  2788. /**
  2789. * Set regular expression to detect withespaces or word separators.
  2790. * The pattern delimiter must be the forward-slash character "/".
  2791. * Some example patterns are:
  2792. * <pre>
  2793. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2794. * Unicode and PCRE unicode support: "/[^\S\P{Z}\xa0]/u"
  2795. * Unicode and PCRE unicode support in Chinese mode: "/[^\S\P{Z}\P{Lo}\xa0]/u"
  2796. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2797. * "\p{Z}" or "\p{Separator}": any kind of Unicode whitespace or invisible separator.
  2798. * "\p{Lo}" or "\p{Other_Letter}": a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  2799. * "\p{Lo}" is needed for Chinese characters because are packed next to each other without spaces in between.
  2800. * </pre>
  2801. * @param $re (string) regular expression (leave empty for default).
  2802. * @public
  2803. * @since 4.6.016 (2009-06-15)
  2804. */
  2805. public function setSpacesRE($re='/[^\S\xa0]/') {
  2806. $this->re_spaces = $re;
  2807. $re_parts = explode('/', $re);
  2808. // get pattern parts
  2809. $this->re_space = array();
  2810. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2811. $this->re_space['p'] = $re_parts[1];
  2812. } else {
  2813. $this->re_space['p'] = '[\s]';
  2814. }
  2815. // set pattern modifiers
  2816. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2817. $this->re_space['m'] = $re_parts[2];
  2818. } else {
  2819. $this->re_space['m'] = '';
  2820. }
  2821. }
  2822. /**
  2823. * Enable or disable Right-To-Left language mode
  2824. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2825. * @param $resetx (Boolean) if true reset the X position on direction change.
  2826. * @public
  2827. * @since 2.0.000 (2008-01-03)
  2828. */
  2829. public function setRTL($enable, $resetx=true) {
  2830. $enable = $enable ? true : false;
  2831. $resetx = ($resetx AND ($enable != $this->rtl));
  2832. $this->rtl = $enable;
  2833. $this->tmprtl = false;
  2834. if ($resetx) {
  2835. $this->Ln(0);
  2836. }
  2837. }
  2838. /**
  2839. * Return the RTL status
  2840. * @return boolean
  2841. * @public
  2842. * @since 4.0.012 (2008-07-24)
  2843. */
  2844. public function getRTL() {
  2845. return $this->rtl;
  2846. }
  2847. /**
  2848. * Force temporary RTL language direction
  2849. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2850. * @public
  2851. * @since 2.1.000 (2008-01-09)
  2852. */
  2853. public function setTempRTL($mode) {
  2854. $newmode = false;
  2855. switch (strtoupper($mode)) {
  2856. case 'LTR':
  2857. case 'L': {
  2858. if ($this->rtl) {
  2859. $newmode = 'L';
  2860. }
  2861. break;
  2862. }
  2863. case 'RTL':
  2864. case 'R': {
  2865. if (!$this->rtl) {
  2866. $newmode = 'R';
  2867. }
  2868. break;
  2869. }
  2870. case false:
  2871. default: {
  2872. $newmode = false;
  2873. break;
  2874. }
  2875. }
  2876. $this->tmprtl = $newmode;
  2877. }
  2878. /**
  2879. * Return the current temporary RTL status
  2880. * @return boolean
  2881. * @public
  2882. * @since 4.8.014 (2009-11-04)
  2883. */
  2884. public function isRTLTextDir() {
  2885. return ($this->rtl OR ($this->tmprtl == 'R'));
  2886. }
  2887. /**
  2888. * Set the last cell height.
  2889. * @param $h (float) cell height.
  2890. * @author Nicola Asuni
  2891. * @public
  2892. * @since 1.53.0.TC034
  2893. */
  2894. public function setLastH($h) {
  2895. $this->lasth = $h;
  2896. }
  2897. /**
  2898. * Reset the last cell height.
  2899. * @public
  2900. * @since 5.9.000 (2010-10-03)
  2901. */
  2902. public function resetLastH() {
  2903. $this->lasth = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  2904. }
  2905. /**
  2906. * Get the last cell height.
  2907. * @return last cell height
  2908. * @public
  2909. * @since 4.0.017 (2008-08-05)
  2910. */
  2911. public function getLastH() {
  2912. return $this->lasth;
  2913. }
  2914. /**
  2915. * Set the adjusting factor to convert pixels to user units.
  2916. * @param $scale (float) adjusting factor to convert pixels to user units.
  2917. * @author Nicola Asuni
  2918. * @public
  2919. * @since 1.5.2
  2920. */
  2921. public function setImageScale($scale) {
  2922. $this->imgscale = $scale;
  2923. }
  2924. /**
  2925. * Returns the adjusting factor to convert pixels to user units.
  2926. * @return float adjusting factor to convert pixels to user units.
  2927. * @author Nicola Asuni
  2928. * @public
  2929. * @since 1.5.2
  2930. */
  2931. public function getImageScale() {
  2932. return $this->imgscale;
  2933. }
  2934. /**
  2935. * Returns an array of page dimensions:
  2936. * <ul><li>$this->pagedim[$this->page]['w'] = page width in points</li><li>$this->pagedim[$this->page]['h'] = height in points</li><li>$this->pagedim[$this->page]['wk'] = page width in user units</li><li>$this->pagedim[$this->page]['hk'] = page height in user units</li><li>$this->pagedim[$this->page]['tm'] = top margin</li><li>$this->pagedim[$this->page]['bm'] = bottom margin</li><li>$this->pagedim[$this->page]['lm'] = left margin</li><li>$this->pagedim[$this->page]['rm'] = right margin</li><li>$this->pagedim[$this->page]['pb'] = auto page break</li><li>$this->pagedim[$this->page]['or'] = page orientation</li><li>$this->pagedim[$this->page]['olm'] = original left margin</li><li>$this->pagedim[$this->page]['orm'] = original right margin</li><li>$this->pagedim[$this->page]['Rotate'] = The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li><li>$this->pagedim[$this->page]['PZ'] = The page's preferred zoom (magnification) factor.</li><li>$this->pagedim[$this->page]['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation<ul><li>$this->pagedim[$this->page]['trans']['Dur'] = The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li><li>$this->pagedim[$this->page]['trans']['S'] = transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li><li>$this->pagedim[$this->page]['trans']['D'] = The duration of the transition effect, in seconds.</li><li>$this->pagedim[$this->page]['trans']['Dm'] = (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li><li>$this->pagedim[$this->page]['trans']['M'] = (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li><li>$this->pagedim[$this->page]['trans']['Di'] = (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li><li>$this->pagedim[$this->page]['trans']['SS'] = (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0. </li><li>$this->pagedim[$this->page]['trans']['B'] = (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li></ul></li><li>$this->pagedim[$this->page]['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed<ul><li>$this->pagedim[$this->page]['MediaBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['CropBox'] : the visible region of default user space<ul><li>$this->pagedim[$this->page]['CropBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment<ul><li>$this->pagedim[$this->page]['BleedBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['TrimBox'] : the intended dimensions of the finished page after trimming<ul><li>$this->pagedim[$this->page]['TrimBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['ArtBox'] : the extent of the page's meaningful content<ul><li>$this->pagedim[$this->page]['ArtBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['ury'] = upper-right y coordinate in points</li></ul></li></ul>
  2937. * @param $pagenum (int) page number (empty = current page)
  2938. * @return array of page dimensions.
  2939. * @author Nicola Asuni
  2940. * @public
  2941. * @since 4.5.027 (2009-03-16)
  2942. */
  2943. public function getPageDimensions($pagenum='') {
  2944. if (empty($pagenum)) {
  2945. $pagenum = $this->page;
  2946. }
  2947. return $this->pagedim[$pagenum];
  2948. }
  2949. /**
  2950. * Returns the page width in units.
  2951. * @param $pagenum (int) page number (empty = current page)
  2952. * @return int page width.
  2953. * @author Nicola Asuni
  2954. * @public
  2955. * @since 1.5.2
  2956. * @see getPageDimensions()
  2957. */
  2958. public function getPageWidth($pagenum='') {
  2959. if (empty($pagenum)) {
  2960. return $this->w;
  2961. }
  2962. return $this->pagedim[$pagenum]['w'];
  2963. }
  2964. /**
  2965. * Returns the page height in units.
  2966. * @param $pagenum (int) page number (empty = current page)
  2967. * @return int page height.
  2968. * @author Nicola Asuni
  2969. * @public
  2970. * @since 1.5.2
  2971. * @see getPageDimensions()
  2972. */
  2973. public function getPageHeight($pagenum='') {
  2974. if (empty($pagenum)) {
  2975. return $this->h;
  2976. }
  2977. return $this->pagedim[$pagenum]['h'];
  2978. }
  2979. /**
  2980. * Returns the page break margin.
  2981. * @param $pagenum (int) page number (empty = current page)
  2982. * @return int page break margin.
  2983. * @author Nicola Asuni
  2984. * @public
  2985. * @since 1.5.2
  2986. * @see getPageDimensions()
  2987. */
  2988. public function getBreakMargin($pagenum='') {
  2989. if (empty($pagenum)) {
  2990. return $this->bMargin;
  2991. }
  2992. return $this->pagedim[$pagenum]['bm'];
  2993. }
  2994. /**
  2995. * Returns the scale factor (number of points in user unit).
  2996. * @return int scale factor.
  2997. * @author Nicola Asuni
  2998. * @public
  2999. * @since 1.5.2
  3000. */
  3001. public function getScaleFactor() {
  3002. return $this->k;
  3003. }
  3004. /**
  3005. * Defines the left, top and right margins.
  3006. * @param $left (float) Left margin.
  3007. * @param $top (float) Top margin.
  3008. * @param $right (float) Right margin. Default value is the left one.
  3009. * @param $keepmargins (boolean) if true overwrites the default page margins
  3010. * @public
  3011. * @since 1.0
  3012. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  3013. */
  3014. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  3015. //Set left, top and right margins
  3016. $this->lMargin = $left;
  3017. $this->tMargin = $top;
  3018. if ($right == -1) {
  3019. $right = $left;
  3020. }
  3021. $this->rMargin = $right;
  3022. if ($keepmargins) {
  3023. // overwrite original values
  3024. $this->original_lMargin = $this->lMargin;
  3025. $this->original_rMargin = $this->rMargin;
  3026. }
  3027. }
  3028. /**
  3029. * 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.
  3030. * @param $margin (float) The margin.
  3031. * @public
  3032. * @since 1.4
  3033. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  3034. */
  3035. public function SetLeftMargin($margin) {
  3036. //Set left margin
  3037. $this->lMargin = $margin;
  3038. if (($this->page > 0) AND ($this->x < $margin)) {
  3039. $this->x = $margin;
  3040. }
  3041. }
  3042. /**
  3043. * Defines the top margin. The method can be called before creating the first page.
  3044. * @param $margin (float) The margin.
  3045. * @public
  3046. * @since 1.5
  3047. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  3048. */
  3049. public function SetTopMargin($margin) {
  3050. //Set top margin
  3051. $this->tMargin = $margin;
  3052. if (($this->page > 0) AND ($this->y < $margin)) {
  3053. $this->y = $margin;
  3054. }
  3055. }
  3056. /**
  3057. * Defines the right margin. The method can be called before creating the first page.
  3058. * @param $margin (float) The margin.
  3059. * @public
  3060. * @since 1.5
  3061. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  3062. */
  3063. public function SetRightMargin($margin) {
  3064. $this->rMargin = $margin;
  3065. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  3066. $this->x = $this->w - $margin;
  3067. }
  3068. }
  3069. /**
  3070. * Set the same internal Cell padding for top, right, bottom, left-
  3071. * @param $pad (float) internal padding.
  3072. * @public
  3073. * @since 2.1.000 (2008-01-09)
  3074. * @see getCellPaddings(), setCellPaddings()
  3075. */
  3076. public function SetCellPadding($pad) {
  3077. if ($pad >= 0) {
  3078. $this->cell_padding['L'] = $pad;
  3079. $this->cell_padding['T'] = $pad;
  3080. $this->cell_padding['R'] = $pad;
  3081. $this->cell_padding['B'] = $pad;
  3082. }
  3083. }
  3084. /**
  3085. * Set the internal Cell paddings.
  3086. * @param $left (float) left padding
  3087. * @param $top (float) top padding
  3088. * @param $right (float) right padding
  3089. * @param $bottom (float) bottom padding
  3090. * @public
  3091. * @since 5.9.000 (2010-10-03)
  3092. * @see getCellPaddings(), SetCellPadding()
  3093. */
  3094. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  3095. if (($left !== '') AND ($left >= 0)) {
  3096. $this->cell_padding['L'] = $left;
  3097. }
  3098. if (($top !== '') AND ($top >= 0)) {
  3099. $this->cell_padding['T'] = $top;
  3100. }
  3101. if (($right !== '') AND ($right >= 0)) {
  3102. $this->cell_padding['R'] = $right;
  3103. }
  3104. if (($bottom !== '') AND ($bottom >= 0)) {
  3105. $this->cell_padding['B'] = $bottom;
  3106. }
  3107. }
  3108. /**
  3109. * Get the internal Cell padding array.
  3110. * @return array of padding values
  3111. * @public
  3112. * @since 5.9.000 (2010-10-03)
  3113. * @see setCellPaddings(), SetCellPadding()
  3114. */
  3115. public function getCellPaddings() {
  3116. return $this->cell_padding;
  3117. }
  3118. /**
  3119. * Set the internal Cell margins.
  3120. * @param $left (float) left margin
  3121. * @param $top (float) top margin
  3122. * @param $right (float) right margin
  3123. * @param $bottom (float) bottom margin
  3124. * @public
  3125. * @since 5.9.000 (2010-10-03)
  3126. * @see getCellMargins()
  3127. */
  3128. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  3129. if (($left !== '') AND ($left >= 0)) {
  3130. $this->cell_margin['L'] = $left;
  3131. }
  3132. if (($top !== '') AND ($top >= 0)) {
  3133. $this->cell_margin['T'] = $top;
  3134. }
  3135. if (($right !== '') AND ($right >= 0)) {
  3136. $this->cell_margin['R'] = $right;
  3137. }
  3138. if (($bottom !== '') AND ($bottom >= 0)) {
  3139. $this->cell_margin['B'] = $bottom;
  3140. }
  3141. }
  3142. /**
  3143. * Get the internal Cell margin array.
  3144. * @return array of margin values
  3145. * @public
  3146. * @since 5.9.000 (2010-10-03)
  3147. * @see setCellMargins()
  3148. */
  3149. public function getCellMargins() {
  3150. return $this->cell_margin;
  3151. }
  3152. /**
  3153. * Adjust the internal Cell padding array to take account of the line width.
  3154. * @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)))
  3155. * @return array of adjustments
  3156. * @public
  3157. * @since 5.9.000 (2010-10-03)
  3158. */
  3159. protected function adjustCellPadding($brd=0) {
  3160. if (empty($brd)) {
  3161. return;
  3162. }
  3163. if (is_string($brd)) {
  3164. // convert string to array
  3165. $slen = strlen($brd);
  3166. $newbrd = array();
  3167. for ($i = 0; $i < $slen; ++$i) {
  3168. $newbrd[$brd[$i]] = true;
  3169. }
  3170. $brd = $newbrd;
  3171. } elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
  3172. $brd = array('LRTB' => true);
  3173. }
  3174. if (!is_array($brd)) {
  3175. return;
  3176. }
  3177. // store current cell padding
  3178. $cp = $this->cell_padding;
  3179. // select border mode
  3180. if (isset($brd['mode'])) {
  3181. $mode = $brd['mode'];
  3182. unset($brd['mode']);
  3183. } else {
  3184. $mode = 'normal';
  3185. }
  3186. // process borders
  3187. foreach ($brd as $border => $style) {
  3188. $line_width = $this->LineWidth;
  3189. if (is_array($style) AND isset($style['width'])) {
  3190. // get border width
  3191. $line_width = $style['width'];
  3192. }
  3193. $adj = 0; // line width inside the cell
  3194. switch ($mode) {
  3195. case 'ext': {
  3196. $adj = 0;
  3197. break;
  3198. }
  3199. case 'int': {
  3200. $adj = $line_width;
  3201. break;
  3202. }
  3203. case 'normal':
  3204. default: {
  3205. $adj = ($line_width / 2);
  3206. break;
  3207. }
  3208. }
  3209. // correct internal cell padding if required to avoid overlap between text and lines
  3210. if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
  3211. $this->cell_padding['T'] = $adj;
  3212. }
  3213. if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
  3214. $this->cell_padding['R'] = $adj;
  3215. }
  3216. if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
  3217. $this->cell_padding['B'] = $adj;
  3218. }
  3219. if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
  3220. $this->cell_padding['L'] = $adj;
  3221. }
  3222. }
  3223. 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']));
  3224. }
  3225. /**
  3226. * 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.
  3227. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  3228. * @param $margin (float) Distance from the bottom of the page.
  3229. * @public
  3230. * @since 1.0
  3231. * @see Cell(), MultiCell(), AcceptPageBreak()
  3232. */
  3233. public function SetAutoPageBreak($auto, $margin=0) {
  3234. $this->AutoPageBreak = $auto ? true : false;
  3235. $this->bMargin = $margin;
  3236. $this->PageBreakTrigger = $this->h - $margin;
  3237. }
  3238. /**
  3239. * Return the auto-page-break mode (true or false).
  3240. * @return boolean auto-page-break mode
  3241. * @public
  3242. * @since 5.9.088
  3243. */
  3244. public function getAutoPageBreak() {
  3245. return $this->AutoPageBreak;
  3246. }
  3247. /**
  3248. * Defines the way the document is to be displayed by the viewer.
  3249. * @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>
  3250. * @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>
  3251. * @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>
  3252. * @public
  3253. * @since 1.2
  3254. */
  3255. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  3256. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  3257. $this->ZoomMode = $zoom;
  3258. } else {
  3259. $this->Error('Incorrect zoom display mode: '.$zoom);
  3260. }
  3261. switch ($layout) {
  3262. case 'default':
  3263. case 'single':
  3264. case 'SinglePage': {
  3265. $this->LayoutMode = 'SinglePage';
  3266. break;
  3267. }
  3268. case 'continuous':
  3269. case 'OneColumn': {
  3270. $this->LayoutMode = 'OneColumn';
  3271. break;
  3272. }
  3273. case 'two':
  3274. case 'TwoColumnLeft': {
  3275. $this->LayoutMode = 'TwoColumnLeft';
  3276. break;
  3277. }
  3278. case 'TwoColumnRight': {
  3279. $this->LayoutMode = 'TwoColumnRight';
  3280. break;
  3281. }
  3282. case 'TwoPageLeft': {
  3283. $this->LayoutMode = 'TwoPageLeft';
  3284. break;
  3285. }
  3286. case 'TwoPageRight': {
  3287. $this->LayoutMode = 'TwoPageRight';
  3288. break;
  3289. }
  3290. default: {
  3291. $this->LayoutMode = 'SinglePage';
  3292. }
  3293. }
  3294. switch ($mode) {
  3295. case 'UseNone': {
  3296. $this->PageMode = 'UseNone';
  3297. break;
  3298. }
  3299. case 'UseOutlines': {
  3300. $this->PageMode = 'UseOutlines';
  3301. break;
  3302. }
  3303. case 'UseThumbs': {
  3304. $this->PageMode = 'UseThumbs';
  3305. break;
  3306. }
  3307. case 'FullScreen': {
  3308. $this->PageMode = 'FullScreen';
  3309. break;
  3310. }
  3311. case 'UseOC': {
  3312. $this->PageMode = 'UseOC';
  3313. break;
  3314. }
  3315. case '': {
  3316. $this->PageMode = 'UseAttachments';
  3317. break;
  3318. }
  3319. default: {
  3320. $this->PageMode = 'UseNone';
  3321. }
  3322. }
  3323. }
  3324. /**
  3325. * 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.
  3326. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  3327. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  3328. * @public
  3329. * @since 1.4
  3330. */
  3331. public function SetCompression($compress=true) {
  3332. if (function_exists('gzcompress')) {
  3333. $this->compress = $compress ? true : false;
  3334. } else {
  3335. $this->compress = false;
  3336. }
  3337. }
  3338. /**
  3339. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  3340. * @param $mode (boolean) If true force sRGB output intent.
  3341. * @public
  3342. * @since 5.9.121 (2011-09-28)
  3343. */
  3344. public function setSRGBmode($mode=false) {
  3345. $this->force_srgb = $mode ? true : false;
  3346. }
  3347. /**
  3348. * Turn on/off Unicode mode for document information dictionary (meta tags).
  3349. * This has effect only when unicode mode is set to false.
  3350. * @param $unicode (boolean) if true set the meta information in Unicode
  3351. * @since 5.9.027 (2010-12-01)
  3352. * @public
  3353. */
  3354. public function SetDocInfoUnicode($unicode=true) {
  3355. $this->docinfounicode = $unicode ? true : false;
  3356. }
  3357. /**
  3358. * Defines the title of the document.
  3359. * @param $title (string) The title.
  3360. * @public
  3361. * @since 1.2
  3362. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  3363. */
  3364. public function SetTitle($title) {
  3365. $this->title = $title;
  3366. }
  3367. /**
  3368. * Defines the subject of the document.
  3369. * @param $subject (string) The subject.
  3370. * @public
  3371. * @since 1.2
  3372. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  3373. */
  3374. public function SetSubject($subject) {
  3375. $this->subject = $subject;
  3376. }
  3377. /**
  3378. * Defines the author of the document.
  3379. * @param $author (string) The name of the author.
  3380. * @public
  3381. * @since 1.2
  3382. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  3383. */
  3384. public function SetAuthor($author) {
  3385. $this->author = $author;
  3386. }
  3387. /**
  3388. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  3389. * @param $keywords (string) The list of keywords.
  3390. * @public
  3391. * @since 1.2
  3392. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  3393. */
  3394. public function SetKeywords($keywords) {
  3395. $this->keywords = $keywords;
  3396. }
  3397. /**
  3398. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  3399. * @param $creator (string) The name of the creator.
  3400. * @public
  3401. * @since 1.2
  3402. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  3403. */
  3404. public function SetCreator($creator) {
  3405. $this->creator = $creator;
  3406. }
  3407. /**
  3408. * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
  3409. * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
  3410. * @param $msg (string) The error message
  3411. * @public
  3412. * @since 1.0
  3413. */
  3414. public function Error($msg) {
  3415. // unset all class variables
  3416. $this->_destroy(true);
  3417. // exit program and print error
  3418. die('<strong>TCPDF ERROR: </strong>'.$msg);
  3419. }
  3420. /**
  3421. * This method begins the generation of the PDF document.
  3422. * It is not necessary to call it explicitly because AddPage() does it automatically.
  3423. * Note: no page is created by this method
  3424. * @public
  3425. * @since 1.0
  3426. * @see AddPage(), Close()
  3427. */
  3428. public function Open() {
  3429. $this->state = 1;
  3430. }
  3431. /**
  3432. * Terminates the PDF document.
  3433. * It is not necessary to call this method explicitly because Output() does it automatically.
  3434. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  3435. * @public
  3436. * @since 1.0
  3437. * @see Open(), Output()
  3438. */
  3439. public function Close() {
  3440. if ($this->state == 3) {
  3441. return;
  3442. }
  3443. if ($this->page == 0) {
  3444. $this->AddPage();
  3445. }
  3446. $this->endLayer();
  3447. // save current graphic settings
  3448. $gvars = $this->getGraphicVars();
  3449. $this->setEqualColumns();
  3450. $this->lastpage(true);
  3451. $this->SetAutoPageBreak(false);
  3452. $this->x = 0;
  3453. $this->y = $this->h - (1 / $this->k);
  3454. $this->lMargin = 0;
  3455. $this->_out('q');
  3456. $this->SetFont('helvetica', '', 1);
  3457. $this->setTextRenderingMode(0, false, false);
  3458. $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";
  3459. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  3460. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  3461. $this->_out('Q');
  3462. // restore graphic settings
  3463. $this->setGraphicVars($gvars);
  3464. // close page
  3465. $this->endPage();
  3466. // close document
  3467. $this->_enddoc();
  3468. // unset all class variables (except critical ones)
  3469. $this->_destroy(false);
  3470. }
  3471. /**
  3472. * Move pointer at the specified document page and update page dimensions.
  3473. * @param $pnum (int) page number (1 ... numpages)
  3474. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  3475. * @public
  3476. * @since 2.1.000 (2008-01-07)
  3477. * @see getPage(), lastpage(), getNumPages()
  3478. */
  3479. public function setPage($pnum, $resetmargins=false) {
  3480. if (($pnum == $this->page) AND ($this->state == 2)) {
  3481. return;
  3482. }
  3483. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  3484. $this->state = 2;
  3485. // save current graphic settings
  3486. //$gvars = $this->getGraphicVars();
  3487. $oldpage = $this->page;
  3488. $this->page = $pnum;
  3489. $this->wPt = $this->pagedim[$this->page]['w'];
  3490. $this->hPt = $this->pagedim[$this->page]['h'];
  3491. $this->w = $this->pagedim[$this->page]['wk'];
  3492. $this->h = $this->pagedim[$this->page]['hk'];
  3493. $this->tMargin = $this->pagedim[$this->page]['tm'];
  3494. $this->bMargin = $this->pagedim[$this->page]['bm'];
  3495. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  3496. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  3497. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  3498. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  3499. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  3500. // restore graphic settings
  3501. //$this->setGraphicVars($gvars);
  3502. if ($resetmargins) {
  3503. $this->lMargin = $this->pagedim[$this->page]['olm'];
  3504. $this->rMargin = $this->pagedim[$this->page]['orm'];
  3505. $this->SetY($this->tMargin);
  3506. } else {
  3507. // account for booklet mode
  3508. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  3509. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  3510. $this->lMargin += $deltam;
  3511. $this->rMargin -= $deltam;
  3512. }
  3513. }
  3514. } else {
  3515. $this->Error('Wrong page number on setPage() function: '.$pnum);
  3516. }
  3517. }
  3518. /**
  3519. * Reset pointer to the last document page.
  3520. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  3521. * @public
  3522. * @since 2.0.000 (2008-01-04)
  3523. * @see setPage(), getPage(), getNumPages()
  3524. */
  3525. public function lastPage($resetmargins=false) {
  3526. $this->setPage($this->getNumPages(), $resetmargins);
  3527. }
  3528. /**
  3529. * Get current document page number.
  3530. * @return int page number
  3531. * @public
  3532. * @since 2.1.000 (2008-01-07)
  3533. * @see setPage(), lastpage(), getNumPages()
  3534. */
  3535. public function getPage() {
  3536. return $this->page;
  3537. }
  3538. /**
  3539. * Get the total number of insered pages.
  3540. * @return int number of pages
  3541. * @public
  3542. * @since 2.1.000 (2008-01-07)
  3543. * @see setPage(), getPage(), lastpage()
  3544. */
  3545. public function getNumPages() {
  3546. return $this->numpages;
  3547. }
  3548. /**
  3549. * Adds a new TOC (Table Of Content) page to the document.
  3550. * @param $orientation (string) page orientation.
  3551. * @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().
  3552. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  3553. * @public
  3554. * @since 5.0.001 (2010-05-06)
  3555. * @see AddPage(), startPage(), endPage(), endTOCPage()
  3556. */
  3557. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  3558. $this->AddPage($orientation, $format, $keepmargins, true);
  3559. }
  3560. /**
  3561. * Terminate the current TOC (Table Of Content) page
  3562. * @public
  3563. * @since 5.0.001 (2010-05-06)
  3564. * @see AddPage(), startPage(), endPage(), addTOCPage()
  3565. */
  3566. public function endTOCPage() {
  3567. $this->endPage(true);
  3568. }
  3569. /**
  3570. * 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).
  3571. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  3572. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  3573. * @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().
  3574. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  3575. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  3576. * @public
  3577. * @since 1.0
  3578. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  3579. */
  3580. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  3581. if ($this->inxobj) {
  3582. // we are inside an XObject template
  3583. return;
  3584. }
  3585. if (!isset($this->original_lMargin) OR $keepmargins) {
  3586. $this->original_lMargin = $this->lMargin;
  3587. }
  3588. if (!isset($this->original_rMargin) OR $keepmargins) {
  3589. $this->original_rMargin = $this->rMargin;
  3590. }
  3591. // terminate previous page
  3592. $this->endPage();
  3593. // start new page
  3594. $this->startPage($orientation, $format, $tocpage);
  3595. }
  3596. /**
  3597. * Terminate the current page
  3598. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  3599. * @public
  3600. * @since 4.2.010 (2008-11-14)
  3601. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  3602. */
  3603. public function endPage($tocpage=false) {
  3604. // check if page is already closed
  3605. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  3606. return;
  3607. }
  3608. // print page footer
  3609. $this->setFooter();
  3610. // close page
  3611. $this->_endpage();
  3612. // mark page as closed
  3613. $this->pageopen[$this->page] = false;
  3614. if ($tocpage) {
  3615. $this->tocpage = false;
  3616. }
  3617. }
  3618. /**
  3619. * Starts a new page to the document. The page must be closed using the endPage() function.
  3620. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  3621. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  3622. * @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().
  3623. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  3624. * @since 4.2.010 (2008-11-14)
  3625. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  3626. * @public
  3627. */
  3628. public function startPage($orientation='', $format='', $tocpage=false) {
  3629. if ($tocpage) {
  3630. $this->tocpage = true;
  3631. }
  3632. // move page numbers of documents to be attached
  3633. if ($this->tocpage) {
  3634. // move reference to unexistent pages (used for page attachments)
  3635. // adjust outlines
  3636. $tmpoutlines = $this->outlines;
  3637. foreach ($tmpoutlines as $key => $outline) {
  3638. if ($outline['p'] > $this->numpages) {
  3639. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  3640. }
  3641. }
  3642. // adjust dests
  3643. $tmpdests = $this->dests;
  3644. foreach ($tmpdests as $key => $dest) {
  3645. if ($dest['p'] > $this->numpages) {
  3646. $this->dests[$key]['p'] = ($dest['p'] + 1);
  3647. }
  3648. }
  3649. // adjust links
  3650. $tmplinks = $this->links;
  3651. foreach ($tmplinks as $key => $link) {
  3652. if ($link[0] > $this->numpages) {
  3653. $this->links[$key][0] = ($link[0] + 1);
  3654. }
  3655. }
  3656. }
  3657. if ($this->numpages > $this->page) {
  3658. // this page has been already added
  3659. $this->setPage($this->page + 1);
  3660. $this->SetY($this->tMargin);
  3661. return;
  3662. }
  3663. // start a new page
  3664. if ($this->state == 0) {
  3665. $this->Open();
  3666. }
  3667. ++$this->numpages;
  3668. $this->swapMargins($this->booklet);
  3669. // save current graphic settings
  3670. $gvars = $this->getGraphicVars();
  3671. // start new page
  3672. $this->_beginpage($orientation, $format);
  3673. // mark page as open
  3674. $this->pageopen[$this->page] = true;
  3675. // restore graphic settings
  3676. $this->setGraphicVars($gvars);
  3677. // mark this point
  3678. $this->setPageMark();
  3679. // print page header
  3680. $this->setHeader();
  3681. // restore graphic settings
  3682. $this->setGraphicVars($gvars);
  3683. // mark this point
  3684. $this->setPageMark();
  3685. // print table header (if any)
  3686. $this->setTableHeader();
  3687. // set mark for empty page check
  3688. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  3689. }
  3690. /**
  3691. * Set start-writing mark on current page stream used to put borders and fills.
  3692. * Borders and fills are always created after content and inserted on the position marked by this method.
  3693. * This function must be called after calling Image() function for a background image.
  3694. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  3695. * @public
  3696. * @since 4.0.016 (2008-07-30)
  3697. */
  3698. public function setPageMark() {
  3699. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  3700. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  3701. $this->setContentMark();
  3702. }
  3703. /**
  3704. * Set start-writing mark on selected page.
  3705. * Borders and fills are always created after content and inserted on the position marked by this method.
  3706. * @param $page (int) page number (default is the current page)
  3707. * @protected
  3708. * @since 4.6.021 (2009-07-20)
  3709. */
  3710. protected function setContentMark($page=0) {
  3711. if ($page <= 0) {
  3712. $page = $this->page;
  3713. }
  3714. if (isset($this->footerlen[$page])) {
  3715. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  3716. } else {
  3717. $this->cntmrk[$page] = $this->pagelen[$page];
  3718. }
  3719. }
  3720. /**
  3721. * Set header data.
  3722. * @param $ln (string) header image logo
  3723. * @param $lw (string) header image logo width in mm
  3724. * @param $ht (string) string to print as title on document header
  3725. * @param $hs (string) string to print on document header
  3726. * @public
  3727. */
  3728. public function setHeaderData($ln='', $lw=0, $ht='', $hs='') {
  3729. $this->header_logo = $ln;
  3730. $this->header_logo_width = $lw;
  3731. $this->header_title = $ht;
  3732. $this->header_string = $hs;
  3733. }
  3734. /**
  3735. * Returns header data:
  3736. * <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>
  3737. * @return array()
  3738. * @public
  3739. * @since 4.0.012 (2008-07-24)
  3740. */
  3741. public function getHeaderData() {
  3742. $ret = array();
  3743. $ret['logo'] = $this->header_logo;
  3744. $ret['logo_width'] = $this->header_logo_width;
  3745. $ret['title'] = $this->header_title;
  3746. $ret['string'] = $this->header_string;
  3747. return $ret;
  3748. }
  3749. /**
  3750. * Set header margin.
  3751. * (minimum distance between header and top page margin)
  3752. * @param $hm (int) distance in user units
  3753. * @public
  3754. */
  3755. public function setHeaderMargin($hm=10) {
  3756. $this->header_margin = $hm;
  3757. }
  3758. /**
  3759. * Returns header margin in user units.
  3760. * @return float
  3761. * @since 4.0.012 (2008-07-24)
  3762. * @public
  3763. */
  3764. public function getHeaderMargin() {
  3765. return $this->header_margin;
  3766. }
  3767. /**
  3768. * Set footer margin.
  3769. * (minimum distance between footer and bottom page margin)
  3770. * @param $fm (int) distance in user units
  3771. * @public
  3772. */
  3773. public function setFooterMargin($fm=10) {
  3774. $this->footer_margin = $fm;
  3775. }
  3776. /**
  3777. * Returns footer margin in user units.
  3778. * @return float
  3779. * @since 4.0.012 (2008-07-24)
  3780. * @public
  3781. */
  3782. public function getFooterMargin() {
  3783. return $this->footer_margin;
  3784. }
  3785. /**
  3786. * Set a flag to print page header.
  3787. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3788. * @public
  3789. */
  3790. public function setPrintHeader($val=true) {
  3791. $this->print_header = $val ? true : false;
  3792. }
  3793. /**
  3794. * Set a flag to print page footer.
  3795. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3796. * @public
  3797. */
  3798. public function setPrintFooter($val=true) {
  3799. $this->print_footer = $val ? true : false;
  3800. }
  3801. /**
  3802. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3803. * @return float
  3804. * @public
  3805. */
  3806. public function getImageRBX() {
  3807. return $this->img_rb_x;
  3808. }
  3809. /**
  3810. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3811. * @return float
  3812. * @public
  3813. */
  3814. public function getImageRBY() {
  3815. return $this->img_rb_y;
  3816. }
  3817. /**
  3818. * Reset the xobject template used by Header() method.
  3819. * @public
  3820. */
  3821. public function resetHeaderTemplate() {
  3822. $this->header_xobjid = -1;
  3823. }
  3824. /**
  3825. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3826. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3827. * @public
  3828. */
  3829. public function setHeaderTemplateAutoreset($val=true) {
  3830. $this->header_xobj_autoreset = $val ? true : false;
  3831. }
  3832. /**
  3833. * This method is used to render the page header.
  3834. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3835. * @public
  3836. */
  3837. public function Header() {
  3838. if ($this->header_xobjid < 0) {
  3839. // start a new XObject Template
  3840. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3841. $headerfont = $this->getHeaderFont();
  3842. $headerdata = $this->getHeaderData();
  3843. $this->y = $this->header_margin;
  3844. if ($this->rtl) {
  3845. $this->x = $this->w - $this->original_rMargin;
  3846. } else {
  3847. $this->x = $this->original_lMargin;
  3848. }
  3849. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3850. $imgtype = $this->getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3851. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3852. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3853. } elseif ($imgtype == 'svg') {
  3854. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3855. } else {
  3856. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3857. }
  3858. $imgy = $this->getImageRBY();
  3859. } else {
  3860. $imgy = $this->y;
  3861. }
  3862. $cell_height = round(($this->cell_height_ratio * $headerfont[2]) / $this->k, 2);
  3863. // set starting margin for text data cell
  3864. if ($this->getRTL()) {
  3865. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3866. } else {
  3867. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3868. }
  3869. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3870. $this->SetTextColor(0, 0, 0);
  3871. // header title
  3872. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3873. $this->SetX($header_x);
  3874. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3875. // header string
  3876. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3877. $this->SetX($header_x);
  3878. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3879. // print an ending header line
  3880. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
  3881. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3882. if ($this->rtl) {
  3883. $this->SetX($this->original_rMargin);
  3884. } else {
  3885. $this->SetX($this->original_lMargin);
  3886. }
  3887. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3888. $this->endTemplate();
  3889. }
  3890. // print header template
  3891. $x = 0;
  3892. $dx = 0;
  3893. if ($this->booklet AND (($this->page % 2) == 0)) {
  3894. // adjust margins for booklet mode
  3895. $dx = ($this->original_lMargin - $this->original_rMargin);
  3896. }
  3897. if ($this->rtl) {
  3898. $x = $this->w + $dx;
  3899. } else {
  3900. $x = 0 + $dx;
  3901. }
  3902. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  3903. if ($this->header_xobj_autoreset) {
  3904. // reset header xobject template at each page
  3905. $this->header_xobjid = -1;
  3906. }
  3907. }
  3908. /**
  3909. * This method is used to render the page footer.
  3910. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3911. * @public
  3912. */
  3913. public function Footer() {
  3914. $cur_y = $this->y;
  3915. $this->SetTextColor(0, 0, 0);
  3916. //set style for cell border
  3917. $line_width = 0.85 / $this->k;
  3918. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
  3919. //print document barcode
  3920. $barcode = $this->getBarcode();
  3921. if (!empty($barcode)) {
  3922. $this->Ln($line_width);
  3923. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  3924. $style = array(
  3925. 'position' => $this->rtl?'R':'L',
  3926. 'align' => $this->rtl?'R':'L',
  3927. 'stretch' => false,
  3928. 'fitwidth' => true,
  3929. 'cellfitalign' => '',
  3930. 'border' => false,
  3931. 'padding' => 0,
  3932. 'fgcolor' => array(0,0,0),
  3933. 'bgcolor' => false,
  3934. 'text' => false
  3935. );
  3936. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  3937. }
  3938. if (empty($this->pagegroups)) {
  3939. $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  3940. } else {
  3941. $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  3942. }
  3943. $this->SetY($cur_y);
  3944. //Print page number
  3945. if ($this->getRTL()) {
  3946. $this->SetX($this->original_rMargin);
  3947. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  3948. } else {
  3949. $this->SetX($this->original_lMargin);
  3950. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  3951. }
  3952. }
  3953. /**
  3954. * This method is used to render the page header.
  3955. * @protected
  3956. * @since 4.0.012 (2008-07-24)
  3957. */
  3958. protected function setHeader() {
  3959. if (!$this->print_header) {
  3960. return;
  3961. }
  3962. $this->InHeader = true;
  3963. $this->setGraphicVars($this->default_graphic_vars);
  3964. $temp_thead = $this->thead;
  3965. $temp_theadMargins = $this->theadMargins;
  3966. $lasth = $this->lasth;
  3967. $this->_out('q');
  3968. $this->rMargin = $this->original_rMargin;
  3969. $this->lMargin = $this->original_lMargin;
  3970. $this->SetCellPadding(0);
  3971. //set current position
  3972. if ($this->rtl) {
  3973. $this->SetXY($this->original_rMargin, $this->header_margin);
  3974. } else {
  3975. $this->SetXY($this->original_lMargin, $this->header_margin);
  3976. }
  3977. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  3978. $this->Header();
  3979. //restore position
  3980. if ($this->rtl) {
  3981. $this->SetXY($this->original_rMargin, $this->tMargin);
  3982. } else {
  3983. $this->SetXY($this->original_lMargin, $this->tMargin);
  3984. }
  3985. $this->_out('Q');
  3986. $this->lasth = $lasth;
  3987. $this->thead = $temp_thead;
  3988. $this->theadMargins = $temp_theadMargins;
  3989. $this->newline = false;
  3990. $this->InHeader = false;
  3991. }
  3992. /**
  3993. * This method is used to render the page footer.
  3994. * @protected
  3995. * @since 4.0.012 (2008-07-24)
  3996. */
  3997. protected function setFooter() {
  3998. //Page footer
  3999. $this->InFooter = true;
  4000. // save current graphic settings
  4001. $gvars = $this->getGraphicVars();
  4002. // mark this point
  4003. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  4004. $this->_out("\n");
  4005. if ($this->print_footer) {
  4006. $this->setGraphicVars($this->default_graphic_vars);
  4007. $this->current_column = 0;
  4008. $this->num_columns = 1;
  4009. $temp_thead = $this->thead;
  4010. $temp_theadMargins = $this->theadMargins;
  4011. $lasth = $this->lasth;
  4012. $this->_out('q');
  4013. $this->rMargin = $this->original_rMargin;
  4014. $this->lMargin = $this->original_lMargin;
  4015. $this->SetCellPadding(0);
  4016. //set current position
  4017. $footer_y = $this->h - $this->footer_margin;
  4018. if ($this->rtl) {
  4019. $this->SetXY($this->original_rMargin, $footer_y);
  4020. } else {
  4021. $this->SetXY($this->original_lMargin, $footer_y);
  4022. }
  4023. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  4024. $this->Footer();
  4025. //restore position
  4026. if ($this->rtl) {
  4027. $this->SetXY($this->original_rMargin, $this->tMargin);
  4028. } else {
  4029. $this->SetXY($this->original_lMargin, $this->tMargin);
  4030. }
  4031. $this->_out('Q');
  4032. $this->lasth = $lasth;
  4033. $this->thead = $temp_thead;
  4034. $this->theadMargins = $temp_theadMargins;
  4035. }
  4036. // restore graphic settings
  4037. $this->setGraphicVars($gvars);
  4038. $this->current_column = $gvars['current_column'];
  4039. $this->num_columns = $gvars['num_columns'];
  4040. // calculate footer length
  4041. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  4042. $this->InFooter = false;
  4043. }
  4044. /**
  4045. * Check if we are on the page body (excluding page header and footer).
  4046. * @return true if we are not in page header nor in page footer, false otherwise.
  4047. * @protected
  4048. * @since 5.9.091 (2011-06-15)
  4049. */
  4050. protected function inPageBody() {
  4051. return (($this->InHeader === false) AND ($this->InFooter === false));
  4052. }
  4053. /**
  4054. * This method is used to render the table header on new page (if any).
  4055. * @protected
  4056. * @since 4.5.030 (2009-03-25)
  4057. */
  4058. protected function setTableHeader() {
  4059. if ($this->num_columns > 1) {
  4060. // multi column mode
  4061. return;
  4062. }
  4063. if (isset($this->theadMargins['top'])) {
  4064. // restore the original top-margin
  4065. $this->tMargin = $this->theadMargins['top'];
  4066. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  4067. $this->y = $this->tMargin;
  4068. }
  4069. if (!$this->empty_string($this->thead) AND (!$this->inthead)) {
  4070. // set margins
  4071. $prev_lMargin = $this->lMargin;
  4072. $prev_rMargin = $this->rMargin;
  4073. $prev_cell_padding = $this->cell_padding;
  4074. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  4075. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  4076. $this->cell_padding = $this->theadMargins['cell_padding'];
  4077. if ($this->rtl) {
  4078. $this->x = $this->w - $this->rMargin;
  4079. } else {
  4080. $this->x = $this->lMargin;
  4081. }
  4082. // account for special "cell" mode
  4083. if ($this->theadMargins['cell']) {
  4084. if ($this->rtl) {
  4085. $this->x -= $this->cell_padding['R'];
  4086. } else {
  4087. $this->x += $this->cell_padding['L'];
  4088. }
  4089. }
  4090. // print table header
  4091. $this->writeHTML($this->thead, false, false, false, false, '');
  4092. // set new top margin to skip the table headers
  4093. if (!isset($this->theadMargins['top'])) {
  4094. $this->theadMargins['top'] = $this->tMargin;
  4095. }
  4096. // store end of header position
  4097. if (!isset($this->columns[0]['th'])) {
  4098. $this->columns[0]['th'] = array();
  4099. }
  4100. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  4101. $this->tMargin = $this->y;
  4102. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  4103. $this->lasth = 0;
  4104. $this->lMargin = $prev_lMargin;
  4105. $this->rMargin = $prev_rMargin;
  4106. $this->cell_padding = $prev_cell_padding;
  4107. }
  4108. }
  4109. /**
  4110. * Returns the current page number.
  4111. * @return int page number
  4112. * @public
  4113. * @since 1.0
  4114. * @see getAliasNbPages()
  4115. */
  4116. public function PageNo() {
  4117. return $this->page;
  4118. }
  4119. /**
  4120. * Defines a new spot color.
  4121. * It can be expressed in RGB components or gray scale.
  4122. * The method can be called before the first page is created and the value is retained from page to page.
  4123. * @param $name (string) Full name of the spot color.
  4124. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  4125. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  4126. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  4127. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  4128. * @public
  4129. * @since 4.0.024 (2008-09-12)
  4130. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  4131. */
  4132. public function AddSpotColor($name, $c, $m, $y, $k) {
  4133. if (!isset($this->spot_colors[$name])) {
  4134. $i = (1 + count($this->spot_colors));
  4135. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  4136. }
  4137. }
  4138. /**
  4139. * Return the Spot color array.
  4140. * @param $name (string) Name of the spot color.
  4141. * @return (array) Spot color array or false if not defined.
  4142. * @public
  4143. * @since 5.9.125 (2011-10-03)
  4144. */
  4145. public function getSpotColor($name) {
  4146. if (isset($this->spot_colors[$name])) {
  4147. return $this->spot_colors[$name];
  4148. }
  4149. $color = preg_replace('/[\s]*/', '', $name); // remove extra spaces
  4150. $color = strtolower($color);
  4151. if (isset($this->spotcolor[$color])) {
  4152. $this->AddSpotColor($this->spotcolor[$color][4], $this->spotcolor[$color][0], $this->spotcolor[$color][1], $this->spotcolor[$color][2], $this->spotcolor[$color][3]);
  4153. return $this->spot_colors[$this->spotcolor[$color][4]];
  4154. }
  4155. return false;
  4156. }
  4157. /**
  4158. * Set the spot color for the specified type ('draw', 'fill', 'text').
  4159. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  4160. * @param $name (string) Name of the spot color.
  4161. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4162. * @return (string) PDF color command.
  4163. * @public
  4164. * @since 5.9.125 (2011-10-03)
  4165. */
  4166. public function setSpotColor($type, $name, $tint=100) {
  4167. $spotcolor = $this->getSpotColor($name);
  4168. if ($spotcolor === false) {
  4169. $this->Error('Undefined spot color: '.$name.', you must add it on the spotcolors.php file.');
  4170. }
  4171. $tint = (max(0, min(100, $tint)) / 100);
  4172. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  4173. switch ($type) {
  4174. case 'draw': {
  4175. $pdfcolor .= sprintf('CS %.3F SCN', $tint);
  4176. $this->DrawColor = $pdfcolor;
  4177. $this->strokecolor = $spotcolor;
  4178. break;
  4179. }
  4180. case 'fill': {
  4181. $pdfcolor .= sprintf('cs %.3F scn', $tint);
  4182. $this->FillColor = $pdfcolor;
  4183. $this->bgcolor = $spotcolor;
  4184. break;
  4185. }
  4186. case 'text': {
  4187. $pdfcolor .= sprintf('cs %.3F scn', $tint);
  4188. $this->TextColor = $pdfcolor;
  4189. $this->fgcolor = $spotcolor;
  4190. break;
  4191. }
  4192. }
  4193. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  4194. if ($this->page > 0) {
  4195. $this->_out($pdfcolor);
  4196. }
  4197. if ($this->inxobj) {
  4198. // we are inside an XObject template
  4199. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  4200. }
  4201. return $pdfcolor;
  4202. }
  4203. /**
  4204. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  4205. * @param $name (string) Name of the spot color.
  4206. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4207. * @public
  4208. * @since 4.0.024 (2008-09-12)
  4209. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  4210. */
  4211. public function SetDrawSpotColor($name, $tint=100) {
  4212. $this->setSpotColor('draw', $name, $tint);
  4213. }
  4214. /**
  4215. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  4216. * @param $name (string) Name of the spot color.
  4217. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4218. * @public
  4219. * @since 4.0.024 (2008-09-12)
  4220. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  4221. */
  4222. public function SetFillSpotColor($name, $tint=100) {
  4223. $this->setSpotColor('fill', $name, $tint);
  4224. }
  4225. /**
  4226. * Defines the spot color used for text.
  4227. * @param $name (string) Name of the spot color.
  4228. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4229. * @public
  4230. * @since 4.0.024 (2008-09-12)
  4231. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  4232. */
  4233. public function SetTextSpotColor($name, $tint=100) {
  4234. $this->setSpotColor('text', $name, $tint);
  4235. }
  4236. /**
  4237. * Set the color array for the specified type ('draw', 'fill', 'text').
  4238. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  4239. * The method can be called before the first page is created and the value is retained from page to page.
  4240. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  4241. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  4242. * @param $ret (boolean) If true do not send the PDF command.
  4243. * @return (string) The PDF command or empty string.
  4244. * @public
  4245. * @since 3.1.000 (2008-06-11)
  4246. */
  4247. public function setColorArray($type, $color, $ret=false) {
  4248. if (is_array($color)) {
  4249. $color = array_values($color);
  4250. // component: grey, RGB red or CMYK cyan
  4251. $c = isset($color[0]) ? $color[0] : -1;
  4252. // component: RGB green or CMYK magenta
  4253. $m = isset($color[1]) ? $color[1] : -1;
  4254. // component: RGB blue or CMYK yellow
  4255. $y = isset($color[2]) ? $color[2] : -1;
  4256. // component: CMYK black
  4257. $k = isset($color[3]) ? $color[3] : -1;
  4258. // color name
  4259. $name = isset($color[4]) ? $color[4] : '';
  4260. if ($c >= 0) {
  4261. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  4262. }
  4263. }
  4264. return '';
  4265. }
  4266. /**
  4267. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  4268. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  4269. * The method can be called before the first page is created and the value is retained from page to page.
  4270. * @param $color (array) Array of colors (1, 3 or 4 values).
  4271. * @param $ret (boolean) If true do not send the PDF command.
  4272. * @return string the PDF command
  4273. * @public
  4274. * @since 3.1.000 (2008-06-11)
  4275. * @see SetDrawColor()
  4276. */
  4277. public function SetDrawColorArray($color, $ret=false) {
  4278. return $this->setColorArray('draw', $color, $ret);
  4279. }
  4280. /**
  4281. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  4282. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  4283. * The method can be called before the first page is created and the value is retained from page to page.
  4284. * @param $color (array) Array of colors (1, 3 or 4 values).
  4285. * @param $ret (boolean) If true do not send the PDF command.
  4286. * @public
  4287. * @since 3.1.000 (2008-6-11)
  4288. * @see SetFillColor()
  4289. */
  4290. public function SetFillColorArray($color, $ret=false) {
  4291. return $this->setColorArray('fill', $color, $ret);
  4292. }
  4293. /**
  4294. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  4295. * The method can be called before the first page is created and the value is retained from page to page.
  4296. * @param $color (array) Array of colors (1, 3 or 4 values).
  4297. * @param $ret (boolean) If true do not send the PDF command.
  4298. * @public
  4299. * @since 3.1.000 (2008-6-11)
  4300. * @see SetFillColor()
  4301. */
  4302. public function SetTextColorArray($color, $ret=false) {
  4303. return $this->setColorArray('text', $color, $ret);
  4304. }
  4305. /**
  4306. * Defines the color used by the specified type ('draw', 'fill', 'text').
  4307. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  4308. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4309. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4310. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4311. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4312. * @param $ret (boolean) If true do not send the command.
  4313. * @param $name (string) spot color name (if any)
  4314. * @return (string) The PDF command or empty string.
  4315. * @public
  4316. * @since 5.9.125 (2011-10-03)
  4317. */
  4318. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4319. // set default values
  4320. if (!is_numeric($col1)) {
  4321. $col1 = 0;
  4322. }
  4323. if (!is_numeric($col2)) {
  4324. $col2 = -1;
  4325. }
  4326. if (!is_numeric($col3)) {
  4327. $col3 = -1;
  4328. }
  4329. if (!is_numeric($col4)) {
  4330. $col4 = -1;
  4331. }
  4332. // set color by case
  4333. $suffix = '';
  4334. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  4335. // Grey scale
  4336. $col1 = max(0, min(255, $col1));
  4337. $intcolor = array('G' => $col1);
  4338. $pdfcolor = sprintf('%.3F ', ($col1 / 255));
  4339. $suffix = 'g';
  4340. } elseif ($col4 == -1) {
  4341. // RGB
  4342. $col1 = max(0, min(255, $col1));
  4343. $col2 = max(0, min(255, $col2));
  4344. $col3 = max(0, min(255, $col3));
  4345. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  4346. $pdfcolor = sprintf('%.3F %.3F %.3F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  4347. $suffix = 'rg';
  4348. } else {
  4349. $col1 = max(0, min(100, $col1));
  4350. $col2 = max(0, min(100, $col2));
  4351. $col3 = max(0, min(100, $col3));
  4352. $col4 = max(0, min(100, $col4));
  4353. if (empty($name)) {
  4354. // CMYK
  4355. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  4356. $pdfcolor = sprintf('%.3F %.3F %.3F %.3F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  4357. $suffix = 'k';
  4358. } else {
  4359. // SPOT COLOR
  4360. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  4361. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  4362. $pdfcolor = $this->setSpotColor($type, $name, 100);
  4363. }
  4364. }
  4365. switch ($type) {
  4366. case 'draw': {
  4367. $pdfcolor .= strtoupper($suffix);
  4368. $this->DrawColor = $pdfcolor;
  4369. $this->strokecolor = $intcolor;
  4370. break;
  4371. }
  4372. case 'fill': {
  4373. $pdfcolor .= $suffix;
  4374. $this->FillColor = $pdfcolor;
  4375. $this->bgcolor = $intcolor;
  4376. break;
  4377. }
  4378. case 'text': {
  4379. $pdfcolor .= $suffix;
  4380. $this->TextColor = $pdfcolor;
  4381. $this->fgcolor = $intcolor;
  4382. break;
  4383. }
  4384. }
  4385. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  4386. if (($type != 'text') AND ($this->page > 0)) {
  4387. if (!$ret) {
  4388. $this->_out($pdfcolor);
  4389. }
  4390. return $pdfcolor;
  4391. }
  4392. return '';
  4393. }
  4394. /**
  4395. * Convert a color array into a string representation.
  4396. * @param $c (array) Array of colors.
  4397. * @return (string) The color array representation.
  4398. * @protected
  4399. * @since 5.9.137 (2011-12-01)
  4400. */
  4401. protected function getColorStringFromArray($c) {
  4402. $c = array_values($c);
  4403. $color = '[';
  4404. switch (count($c)) {
  4405. case 4: {
  4406. // CMYK
  4407. $color .= sprintf('%.3F %.3F %.3F %.3F', (max(0, min(100, floatval($c[0]))) / 100), (max(0, min(100, floatval($c[1]))) / 100), (max(0, min(100, floatval($c[2]))) / 100), (max(0, min(100, floatval($c[3]))) / 100));
  4408. break;
  4409. }
  4410. case 3: {
  4411. // RGB
  4412. $color .= sprintf('%.3F %.3F %.3F', (max(0, min(255, floatval($c[0]))) / 255), (max(0, min(255, floatval($c[1]))) / 255), (max(0, min(255, floatval($c[2]))) / 255));
  4413. break;
  4414. }
  4415. case 1: {
  4416. // grayscale
  4417. $color .= sprintf('%.3F', (max(0, min(255, floatval($c[0]))) / 255));
  4418. break;
  4419. }
  4420. }
  4421. $color .= ']';
  4422. return $color;
  4423. }
  4424. /**
  4425. * 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.
  4426. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4427. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4428. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4429. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4430. * @param $ret (boolean) If true do not send the command.
  4431. * @param $name (string) spot color name (if any)
  4432. * @return string the PDF command
  4433. * @public
  4434. * @since 1.3
  4435. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  4436. */
  4437. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4438. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  4439. }
  4440. /**
  4441. * 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.
  4442. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4443. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4444. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4445. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4446. * @param $ret (boolean) If true do not send the command.
  4447. * @param $name (string) Spot color name (if any).
  4448. * @return (string) The PDF command.
  4449. * @public
  4450. * @since 1.3
  4451. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  4452. */
  4453. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4454. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  4455. }
  4456. /**
  4457. * 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.
  4458. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4459. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4460. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4461. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4462. * @param $ret (boolean) If true do not send the command.
  4463. * @param $name (string) Spot color name (if any).
  4464. * @return (string) Empty string.
  4465. * @public
  4466. * @since 1.3
  4467. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  4468. */
  4469. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4470. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  4471. }
  4472. /**
  4473. * Returns the length of a string in user unit. A font must be selected.<br>
  4474. * @param $s (string) The string whose length is to be computed
  4475. * @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.
  4476. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-trough</li><li>O: overline</li></ul> or any combination. The default value is regular.
  4477. * @param $fontsize (float) Font size in points. The default value is the current size.
  4478. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  4479. * @return mixed int total string length or array of characted widths
  4480. * @author Nicola Asuni
  4481. * @public
  4482. * @since 1.2
  4483. */
  4484. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  4485. return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize, $getarray);
  4486. }
  4487. /**
  4488. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  4489. * @param $sa (string) The array of chars whose total length is to be computed
  4490. * @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.
  4491. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li><li>O: overline</li></ul> or any combination. The default value is regular.
  4492. * @param $fontsize (float) Font size in points. The default value is the current size.
  4493. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  4494. * @return mixed int total string length or array of characted widths
  4495. * @author Nicola Asuni
  4496. * @public
  4497. * @since 2.4.000 (2008-03-06)
  4498. */
  4499. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  4500. // store current values
  4501. if (!$this->empty_string($fontname)) {
  4502. $prev_FontFamily = $this->FontFamily;
  4503. $prev_FontStyle = $this->FontStyle;
  4504. $prev_FontSizePt = $this->FontSizePt;
  4505. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  4506. }
  4507. // convert UTF-8 array to Latin1 if required
  4508. $sa = $this->UTF8ArrToLatin1($sa);
  4509. $w = 0; // total width
  4510. $wa = array(); // array of characters widths
  4511. foreach ($sa as $ck => $char) {
  4512. // character width
  4513. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  4514. $wa[] = $cw;
  4515. $w += $cw;
  4516. }
  4517. // restore previous values
  4518. if (!$this->empty_string($fontname)) {
  4519. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  4520. }
  4521. if ($getarray) {
  4522. return $wa;
  4523. }
  4524. return $w;
  4525. }
  4526. /**
  4527. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking/kerning).
  4528. * @param $char (int) The char code whose length is to be returned
  4529. * @param $notlast (boolean) set to false for the latest character on string, true otherwise (default)
  4530. * @return float char width
  4531. * @author Nicola Asuni
  4532. * @public
  4533. * @since 2.4.000 (2008-03-06)
  4534. */
  4535. public function GetCharWidth($char, $notlast=true) {
  4536. // get raw width
  4537. $chw = $this->getRawCharWidth($char);
  4538. if (($this->font_spacing != 0) AND $notlast) {
  4539. // increase/decrease font spacing
  4540. $chw += $this->font_spacing;
  4541. }
  4542. if ($this->font_stretching != 100) {
  4543. // fixed stretching mode
  4544. $chw *= ($this->font_stretching / 100);
  4545. }
  4546. return $chw;
  4547. }
  4548. /**
  4549. * Returns the length of the char in user unit for the current font.
  4550. * @param $char (int) The char code whose length is to be returned
  4551. * @return float char width
  4552. * @author Nicola Asuni
  4553. * @public
  4554. * @since 5.9.000 (2010-09-28)
  4555. */
  4556. public function getRawCharWidth($char) {
  4557. if ($char == 173) {
  4558. // SHY character will not be printed
  4559. return (0);
  4560. }
  4561. if (isset($this->CurrentFont['cw'][$char])) {
  4562. $w = $this->CurrentFont['cw'][$char];
  4563. } elseif (isset($this->CurrentFont['dw'])) {
  4564. // default width
  4565. $w = $this->CurrentFont['dw'];
  4566. } elseif (isset($this->CurrentFont['cw'][32])) {
  4567. // default width
  4568. $w = $this->CurrentFont['cw'][32];
  4569. } else {
  4570. $w = 600;
  4571. }
  4572. return ($w * $this->FontSize / 1000);
  4573. }
  4574. /**
  4575. * Returns the numbero of characters in a string.
  4576. * @param $s (string) The input string.
  4577. * @return int number of characters
  4578. * @public
  4579. * @since 2.0.0001 (2008-01-07)
  4580. */
  4581. public function GetNumChars($s) {
  4582. if ($this->isUnicodeFont()) {
  4583. return count($this->UTF8StringToArray($s));
  4584. }
  4585. return strlen($s);
  4586. }
  4587. /**
  4588. * Fill the list of available fonts ($this->fontlist).
  4589. * @protected
  4590. * @since 4.0.013 (2008-07-28)
  4591. */
  4592. protected function getFontsList() {
  4593. $fontsdir = opendir($this->_getfontpath());
  4594. while (($file = readdir($fontsdir)) !== false) {
  4595. if (substr($file, -4) == '.php') {
  4596. array_push($this->fontlist, strtolower(basename($file, '.php')));
  4597. }
  4598. }
  4599. closedir($fontsdir);
  4600. }
  4601. /**
  4602. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  4603. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  4604. * 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.
  4605. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  4606. * @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>
  4607. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4608. * @return array containing the font data, or false in case of error.
  4609. * @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.
  4610. * @public
  4611. * @since 1.5
  4612. * @see SetFont(), setFontSubsetting()
  4613. */
  4614. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  4615. if ($subset === 'default') {
  4616. $subset = $this->font_subsetting;
  4617. }
  4618. if ($this->pdfa_mode) {
  4619. $subset = false;
  4620. }
  4621. if ($this->empty_string($family)) {
  4622. if (!$this->empty_string($this->FontFamily)) {
  4623. $family = $this->FontFamily;
  4624. } else {
  4625. $this->Error('Empty font family');
  4626. }
  4627. }
  4628. // move embedded styles on $style
  4629. if (substr($family, -1) == 'I') {
  4630. $style .= 'I';
  4631. $family = substr($family, 0, -1);
  4632. }
  4633. if (substr($family, -1) == 'B') {
  4634. $style .= 'B';
  4635. $family = substr($family, 0, -1);
  4636. }
  4637. // normalize family name
  4638. $family = strtolower($family);
  4639. if ((!$this->isunicode) AND ($family == 'arial')) {
  4640. $family = 'helvetica';
  4641. }
  4642. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  4643. $style = '';
  4644. }
  4645. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  4646. // all fonts must be embedded
  4647. $family = 'pdfa'.$family;
  4648. }
  4649. $tempstyle = strtoupper($style);
  4650. $style = '';
  4651. // underline
  4652. if (strpos($tempstyle, 'U') !== false) {
  4653. $this->underline = true;
  4654. } else {
  4655. $this->underline = false;
  4656. }
  4657. // line-through (deleted)
  4658. if (strpos($tempstyle, 'D') !== false) {
  4659. $this->linethrough = true;
  4660. } else {
  4661. $this->linethrough = false;
  4662. }
  4663. // overline
  4664. if (strpos($tempstyle, 'O') !== false) {
  4665. $this->overline = true;
  4666. } else {
  4667. $this->overline = false;
  4668. }
  4669. // bold
  4670. if (strpos($tempstyle, 'B') !== false) {
  4671. $style .= 'B';
  4672. }
  4673. // oblique
  4674. if (strpos($tempstyle, 'I') !== false) {
  4675. $style .= 'I';
  4676. }
  4677. $bistyle = $style;
  4678. $fontkey = $family.$style;
  4679. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  4680. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  4681. // check if the font has been already added
  4682. $fb = $this->getFontBuffer($fontkey);
  4683. if ($fb !== false) {
  4684. if ($this->inxobj) {
  4685. // we are inside an XObject template
  4686. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  4687. }
  4688. return $fontdata;
  4689. }
  4690. if (isset($type)) {
  4691. unset($type);
  4692. }
  4693. if (isset($cw)) {
  4694. unset($cw);
  4695. }
  4696. // get specified font directory (if any)
  4697. $fontdir = false;
  4698. if (!$this->empty_string($fontfile)) {
  4699. $fontdir = dirname($fontfile);
  4700. if ($this->empty_string($fontdir) OR ($fontdir == '.')) {
  4701. $fontdir = '';
  4702. } else {
  4703. $fontdir .= '/';
  4704. }
  4705. }
  4706. $missing_style = false; // true when the font style variation is missing
  4707. // search and include font file
  4708. if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) {
  4709. // build a standard filenames for specified font
  4710. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  4711. // search files on various directories
  4712. if (($fontdir !== false) AND file_exists($fontdir.$tmp_fontfile)) {
  4713. $fontfile = $fontdir.$tmp_fontfile;
  4714. } elseif (file_exists($this->_getfontpath().$tmp_fontfile)) {
  4715. $fontfile = $this->_getfontpath().$tmp_fontfile;
  4716. } elseif (file_exists($tmp_fontfile)) {
  4717. $fontfile = $tmp_fontfile;
  4718. } elseif (!$this->empty_string($style)) {
  4719. $missing_style = true;
  4720. // try to remove the style part
  4721. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  4722. if (($fontdir !== false) AND file_exists($fontdir.$tmp_fontfile)) {
  4723. $fontfile = $fontdir.$tmp_fontfile;
  4724. } elseif (file_exists($this->_getfontpath().$tmp_fontfile)) {
  4725. $fontfile = $this->_getfontpath().$tmp_fontfile;
  4726. } else {
  4727. $fontfile = $tmp_fontfile;
  4728. }
  4729. }
  4730. }
  4731. // include font file
  4732. if (file_exists($fontfile)) {
  4733. include($fontfile);
  4734. } else {
  4735. $this->Error('Could not include font definition file: '.$family.'');
  4736. }
  4737. // check font parameters
  4738. if ((!isset($type)) OR (!isset($cw))) {
  4739. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  4740. }
  4741. // SET default parameters
  4742. if (!isset($file) OR $this->empty_string($file)) {
  4743. $file = '';
  4744. }
  4745. if (!isset($enc) OR $this->empty_string($enc)) {
  4746. $enc = '';
  4747. }
  4748. if (!isset($cidinfo) OR $this->empty_string($cidinfo)) {
  4749. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  4750. $cidinfo['uni2cid'] = array();
  4751. }
  4752. if (!isset($ctg) OR $this->empty_string($ctg)) {
  4753. $ctg = '';
  4754. }
  4755. if (!isset($desc) OR $this->empty_string($desc)) {
  4756. $desc = array();
  4757. }
  4758. if (!isset($up) OR $this->empty_string($up)) {
  4759. $up = -100;
  4760. }
  4761. if (!isset($ut) OR $this->empty_string($ut)) {
  4762. $ut = 50;
  4763. }
  4764. if (!isset($cw) OR $this->empty_string($cw)) {
  4765. $cw = array();
  4766. }
  4767. if (!isset($dw) OR $this->empty_string($dw)) {
  4768. // set default width
  4769. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  4770. $dw = $desc['MissingWidth'];
  4771. } elseif (isset($cw[32])) {
  4772. $dw = $cw[32];
  4773. } else {
  4774. $dw = 600;
  4775. }
  4776. }
  4777. ++$this->numfonts;
  4778. if ($type == 'core') {
  4779. $name = $this->CoreFonts[$fontkey];
  4780. $subset = false;
  4781. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  4782. $subset = false;
  4783. } elseif ($type == 'TrueTypeUnicode') {
  4784. $enc = 'Identity-H';
  4785. } elseif ($type == 'cidfont0') {
  4786. if ($this->pdfa_mode) {
  4787. $this->Error('All fonts must be embedded in PDF/A mode!');
  4788. }
  4789. } else {
  4790. $this->Error('Unknow font type: '.$type.'');
  4791. }
  4792. // set name if unset
  4793. if (!isset($name) OR empty($name)) {
  4794. $name = $fontkey;
  4795. }
  4796. // create artificial font style variations if missing (only works with non-embedded fonts)
  4797. if (($type != 'core') AND $missing_style) {
  4798. // style variations
  4799. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4800. $name .= $styles[$bistyle];
  4801. // artificial bold
  4802. if (strpos($bistyle, 'B') !== false) {
  4803. if (isset($desc['StemV'])) {
  4804. // from normal to bold
  4805. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4806. } else {
  4807. // bold
  4808. $desc['StemV'] = 123;
  4809. }
  4810. }
  4811. // artificial italic
  4812. if (strpos($bistyle, 'I') !== false) {
  4813. if (isset($desc['ItalicAngle'])) {
  4814. $desc['ItalicAngle'] -= 11;
  4815. } else {
  4816. $desc['ItalicAngle'] = -11;
  4817. }
  4818. if (isset($desc['Flags'])) {
  4819. $desc['Flags'] |= 64; //bit 7
  4820. } else {
  4821. $desc['Flags'] = 64;
  4822. }
  4823. }
  4824. }
  4825. // initialize subsetchars to contain default ASCII values (0-255)
  4826. $subsetchars = array_fill(0, 256, true);
  4827. $this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars));
  4828. if ($this->inxobj) {
  4829. // we are inside an XObject template
  4830. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4831. }
  4832. if (isset($diff) AND (!empty($diff))) {
  4833. //Search existing encodings
  4834. $d = 0;
  4835. $nb = count($this->diffs);
  4836. for ($i=1; $i <= $nb; ++$i) {
  4837. if ($this->diffs[$i] == $diff) {
  4838. $d = $i;
  4839. break;
  4840. }
  4841. }
  4842. if ($d == 0) {
  4843. $d = $nb + 1;
  4844. $this->diffs[$d] = $diff;
  4845. }
  4846. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4847. }
  4848. if (!$this->empty_string($file)) {
  4849. if (!isset($this->FontFiles[$file])) {
  4850. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4851. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4852. } elseif ($type != 'core') {
  4853. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4854. }
  4855. } else {
  4856. // update fontkeys that are sharing this font file
  4857. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4858. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4859. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4860. }
  4861. }
  4862. }
  4863. return $fontdata;
  4864. }
  4865. /**
  4866. * Sets the font used to print character strings.
  4867. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4868. * The method can be called before the first page is created and the font is retained from page to page.
  4869. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4870. * 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 />
  4871. * @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.
  4872. * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li><li>O: overline</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
  4873. * @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
  4874. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4875. * @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.
  4876. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4877. * @author Nicola Asuni
  4878. * @public
  4879. * @since 1.0
  4880. * @see AddFont(), SetFontSize()
  4881. */
  4882. public function SetFont($family, $style='', $size=0, $fontfile='', $subset='default', $out=true) {
  4883. //Select a font; size given in points
  4884. if ($size == 0) {
  4885. $size = $this->FontSizePt;
  4886. }
  4887. // try to add font (if not already added)
  4888. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4889. $this->FontFamily = $fontdata['family'];
  4890. $this->FontStyle = $fontdata['style'];
  4891. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4892. $this->SetFontSize($size, $out);
  4893. }
  4894. /**
  4895. * Defines the size of the current font.
  4896. * @param $size (float) The font size in points.
  4897. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4898. * @public
  4899. * @since 1.0
  4900. * @see SetFont()
  4901. */
  4902. public function SetFontSize($size, $out=true) {
  4903. // font size in points
  4904. $this->FontSizePt = $size;
  4905. // font size in user units
  4906. $this->FontSize = $size / $this->k;
  4907. // calculate some font metrics
  4908. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4909. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4910. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  4911. } else {
  4912. $font_height = $size * 1.219;
  4913. }
  4914. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  4915. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  4916. }
  4917. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  4918. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  4919. }
  4920. if (!isset($font_ascent) AND !isset($font_descent)) {
  4921. // core font
  4922. $font_ascent = 0.76 * $font_height;
  4923. $font_descent = $font_height - $font_ascent;
  4924. } elseif (!isset($font_descent)) {
  4925. $font_descent = $font_height - $font_ascent;
  4926. } elseif (!isset($font_ascent)) {
  4927. $font_ascent = $font_height - $font_descent;
  4928. }
  4929. $this->FontAscent = ($font_ascent / $this->k);
  4930. $this->FontDescent = ($font_descent / $this->k);
  4931. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i']))) {
  4932. $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  4933. }
  4934. }
  4935. /**
  4936. * Return the font descent value
  4937. * @param $font (string) font name
  4938. * @param $style (string) font style
  4939. * @param $size (float) The size (in points)
  4940. * @return int font descent
  4941. * @public
  4942. * @author Nicola Asuni
  4943. * @since 4.9.003 (2010-03-30)
  4944. */
  4945. public function getFontDescent($font, $style='', $size=0) {
  4946. $fontdata = $this->AddFont($font, $style);
  4947. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4948. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  4949. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  4950. } else {
  4951. $descent = 1.219 * 0.24 * $size;
  4952. }
  4953. return ($descent / $this->k);
  4954. }
  4955. /**
  4956. * Return the font ascent value
  4957. * @param $font (string) font name
  4958. * @param $style (string) font style
  4959. * @param $size (float) The size (in points)
  4960. * @return int font ascent
  4961. * @public
  4962. * @author Nicola Asuni
  4963. * @since 4.9.003 (2010-03-30)
  4964. */
  4965. public function getFontAscent($font, $style='', $size=0) {
  4966. $fontdata = $this->AddFont($font, $style);
  4967. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4968. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  4969. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  4970. } else {
  4971. $ascent = 1.219 * 0.76 * $size;
  4972. }
  4973. return ($ascent / $this->k);
  4974. }
  4975. /**
  4976. * Defines the default monospaced font.
  4977. * @param $font (string) Font name.
  4978. * @public
  4979. * @since 4.5.025
  4980. */
  4981. public function SetDefaultMonospacedFont($font) {
  4982. $this->default_monospaced_font = $font;
  4983. }
  4984. /**
  4985. * 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 />
  4986. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  4987. * @public
  4988. * @since 1.5
  4989. * @see Cell(), Write(), Image(), Link(), SetLink()
  4990. */
  4991. public function AddLink() {
  4992. //Create a new internal link
  4993. $n = count($this->links) + 1;
  4994. $this->links[$n] = array(0, 0);
  4995. return $n;
  4996. }
  4997. /**
  4998. * Defines the page and position a link points to.
  4999. * @param $link (int) The link identifier returned by AddLink()
  5000. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  5001. * @param $page (int) Number of target page; -1 indicates the current page. This is the default value
  5002. * @public
  5003. * @since 1.5
  5004. * @see AddLink()
  5005. */
  5006. public function SetLink($link, $y=0, $page=-1) {
  5007. if ($y == -1) {
  5008. $y = $this->y;
  5009. }
  5010. if ($page == -1) {
  5011. $page = $this->page;
  5012. }
  5013. $this->links[$link] = array($page, $y);
  5014. }
  5015. /**
  5016. * Puts a link on a rectangular area of the page.
  5017. * 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.
  5018. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  5019. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  5020. * @param $w (float) Width of the rectangle
  5021. * @param $h (float) Height of the rectangle
  5022. * @param $link (mixed) URL or identifier returned by AddLink()
  5023. * @param $spaces (int) number of spaces on the text to link
  5024. * @public
  5025. * @since 1.5
  5026. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  5027. */
  5028. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  5029. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  5030. }
  5031. /**
  5032. * Puts a markup annotation on a rectangular area of the page.
  5033. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  5034. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  5035. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  5036. * @param $w (float) Width of the rectangle
  5037. * @param $h (float) Height of the rectangle
  5038. * @param $text (string) annotation text or alternate content
  5039. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  5040. * @param $spaces (int) number of spaces on the text to link
  5041. * @public
  5042. * @since 4.0.018 (2008-08-06)
  5043. */
  5044. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  5045. if ($this->inxobj) {
  5046. // store parameters for later use on template
  5047. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  5048. return;
  5049. }
  5050. if ($x === '') {
  5051. $x = $this->x;
  5052. }
  5053. if ($y === '') {
  5054. $y = $this->y;
  5055. }
  5056. // check page for no-write regions and adapt page margins if necessary
  5057. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  5058. // recalculate coordinates to account for graphic transformations
  5059. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  5060. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  5061. $maxid = count($this->transfmatrix[$i]) - 1;
  5062. for ($j=$maxid; $j >= 0; --$j) {
  5063. $ctm = $this->transfmatrix[$i][$j];
  5064. if (isset($ctm['a'])) {
  5065. $x = $x * $this->k;
  5066. $y = ($this->h - $y) * $this->k;
  5067. $w = $w * $this->k;
  5068. $h = $h * $this->k;
  5069. // top left
  5070. $xt = $x;
  5071. $yt = $y;
  5072. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5073. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5074. // top right
  5075. $xt = $x + $w;
  5076. $yt = $y;
  5077. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5078. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5079. // bottom left
  5080. $xt = $x;
  5081. $yt = $y - $h;
  5082. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5083. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5084. // bottom right
  5085. $xt = $x + $w;
  5086. $yt = $y - $h;
  5087. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5088. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5089. // new coordinates (rectangle area)
  5090. $x = min($x1, $x2, $x3, $x4);
  5091. $y = max($y1, $y2, $y3, $y4);
  5092. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  5093. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  5094. $x = $x / $this->k;
  5095. $y = $this->h - ($y / $this->k);
  5096. }
  5097. }
  5098. }
  5099. }
  5100. if ($this->page <= 0) {
  5101. $page = 1;
  5102. } else {
  5103. $page = $this->page;
  5104. }
  5105. if (!isset($this->PageAnnots[$page])) {
  5106. $this->PageAnnots[$page] = array();
  5107. }
  5108. ++$this->n;
  5109. $this->PageAnnots[$page][] = array('n' => $this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  5110. if (!$this->pdfa_mode) {
  5111. if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!$this->empty_string($opt['FS'])) AND file_exists($opt['FS']) AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  5112. ++$this->n;
  5113. $this->embeddedfiles[basename($opt['FS'])] = array('n' => $this->n, 'file' => $opt['FS']);
  5114. }
  5115. }
  5116. // Add widgets annotation's icons
  5117. if (isset($opt['mk']['i']) AND file_exists($opt['mk']['i'])) {
  5118. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  5119. }
  5120. if (isset($opt['mk']['ri']) AND file_exists($opt['mk']['ri'])) {
  5121. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  5122. }
  5123. if (isset($opt['mk']['ix']) AND file_exists($opt['mk']['ix'])) {
  5124. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  5125. }
  5126. }
  5127. /**
  5128. * Embedd the attached files.
  5129. * @since 4.4.000 (2008-12-07)
  5130. * @protected
  5131. * @see Annotation()
  5132. */
  5133. protected function _putEmbeddedFiles() {
  5134. if ($this->pdfa_mode) {
  5135. // embedded files are not allowed in PDF/A mode
  5136. return;
  5137. }
  5138. reset($this->embeddedfiles);
  5139. foreach ($this->embeddedfiles as $filename => $filedata) {
  5140. $data = file_get_contents($filedata['file']);
  5141. $filter = '';
  5142. if ($this->compress) {
  5143. $data = gzcompress($data);
  5144. $filter = ' /Filter /FlateDecode';
  5145. }
  5146. $stream = $this->_getrawstream($data, $filedata['n']);
  5147. $out = $this->_getobj($filedata['n'])."\n";
  5148. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' >>';
  5149. $out .= ' stream'."\n".$stream."\n".'endstream';
  5150. $out .= "\n".'endobj';
  5151. $this->_out($out);
  5152. }
  5153. }
  5154. /**
  5155. * Prints a text cell at the specified position.
  5156. * This method allows to place a string precisely on the page.
  5157. * @param $x (float) Abscissa of the cell origin
  5158. * @param $y (float) Ordinate of the cell origin
  5159. * @param $txt (string) String to print
  5160. * @param $fstroke (int) outline size in user units (false = disable)
  5161. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  5162. * @param $ffill (boolean) if true fills the text
  5163. * @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)))
  5164. * @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.
  5165. * @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>
  5166. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5167. * @param $link (mixed) URL or identifier returned by AddLink().
  5168. * @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.
  5169. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  5170. * @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>
  5171. * @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>
  5172. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  5173. * @public
  5174. * @since 1.0
  5175. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  5176. */
  5177. 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) {
  5178. $textrendermode = $this->textrendermode;
  5179. $textstrokewidth = $this->textstrokewidth;
  5180. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  5181. $this->SetXY($x, $y, $rtloff);
  5182. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  5183. // restore previous rendering mode
  5184. $this->textrendermode = $textrendermode;
  5185. $this->textstrokewidth = $textstrokewidth;
  5186. }
  5187. /**
  5188. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  5189. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  5190. * This method is called automatically and should not be called directly by the application.
  5191. * @return boolean
  5192. * @public
  5193. * @since 1.4
  5194. * @see SetAutoPageBreak()
  5195. */
  5196. public function AcceptPageBreak() {
  5197. if ($this->num_columns > 1) {
  5198. // multi column mode
  5199. if ($this->current_column < ($this->num_columns - 1)) {
  5200. // go to next column
  5201. $this->selectColumn($this->current_column + 1);
  5202. } else {
  5203. // add a new page
  5204. $this->AddPage();
  5205. // set first column
  5206. $this->selectColumn(0);
  5207. }
  5208. // avoid page breaking from checkPageBreak()
  5209. return false;
  5210. }
  5211. return $this->AutoPageBreak;
  5212. }
  5213. /**
  5214. * Add page if needed.
  5215. * @param $h (float) Cell height. Default value: 0.
  5216. * @param $y (mixed) starting y position, leave empty for current position.
  5217. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  5218. * @return boolean true in case of page break, false otherwise.
  5219. * @since 3.2.000 (2008-07-01)
  5220. * @protected
  5221. */
  5222. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  5223. if ($this->empty_string($y)) {
  5224. $y = $this->y;
  5225. }
  5226. $current_page = $this->page;
  5227. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  5228. if ($addpage) {
  5229. //Automatic page break
  5230. $x = $this->x;
  5231. $this->AddPage($this->CurOrientation);
  5232. $this->y = $this->tMargin;
  5233. $oldpage = $this->page - 1;
  5234. if ($this->rtl) {
  5235. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  5236. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  5237. } else {
  5238. $this->x = $x;
  5239. }
  5240. } else {
  5241. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  5242. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  5243. } else {
  5244. $this->x = $x;
  5245. }
  5246. }
  5247. }
  5248. return true;
  5249. }
  5250. if ($current_page != $this->page) {
  5251. // account for columns mode
  5252. return true;
  5253. }
  5254. return false;
  5255. }
  5256. /**
  5257. * Removes SHY characters from text.
  5258. * Unicode Data:<ul>
  5259. * <li>Name : SOFT HYPHEN, commonly abbreviated as SHY</li>
  5260. * <li>HTML Entity (decimal): "&amp;#173;"</li>
  5261. * <li>HTML Entity (hex): "&amp;#xad;"</li>
  5262. * <li>HTML Entity (named): "&amp;shy;"</li>
  5263. * <li>How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]</li>
  5264. * <li>UTF-8 (hex): 0xC2 0xAD (c2ad)</li>
  5265. * <li>UTF-8 character: chr(194).chr(173)</li>
  5266. * </ul>
  5267. * @param $txt (string) input string
  5268. * @return string without SHY characters.
  5269. * @public
  5270. * @since (4.5.019) 2009-02-28
  5271. */
  5272. public function removeSHY($txt='') {
  5273. $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
  5274. if (!$this->isunicode) {
  5275. $txt = preg_replace('/([\\xad]{1})/', '', $txt);
  5276. }
  5277. return $txt;
  5278. }
  5279. /**
  5280. * 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 />
  5281. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  5282. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  5283. * @param $h (float) Cell height. Default value: 0.
  5284. * @param $txt (string) String to print. Default value: empty string.
  5285. * @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)))
  5286. * @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.
  5287. * @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>
  5288. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5289. * @param $link (mixed) URL or identifier returned by AddLink().
  5290. * @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.
  5291. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  5292. * @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>
  5293. * @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>
  5294. * @public
  5295. * @since 1.0
  5296. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  5297. */
  5298. 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') {
  5299. $prev_cell_margin = $this->cell_margin;
  5300. $prev_cell_padding = $this->cell_padding;
  5301. $this->adjustCellPadding($border);
  5302. if (!$ignore_min_height) {
  5303. $min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  5304. if ($h < $min_cell_height) {
  5305. $h = $min_cell_height;
  5306. }
  5307. }
  5308. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  5309. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  5310. $this->cell_padding = $prev_cell_padding;
  5311. $this->cell_margin = $prev_cell_margin;
  5312. }
  5313. /**
  5314. * 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 />
  5315. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  5316. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  5317. * @param $h (float) Cell height. Default value: 0.
  5318. * @param $txt (string) String to print. Default value: empty string.
  5319. * @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)))
  5320. * @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.
  5321. * @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>
  5322. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5323. * @param $link (mixed) URL or identifier returned by AddLink().
  5324. * @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.
  5325. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  5326. * @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>
  5327. * @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>
  5328. * @return string containing cell code
  5329. * @protected
  5330. * @since 1.0
  5331. * @see Cell()
  5332. */
  5333. 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') {
  5334. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  5335. $txt = str_replace($this->unichr(160), ' ', $txt);
  5336. $prev_cell_margin = $this->cell_margin;
  5337. $prev_cell_padding = $this->cell_padding;
  5338. $txt = $this->removeSHY($txt);
  5339. $rs = ''; //string to be returned
  5340. $this->adjustCellPadding($border);
  5341. if (!$ignore_min_height) {
  5342. $min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  5343. if ($h < $min_cell_height) {
  5344. $h = $min_cell_height;
  5345. }
  5346. }
  5347. $k = $this->k;
  5348. // check page for no-write regions and adapt page margins if necessary
  5349. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5350. if ($this->rtl) {
  5351. $x = $this->x - $this->cell_margin['R'];
  5352. } else {
  5353. $x = $this->x + $this->cell_margin['L'];
  5354. }
  5355. $y = $this->y + $this->cell_margin['T'];
  5356. $prev_font_stretching = $this->font_stretching;
  5357. $prev_font_spacing = $this->font_spacing;
  5358. // cell vertical alignment
  5359. switch ($calign) {
  5360. case 'A': {
  5361. // font top
  5362. switch ($valign) {
  5363. case 'T': {
  5364. // top
  5365. $y -= $this->cell_padding['T'];
  5366. break;
  5367. }
  5368. case 'B': {
  5369. // bottom
  5370. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  5371. break;
  5372. }
  5373. default:
  5374. case 'C':
  5375. case 'M': {
  5376. // center
  5377. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  5378. break;
  5379. }
  5380. }
  5381. break;
  5382. }
  5383. case 'L': {
  5384. // font baseline
  5385. switch ($valign) {
  5386. case 'T': {
  5387. // top
  5388. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  5389. break;
  5390. }
  5391. case 'B': {
  5392. // bottom
  5393. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  5394. break;
  5395. }
  5396. default:
  5397. case 'C':
  5398. case 'M': {
  5399. // center
  5400. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  5401. break;
  5402. }
  5403. }
  5404. break;
  5405. }
  5406. case 'D': {
  5407. // font bottom
  5408. switch ($valign) {
  5409. case 'T': {
  5410. // top
  5411. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  5412. break;
  5413. }
  5414. case 'B': {
  5415. // bottom
  5416. $y -= ($h - $this->cell_padding['B']);
  5417. break;
  5418. }
  5419. default:
  5420. case 'C':
  5421. case 'M': {
  5422. // center
  5423. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  5424. break;
  5425. }
  5426. }
  5427. break;
  5428. }
  5429. case 'B': {
  5430. // cell bottom
  5431. $y -= $h;
  5432. break;
  5433. }
  5434. case 'C':
  5435. case 'M': {
  5436. // cell center
  5437. $y -= ($h / 2);
  5438. break;
  5439. }
  5440. default:
  5441. case 'T': {
  5442. // cell top
  5443. break;
  5444. }
  5445. }
  5446. // text vertical alignment
  5447. switch ($valign) {
  5448. case 'T': {
  5449. // top
  5450. $yt = $y + $this->cell_padding['T'];
  5451. break;
  5452. }
  5453. case 'B': {
  5454. // bottom
  5455. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  5456. break;
  5457. }
  5458. default:
  5459. case 'C':
  5460. case 'M': {
  5461. // center
  5462. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  5463. break;
  5464. }
  5465. }
  5466. $basefonty = $yt + $this->FontAscent;
  5467. if ($this->empty_string($w) OR ($w <= 0)) {
  5468. if ($this->rtl) {
  5469. $w = $x - $this->lMargin;
  5470. } else {
  5471. $w = $this->w - $this->rMargin - $x;
  5472. }
  5473. }
  5474. $s = '';
  5475. // fill and borders
  5476. if (is_string($border) AND (strlen($border) == 4)) {
  5477. // full border
  5478. $border = 1;
  5479. }
  5480. if ($fill OR ($border == 1)) {
  5481. if ($fill) {
  5482. $op = ($border == 1) ? 'B' : 'f';
  5483. } else {
  5484. $op = 'S';
  5485. }
  5486. if ($this->rtl) {
  5487. $xk = (($x - $w) * $k);
  5488. } else {
  5489. $xk = ($x * $k);
  5490. }
  5491. $s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  5492. }
  5493. // draw borders
  5494. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  5495. if ($txt != '') {
  5496. $txt2 = $txt;
  5497. if ($this->isunicode) {
  5498. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  5499. $txt2 = $this->UTF8ToLatin1($txt2);
  5500. } else {
  5501. $unicode = $this->UTF8StringToArray($txt); // array of UTF-8 unicode values
  5502. $unicode = $this->utf8Bidi($unicode, '', $this->tmprtl);
  5503. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  5504. // ---- Fix for bug #2977340 "Incorrect Thai characters position arrangement" ----
  5505. // NOTE: this doesn't work with HTML justification
  5506. // Symbols that could overlap on the font top (only works in LTR)
  5507. $topchar = array(3611, 3613, 3615, 3650, 3651, 3652); // chars that extends on top
  5508. $topsym = array(3633, 3636, 3637, 3638, 3639, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662); // symbols with top position
  5509. $numchars = count($unicode); // number of chars
  5510. $unik = 0;
  5511. $uniblock = array();
  5512. $uniblock[$unik] = array();
  5513. $uniblock[$unik][] = $unicode[0];
  5514. // resolve overlapping conflicts by splitting the string in several parts
  5515. for ($i = 1; $i < $numchars; ++$i) {
  5516. // check if symbols overlaps at top
  5517. if (in_array($unicode[$i], $topsym) AND (in_array($unicode[($i - 1)], $topsym) OR in_array($unicode[($i - 1)], $topchar))) {
  5518. // move symbols to another array
  5519. ++$unik;
  5520. $uniblock[$unik] = array();
  5521. $uniblock[$unik][] = $unicode[$i];
  5522. ++$unik;
  5523. $uniblock[$unik] = array();
  5524. $unicode[$i] = 0x200b; // Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)
  5525. } else {
  5526. $uniblock[$unik][] = $unicode[$i];
  5527. }
  5528. }
  5529. // ---- END OF Fix for bug #2977340
  5530. }
  5531. $txt2 = $this->arrUTF8ToUTF16BE($unicode, false);
  5532. }
  5533. }
  5534. $txt2 = $this->_escape($txt2);
  5535. // get current text width (considering general font stretching and spacing)
  5536. $txwidth = $this->GetStringWidth($txt);
  5537. $width = $txwidth;
  5538. // check for stretch mode
  5539. if ($stretch > 0) {
  5540. // calculate ratio between cell width and text width
  5541. if ($width <= 0) {
  5542. $ratio = 1;
  5543. } else {
  5544. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  5545. }
  5546. // check if stretching is required
  5547. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5548. // the text will be stretched to fit cell width
  5549. if ($stretch > 2) {
  5550. // set new character spacing
  5551. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5552. } else {
  5553. // set new horizontal stretching
  5554. $this->font_stretching *= $ratio;
  5555. }
  5556. // recalculate text width (the text fills the entire cell)
  5557. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5558. // reset alignment
  5559. $align = '';
  5560. }
  5561. }
  5562. if ($this->font_stretching != 100) {
  5563. // apply font stretching
  5564. $rs .= sprintf('BT %.2F Tz ET ', $this->font_stretching);
  5565. }
  5566. if ($this->font_spacing != 0) {
  5567. // increase/decrease font spacing
  5568. $rs .= sprintf('BT %.2F Tc ET ', ($this->font_spacing * $this->k));
  5569. }
  5570. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5571. $s .= 'q '.$this->TextColor.' ';
  5572. }
  5573. // rendering mode
  5574. $s .= sprintf('BT %d Tr %.2F w ET ', $this->textrendermode, $this->textstrokewidth);
  5575. // count number of spaces
  5576. $ns = substr_count($txt, chr(32));
  5577. // Justification
  5578. $spacewidth = 0;
  5579. if (($align == 'J') AND ($ns > 0)) {
  5580. if ($this->isUnicodeFont()) {
  5581. // get string width without spaces
  5582. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5583. // calculate average space width
  5584. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / $this->FontSize;
  5585. if ($this->font_stretching != 100) {
  5586. // word spacing is affected by stretching
  5587. $spacewidth /= ($this->font_stretching / 100);
  5588. }
  5589. // set word position to be used with TJ operator
  5590. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%.3F', $spacewidth).' (', $txt2);
  5591. $unicode_justification = true;
  5592. } else {
  5593. // get string width
  5594. $width = $txwidth;
  5595. // new space width
  5596. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5597. if ($this->font_stretching != 100) {
  5598. // word spacing (Tw) is affected by stretching
  5599. $spacewidth /= ($this->font_stretching / 100);
  5600. }
  5601. // set word spacing
  5602. $rs .= sprintf('BT %.3F Tw ET ', $spacewidth);
  5603. }
  5604. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5605. }
  5606. // replace carriage return characters
  5607. $txt2 = str_replace("\r", ' ', $txt2);
  5608. switch ($align) {
  5609. case 'C': {
  5610. $dx = ($w - $width) / 2;
  5611. break;
  5612. }
  5613. case 'R': {
  5614. if ($this->rtl) {
  5615. $dx = $this->cell_padding['R'];
  5616. } else {
  5617. $dx = $w - $width - $this->cell_padding['R'];
  5618. }
  5619. break;
  5620. }
  5621. case 'L': {
  5622. if ($this->rtl) {
  5623. $dx = $w - $width - $this->cell_padding['L'];
  5624. } else {
  5625. $dx = $this->cell_padding['L'];
  5626. }
  5627. break;
  5628. }
  5629. case 'J':
  5630. default: {
  5631. if ($this->rtl) {
  5632. $dx = $this->cell_padding['R'];
  5633. } else {
  5634. $dx = $this->cell_padding['L'];
  5635. }
  5636. break;
  5637. }
  5638. }
  5639. if ($this->rtl) {
  5640. $xdx = $x - $dx - $width;
  5641. } else {
  5642. $xdx = $x + $dx;
  5643. }
  5644. $xdk = $xdx * $k;
  5645. // print text
  5646. $s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5647. if (isset($uniblock)) {
  5648. // print overlapping characters as separate string
  5649. $xshift = 0; // horizontal shift
  5650. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5651. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5652. foreach ($uniblock as $uk => $uniarr) {
  5653. if (($uk % 2) == 0) {
  5654. // x space to skip
  5655. if ($spacewidth != 0) {
  5656. // justification shift
  5657. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5658. }
  5659. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5660. } else {
  5661. // character to print
  5662. $topchr = $this->arrUTF8ToUTF16BE($uniarr, false);
  5663. $topchr = $this->_escape($topchr);
  5664. $s .= sprintf(' BT %.2F %.2F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5665. }
  5666. }
  5667. }
  5668. if ($this->underline) {
  5669. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5670. }
  5671. if ($this->linethrough) {
  5672. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5673. }
  5674. if ($this->overline) {
  5675. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5676. }
  5677. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5678. $s .= ' Q';
  5679. }
  5680. if ($link) {
  5681. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5682. }
  5683. }
  5684. // output cell
  5685. if ($s) {
  5686. // output cell
  5687. $rs .= $s;
  5688. if ($this->font_spacing != 0) {
  5689. // reset font spacing mode
  5690. $rs .= ' BT 0 Tc ET';
  5691. }
  5692. if ($this->font_stretching != 100) {
  5693. // reset font stretching mode
  5694. $rs .= ' BT 100 Tz ET';
  5695. }
  5696. }
  5697. // reset word spacing
  5698. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  5699. $rs .= ' BT 0 Tw ET';
  5700. }
  5701. // reset stretching and spacing
  5702. $this->font_stretching = $prev_font_stretching;
  5703. $this->font_spacing = $prev_font_spacing;
  5704. $this->lasth = $h;
  5705. if ($ln > 0) {
  5706. //Go to the beginning of the next line
  5707. $this->y = $y + $h + $this->cell_margin['B'];
  5708. if ($ln == 1) {
  5709. if ($this->rtl) {
  5710. $this->x = $this->w - $this->rMargin;
  5711. } else {
  5712. $this->x = $this->lMargin;
  5713. }
  5714. }
  5715. } else {
  5716. // go left or right by case
  5717. if ($this->rtl) {
  5718. $this->x = $x - $w - $this->cell_margin['L'];
  5719. } else {
  5720. $this->x = $x + $w + $this->cell_margin['R'];
  5721. }
  5722. }
  5723. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  5724. $rs = $gstyles.$rs;
  5725. $this->cell_padding = $prev_cell_padding;
  5726. $this->cell_margin = $prev_cell_margin;
  5727. return $rs;
  5728. }
  5729. /**
  5730. * Returns the code to draw the cell border
  5731. * @param $x (float) X coordinate.
  5732. * @param $y (float) Y coordinate.
  5733. * @param $w (float) Cell width.
  5734. * @param $h (float) Cell height.
  5735. * @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)))
  5736. * @return string containing cell border code
  5737. * @protected
  5738. * @see SetLineStyle()
  5739. * @since 5.7.000 (2010-08-02)
  5740. */
  5741. protected function getCellBorder($x, $y, $w, $h, $brd) {
  5742. $s = ''; // string to be returned
  5743. if (empty($brd)) {
  5744. return $s;
  5745. }
  5746. if ($brd == 1) {
  5747. $brd = array('LRTB' => true);
  5748. }
  5749. // calculate coordinates for border
  5750. $k = $this->k;
  5751. if ($this->rtl) {
  5752. $xeL = ($x - $w) * $k;
  5753. $xeR = $x * $k;
  5754. } else {
  5755. $xeL = $x * $k;
  5756. $xeR = ($x + $w) * $k;
  5757. }
  5758. $yeL = (($this->h - ($y + $h)) * $k);
  5759. $yeT = (($this->h - $y) * $k);
  5760. $xeT = $xeL;
  5761. $xeB = $xeR;
  5762. $yeR = $yeT;
  5763. $yeB = $yeL;
  5764. if (is_string($brd)) {
  5765. // convert string to array
  5766. $slen = strlen($brd);
  5767. $newbrd = array();
  5768. for ($i = 0; $i < $slen; ++$i) {
  5769. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  5770. }
  5771. $brd = $newbrd;
  5772. }
  5773. if (isset($brd['mode'])) {
  5774. $mode = $brd['mode'];
  5775. unset($brd['mode']);
  5776. } else {
  5777. $mode = 'normal';
  5778. }
  5779. foreach ($brd as $border => $style) {
  5780. if (is_array($style) AND !empty($style)) {
  5781. // apply border style
  5782. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  5783. $s .= $this->SetLineStyle($style, true)."\n";
  5784. }
  5785. switch ($mode) {
  5786. case 'ext': {
  5787. $off = (($this->LineWidth / 2) * $k);
  5788. $xL = $xeL - $off;
  5789. $xR = $xeR + $off;
  5790. $yT = $yeT + $off;
  5791. $yL = $yeL - $off;
  5792. $xT = $xL;
  5793. $xB = $xR;
  5794. $yR = $yT;
  5795. $yB = $yL;
  5796. $w += $this->LineWidth;
  5797. $h += $this->LineWidth;
  5798. break;
  5799. }
  5800. case 'int': {
  5801. $off = ($this->LineWidth / 2) * $k;
  5802. $xL = $xeL + $off;
  5803. $xR = $xeR - $off;
  5804. $yT = $yeT - $off;
  5805. $yL = $yeL + $off;
  5806. $xT = $xL;
  5807. $xB = $xR;
  5808. $yR = $yT;
  5809. $yB = $yL;
  5810. $w -= $this->LineWidth;
  5811. $h -= $this->LineWidth;
  5812. break;
  5813. }
  5814. case 'normal':
  5815. default: {
  5816. $xL = $xeL;
  5817. $xT = $xeT;
  5818. $xB = $xeB;
  5819. $xR = $xeR;
  5820. $yL = $yeL;
  5821. $yT = $yeT;
  5822. $yB = $yeB;
  5823. $yR = $yeR;
  5824. break;
  5825. }
  5826. }
  5827. // draw borders by case
  5828. if (strlen($border) == 4) {
  5829. $s .= sprintf('%.2F %.2F %.2F %.2F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  5830. } elseif (strlen($border) == 3) {
  5831. if (strpos($border,'B') === false) { // LTR
  5832. $s .= sprintf('%.2F %.2F m ', $xL, $yL);
  5833. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5834. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5835. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5836. $s .= 'S ';
  5837. } elseif (strpos($border,'L') === false) { // TRB
  5838. $s .= sprintf('%.2F %.2F m ', $xT, $yT);
  5839. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5840. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5841. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5842. $s .= 'S ';
  5843. } elseif (strpos($border,'T') === false) { // RBL
  5844. $s .= sprintf('%.2F %.2F m ', $xR, $yR);
  5845. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5846. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5847. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5848. $s .= 'S ';
  5849. } elseif (strpos($border,'R') === false) { // BLT
  5850. $s .= sprintf('%.2F %.2F m ', $xB, $yB);
  5851. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5852. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5853. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5854. $s .= 'S ';
  5855. }
  5856. } elseif (strlen($border) == 2) {
  5857. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  5858. $s .= sprintf('%.2F %.2F m ', $xL, $yL);
  5859. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5860. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5861. $s .= 'S ';
  5862. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  5863. $s .= sprintf('%.2F %.2F m ', $xT, $yT);
  5864. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5865. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5866. $s .= 'S ';
  5867. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  5868. $s .= sprintf('%.2F %.2F m ', $xR, $yR);
  5869. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5870. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5871. $s .= 'S ';
  5872. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  5873. $s .= sprintf('%.2F %.2F m ', $xB, $yB);
  5874. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5875. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5876. $s .= 'S ';
  5877. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  5878. $s .= sprintf('%.2F %.2F m ', $xL, $yL);
  5879. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5880. $s .= 'S ';
  5881. $s .= sprintf('%.2F %.2F m ', $xR, $yR);
  5882. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5883. $s .= 'S ';
  5884. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  5885. $s .= sprintf('%.2F %.2F m ', $xT, $yT);
  5886. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5887. $s .= 'S ';
  5888. $s .= sprintf('%.2F %.2F m ', $xB, $yB);
  5889. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5890. $s .= 'S ';
  5891. }
  5892. } else { // strlen($border) == 1
  5893. if (strpos($border,'L') !== false) { // L
  5894. $s .= sprintf('%.2F %.2F m ', $xL, $yL);
  5895. $s .= sprintf('%.2F %.2F l ', $xT, $yT);
  5896. $s .= 'S ';
  5897. } elseif (strpos($border,'T') !== false) { // T
  5898. $s .= sprintf('%.2F %.2F m ', $xT, $yT);
  5899. $s .= sprintf('%.2F %.2F l ', $xR, $yR);
  5900. $s .= 'S ';
  5901. } elseif (strpos($border,'R') !== false) { // R
  5902. $s .= sprintf('%.2F %.2F m ', $xR, $yR);
  5903. $s .= sprintf('%.2F %.2F l ', $xB, $yB);
  5904. $s .= 'S ';
  5905. } elseif (strpos($border,'B') !== false) { // B
  5906. $s .= sprintf('%.2F %.2F m ', $xB, $yB);
  5907. $s .= sprintf('%.2F %.2F l ', $xL, $yL);
  5908. $s .= 'S ';
  5909. }
  5910. }
  5911. if (is_array($style) AND !empty($style)) {
  5912. // reset border style to previous value
  5913. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  5914. }
  5915. }
  5916. return $s;
  5917. }
  5918. /**
  5919. * This method allows printing text with line breaks.
  5920. * 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 />
  5921. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  5922. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5923. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  5924. * @param $txt (string) String to print
  5925. * @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)))
  5926. * @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>
  5927. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5928. * @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>
  5929. * @param $x (float) x position in user units
  5930. * @param $y (float) y position in user units
  5931. * @param $reseth (boolean) if true reset the last cell height (default true).
  5932. * @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.
  5933. * @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.
  5934. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  5935. * @param $maxh (float) maximum height. It should be >= $h and less than remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
  5936. * @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.
  5937. * @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).
  5938. * @return int Return the number of cells or 1 for html mode.
  5939. * @public
  5940. * @since 1.3
  5941. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  5942. */
  5943. 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) {
  5944. $prev_cell_margin = $this->cell_margin;
  5945. $prev_cell_padding = $this->cell_padding;
  5946. // adjust internal padding
  5947. $this->adjustCellPadding($border);
  5948. $mc_padding = $this->cell_padding;
  5949. $mc_margin = $this->cell_margin;
  5950. $this->cell_padding['T'] = 0;
  5951. $this->cell_padding['B'] = 0;
  5952. $this->setCellMargins(0, 0, 0, 0);
  5953. if ($this->empty_string($this->lasth) OR $reseth) {
  5954. // reset row height
  5955. $this->resetLastH();
  5956. }
  5957. if (!$this->empty_string($y)) {
  5958. $this->SetY($y);
  5959. } else {
  5960. $y = $this->GetY();
  5961. }
  5962. $resth = 0;
  5963. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  5964. // spit cell in more pages/columns
  5965. $newh = ($this->PageBreakTrigger - $y);
  5966. $resth = ($h - $newh); // cell to be printed on the next page/column
  5967. $h = $newh;
  5968. }
  5969. // get current page number
  5970. $startpage = $this->page;
  5971. // get current column
  5972. $startcolumn = $this->current_column;
  5973. if (!$this->empty_string($x)) {
  5974. $this->SetX($x);
  5975. } else {
  5976. $x = $this->GetX();
  5977. }
  5978. // check page for no-write regions and adapt page margins if necessary
  5979. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  5980. // apply margins
  5981. $oy = $y + $mc_margin['T'];
  5982. if ($this->rtl) {
  5983. $ox = $this->w - $x - $mc_margin['R'];
  5984. } else {
  5985. $ox = $x + $mc_margin['L'];
  5986. }
  5987. $this->x = $ox;
  5988. $this->y = $oy;
  5989. // set width
  5990. if ($this->empty_string($w) OR ($w <= 0)) {
  5991. if ($this->rtl) {
  5992. $w = $this->x - $this->lMargin - $mc_margin['L'];
  5993. } else {
  5994. $w = $this->w - $this->x - $this->rMargin - $mc_margin['R'];
  5995. }
  5996. }
  5997. // store original margin values
  5998. $lMargin = $this->lMargin;
  5999. $rMargin = $this->rMargin;
  6000. if ($this->rtl) {
  6001. $this->rMargin = $this->w - $this->x;
  6002. $this->lMargin = $this->x - $w;
  6003. } else {
  6004. $this->lMargin = $this->x;
  6005. $this->rMargin = $this->w - $this->x - $w;
  6006. }
  6007. if ($autopadding) {
  6008. // add top padding
  6009. $this->y += $mc_padding['T'];
  6010. }
  6011. if ($ishtml) { // ******* Write HTML text
  6012. $this->writeHTML($txt, true, false, $reseth, true, $align);
  6013. $nl = 1;
  6014. } else { // ******* Write simple text
  6015. $prev_FontSizePt = $this->FontSizePt;
  6016. // vertical alignment
  6017. if ($maxh > 0) {
  6018. // get text height
  6019. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  6020. if ($fitcell) {
  6021. // try to reduce font size to fit text on cell (use a quick search algorithm)
  6022. $fmin = 1;
  6023. $fmax = $this->FontSizePt;
  6024. $prev_text_height = $text_height;
  6025. $maxit = 100; // max number of iterations
  6026. while ($maxit > 0) {
  6027. $fmid = (($fmax + $fmin) / 2);
  6028. $this->SetFontSize($fmid, false);
  6029. $this->resetLastH();
  6030. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  6031. if (($text_height == $maxh) OR (($text_height < $maxh) AND ($fmin >= ($fmax - 0.01)))) {
  6032. break;
  6033. } elseif ($text_height < $maxh) {
  6034. $fmin = $fmid;
  6035. } else {
  6036. $fmax = $fmid;
  6037. }
  6038. --$maxit;
  6039. }
  6040. $this->SetFontSize($this->FontSizePt);
  6041. }
  6042. if ($text_height < $maxh) {
  6043. if ($valign == 'M') {
  6044. // text vertically centered
  6045. $this->y += (($maxh - $text_height) / 2);
  6046. } elseif ($valign == 'B') {
  6047. // text vertically aligned on bottom
  6048. $this->y += ($maxh - $text_height);
  6049. }
  6050. }
  6051. }
  6052. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  6053. if ($fitcell) {
  6054. // restore font size
  6055. $this->SetFontSize($prev_FontSizePt);
  6056. }
  6057. }
  6058. if ($autopadding) {
  6059. // add bottom padding
  6060. $this->y += $mc_padding['B'];
  6061. }
  6062. // Get end-of-text Y position
  6063. $currentY = $this->y;
  6064. // get latest page number
  6065. $endpage = $this->page;
  6066. if ($resth > 0) {
  6067. $skip = ($endpage - $startpage);
  6068. $tmpresth = $resth;
  6069. while ($tmpresth > 0) {
  6070. if ($skip <= 0) {
  6071. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  6072. $this->checkPageBreak($this->PageBreakTrigger + 1);
  6073. }
  6074. if ($this->num_columns > 1) {
  6075. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  6076. } else {
  6077. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  6078. }
  6079. --$skip;
  6080. }
  6081. $currentY = $this->y;
  6082. $endpage = $this->page;
  6083. }
  6084. // get latest column
  6085. $endcolumn = $this->current_column;
  6086. if ($this->num_columns == 0) {
  6087. $this->num_columns = 1;
  6088. }
  6089. // get border modes
  6090. $border_start = $this->getBorderMode($border, $position='start');
  6091. $border_end = $this->getBorderMode($border, $position='end');
  6092. $border_middle = $this->getBorderMode($border, $position='middle');
  6093. // design borders around HTML cells.
  6094. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  6095. $ccode = '';
  6096. $this->setPage($page);
  6097. if ($this->num_columns < 2) {
  6098. // single-column mode
  6099. $this->SetX($x);
  6100. $this->y = $this->tMargin;
  6101. }
  6102. // account for margin changes
  6103. if ($page > $startpage) {
  6104. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  6105. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  6106. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  6107. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  6108. }
  6109. }
  6110. if ($startpage == $endpage) {
  6111. // single page
  6112. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  6113. $this->selectColumn($column);
  6114. if ($this->rtl) {
  6115. $this->x -= $mc_margin['R'];
  6116. } else {
  6117. $this->x += $mc_margin['L'];
  6118. }
  6119. if ($startcolumn == $endcolumn) { // single column
  6120. $cborder = $border;
  6121. $h = max($h, ($currentY - $oy));
  6122. $this->y = $oy;
  6123. } elseif ($column == $startcolumn) { // first column
  6124. $cborder = $border_start;
  6125. $this->y = $oy;
  6126. $h = $this->h - $this->y - $this->bMargin;
  6127. } elseif ($column == $endcolumn) { // end column
  6128. $cborder = $border_end;
  6129. $h = $currentY - $this->y;
  6130. if ($resth > $h) {
  6131. $h = $resth;
  6132. }
  6133. } else { // middle column
  6134. $cborder = $border_middle;
  6135. $h = $this->h - $this->y - $this->bMargin;
  6136. $resth -= $h;
  6137. }
  6138. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6139. } // end for each column
  6140. } elseif ($page == $startpage) { // first page
  6141. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  6142. $this->selectColumn($column);
  6143. if ($this->rtl) {
  6144. $this->x -= $mc_margin['R'];
  6145. } else {
  6146. $this->x += $mc_margin['L'];
  6147. }
  6148. if ($column == $startcolumn) { // first column
  6149. $cborder = $border_start;
  6150. $this->y = $oy;
  6151. $h = $this->h - $this->y - $this->bMargin;
  6152. } else { // middle column
  6153. $cborder = $border_middle;
  6154. $h = $this->h - $this->y - $this->bMargin;
  6155. $resth -= $h;
  6156. }
  6157. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6158. } // end for each column
  6159. } elseif ($page == $endpage) { // last page
  6160. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  6161. $this->selectColumn($column);
  6162. if ($this->rtl) {
  6163. $this->x -= $mc_margin['R'];
  6164. } else {
  6165. $this->x += $mc_margin['L'];
  6166. }
  6167. if ($column == $endcolumn) {
  6168. // end column
  6169. $cborder = $border_end;
  6170. $h = $currentY - $this->y;
  6171. if ($resth > $h) {
  6172. $h = $resth;
  6173. }
  6174. } else {
  6175. // middle column
  6176. $cborder = $border_middle;
  6177. $h = $this->h - $this->y - $this->bMargin;
  6178. $resth -= $h;
  6179. }
  6180. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6181. } // end for each column
  6182. } else { // middle page
  6183. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  6184. $this->selectColumn($column);
  6185. if ($this->rtl) {
  6186. $this->x -= $mc_margin['R'];
  6187. } else {
  6188. $this->x += $mc_margin['L'];
  6189. }
  6190. $cborder = $border_middle;
  6191. $h = $this->h - $this->y - $this->bMargin;
  6192. $resth -= $h;
  6193. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6194. } // end for each column
  6195. }
  6196. if ($cborder OR $fill) {
  6197. $offsetlen = strlen($ccode);
  6198. // draw border and fill
  6199. if ($this->inxobj) {
  6200. // we are inside an XObject template
  6201. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  6202. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  6203. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  6204. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  6205. } else {
  6206. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  6207. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  6208. }
  6209. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  6210. $pstart = substr($pagebuff, 0, $pagemark);
  6211. $pend = substr($pagebuff, $pagemark);
  6212. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  6213. } else {
  6214. if (end($this->transfmrk[$this->page]) !== false) {
  6215. $pagemarkkey = key($this->transfmrk[$this->page]);
  6216. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  6217. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  6218. } elseif ($this->InFooter) {
  6219. $pagemark = $this->footerpos[$this->page];
  6220. $this->footerpos[$this->page] += $offsetlen;
  6221. } else {
  6222. $pagemark = $this->intmrk[$this->page];
  6223. $this->intmrk[$this->page] += $offsetlen;
  6224. }
  6225. $pagebuff = $this->getPageBuffer($this->page);
  6226. $pstart = substr($pagebuff, 0, $pagemark);
  6227. $pend = substr($pagebuff, $pagemark);
  6228. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  6229. }
  6230. }
  6231. } // end for each page
  6232. // Get end-of-cell Y position
  6233. $currentY = $this->GetY();
  6234. // restore previous values
  6235. if ($this->num_columns > 1) {
  6236. $this->selectColumn();
  6237. } else {
  6238. // restore original margins
  6239. $this->lMargin = $lMargin;
  6240. $this->rMargin = $rMargin;
  6241. if ($this->page > $startpage) {
  6242. // check for margin variations between pages (i.e. booklet mode)
  6243. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  6244. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  6245. if (($dl != 0) OR ($dr != 0)) {
  6246. $this->lMargin += $dl;
  6247. $this->rMargin += $dr;
  6248. }
  6249. }
  6250. }
  6251. if ($ln > 0) {
  6252. //Go to the beginning of the next line
  6253. $this->SetY($currentY + $mc_margin['B']);
  6254. if ($ln == 2) {
  6255. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  6256. }
  6257. } else {
  6258. // go left or right by case
  6259. $this->setPage($startpage);
  6260. $this->y = $y;
  6261. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  6262. }
  6263. $this->setContentMark();
  6264. $this->cell_padding = $prev_cell_padding;
  6265. $this->cell_margin = $prev_cell_margin;
  6266. return $nl;
  6267. }
  6268. /**
  6269. * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
  6270. * @param $brd (mixed) Indicates if borders must be drawn around the cell block. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  6271. * @param $position (string) multicell position: 'start', 'middle', 'end'
  6272. * @return border mode array
  6273. * @protected
  6274. * @since 4.4.002 (2008-12-09)
  6275. */
  6276. protected function getBorderMode($brd, $position='start') {
  6277. if ((!$this->opencell) OR empty($brd)) {
  6278. return $brd;
  6279. }
  6280. if ($brd == 1) {
  6281. $brd = 'LTRB';
  6282. }
  6283. if (is_string($brd)) {
  6284. // convert string to array
  6285. $slen = strlen($brd);
  6286. $newbrd = array();
  6287. for ($i = 0; $i < $slen; ++$i) {
  6288. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  6289. }
  6290. $brd = $newbrd;
  6291. }
  6292. foreach ($brd as $border => $style) {
  6293. switch ($position) {
  6294. case 'start': {
  6295. if (strpos($border, 'B') !== false) {
  6296. // remove bottom line
  6297. $newkey = str_replace('B', '', $border);
  6298. if (strlen($newkey) > 0) {
  6299. $brd[$newkey] = $style;
  6300. }
  6301. unset($brd[$border]);
  6302. }
  6303. break;
  6304. }
  6305. case 'middle': {
  6306. if (strpos($border, 'B') !== false) {
  6307. // remove bottom line
  6308. $newkey = str_replace('B', '', $border);
  6309. if (strlen($newkey) > 0) {
  6310. $brd[$newkey] = $style;
  6311. }
  6312. unset($brd[$border]);
  6313. $border = $newkey;
  6314. }
  6315. if (strpos($border, 'T') !== false) {
  6316. // remove bottom line
  6317. $newkey = str_replace('T', '', $border);
  6318. if (strlen($newkey) > 0) {
  6319. $brd[$newkey] = $style;
  6320. }
  6321. unset($brd[$border]);
  6322. }
  6323. break;
  6324. }
  6325. case 'end': {
  6326. if (strpos($border, 'T') !== false) {
  6327. // remove bottom line
  6328. $newkey = str_replace('T', '', $border);
  6329. if (strlen($newkey) > 0) {
  6330. $brd[$newkey] = $style;
  6331. }
  6332. unset($brd[$border]);
  6333. }
  6334. break;
  6335. }
  6336. }
  6337. }
  6338. return $brd;
  6339. }
  6340. /**
  6341. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  6342. * @param $txt (string) String for calculating his height
  6343. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  6344. * @param $reseth (boolean) if true reset the last cell height (default false).
  6345. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  6346. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  6347. * @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)))
  6348. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  6349. * @author Alexander Escalona Fernández, Nicola Asuni
  6350. * @public
  6351. * @since 4.5.011
  6352. */
  6353. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  6354. if ($txt === '') {
  6355. // empty string
  6356. return 1;
  6357. }
  6358. // adjust internal padding
  6359. $prev_cell_padding = $this->cell_padding;
  6360. $prev_lasth = $this->lasth;
  6361. if (is_array($cellpadding)) {
  6362. $this->cell_padding = $cellpadding;
  6363. }
  6364. $this->adjustCellPadding($border);
  6365. if ($this->empty_string($w) OR ($w <= 0)) {
  6366. if ($this->rtl) {
  6367. $w = $this->x - $this->lMargin;
  6368. } else {
  6369. $w = $this->w - $this->rMargin - $this->x;
  6370. }
  6371. }
  6372. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6373. if ($reseth) {
  6374. // reset row height
  6375. $this->resetLastH();
  6376. }
  6377. $lines = 1;
  6378. $sum = 0;
  6379. $chars = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl);
  6380. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  6381. $length = count($chars);
  6382. $lastSeparator = -1;
  6383. for ($i = 0; $i < $length; ++$i) {
  6384. $charWidth = $charsWidth[$i];
  6385. if (preg_match($this->re_spaces, $this->unichr($chars[$i]))) {
  6386. $lastSeparator = $i;
  6387. }
  6388. if ((($sum + $charWidth) > $wmax) OR ($chars[$i] == 10)) {
  6389. ++$lines;
  6390. if ($chars[$i] == 10) {
  6391. $lastSeparator = -1;
  6392. $sum = 0;
  6393. } elseif ($lastSeparator != -1) {
  6394. $i = $lastSeparator;
  6395. $lastSeparator = -1;
  6396. $sum = 0;
  6397. } else {
  6398. $sum = $charWidth;
  6399. }
  6400. } else {
  6401. $sum += $charWidth;
  6402. }
  6403. }
  6404. if ($chars[($length - 1)] == 10) {
  6405. --$lines;
  6406. }
  6407. $this->cell_padding = $prev_cell_padding;
  6408. $this->lasth = $prev_lasth;
  6409. return $lines;
  6410. }
  6411. /**
  6412. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  6413. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  6414. * @pre
  6415. * // store current object
  6416. * $pdf->startTransaction();
  6417. * // store starting values
  6418. * $start_y = $pdf->GetY();
  6419. * $start_page = $pdf->getPage();
  6420. * // call your printing functions with your parameters
  6421. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6422. * $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);
  6423. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6424. * // get the new Y
  6425. * $end_y = $pdf->GetY();
  6426. * $end_page = $pdf->getPage();
  6427. * // calculate height
  6428. * $height = 0;
  6429. * if ($end_page == $start_page) {
  6430. * $height = $end_y - $start_y;
  6431. * } else {
  6432. * for ($page=$start_page; $page <= $end_page; ++$page) {
  6433. * $this->setPage($page);
  6434. * if ($page == $start_page) {
  6435. * // first page
  6436. * $height = $this->h - $start_y - $this->bMargin;
  6437. * } elseif ($page == $end_page) {
  6438. * // last page
  6439. * $height = $end_y - $this->tMargin;
  6440. * } else {
  6441. * $height = $this->h - $this->tMargin - $this->bMargin;
  6442. * }
  6443. * }
  6444. * }
  6445. * // restore previous object
  6446. * $pdf = $pdf->rollbackTransaction();
  6447. *
  6448. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  6449. * @param $txt (string) String for calculating his height
  6450. * @param $reseth (boolean) if true reset the last cell height (default false).
  6451. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  6452. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  6453. * @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)))
  6454. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  6455. * @author Nicola Asuni, Alexander Escalona Fernández
  6456. * @public
  6457. */
  6458. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  6459. // adjust internal padding
  6460. $prev_cell_padding = $this->cell_padding;
  6461. $prev_lasth = $this->lasth;
  6462. if (is_array($cellpadding)) {
  6463. $this->cell_padding = $cellpadding;
  6464. }
  6465. $this->adjustCellPadding($border);
  6466. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  6467. $height = $lines * ($this->FontSize * $this->cell_height_ratio);
  6468. if ($autopadding) {
  6469. // add top and bottom padding
  6470. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  6471. }
  6472. $this->cell_padding = $prev_cell_padding;
  6473. $this->lasth = $prev_lasth;
  6474. return $height;
  6475. }
  6476. /**
  6477. * This method prints text from the current position.<br />
  6478. * @param $h (float) Line height
  6479. * @param $txt (string) String to print
  6480. * @param $link (mixed) URL or identifier returned by AddLink()
  6481. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  6482. * @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>
  6483. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  6484. * @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.
  6485. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  6486. * @param $firstblock (boolean) if true the string is the starting of a line.
  6487. * @param $maxh (float) maximum height. The remaining unprinted text will be returned. It should be >= $h and less than remaining space to the bottom of the page, or 0 for disable this feature.
  6488. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  6489. * @param $margin (array) margin array of the parent container
  6490. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  6491. * @public
  6492. * @since 1.5
  6493. */
  6494. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  6495. // check page for no-write regions and adapt page margins if necessary
  6496. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  6497. if (strlen($txt) == 0) {
  6498. // fix empty text
  6499. $txt = ' ';
  6500. }
  6501. if ($margin === '') {
  6502. // set default margins
  6503. $margin = $this->cell_margin;
  6504. }
  6505. // remove carriage returns
  6506. $s = str_replace("\r", '', $txt);
  6507. // check if string contains arabic text
  6508. if (preg_match($this->unicode->uni_RE_PATTERN_ARABIC, $s)) {
  6509. $arabic = true;
  6510. } else {
  6511. $arabic = false;
  6512. }
  6513. // check if string contains RTL text
  6514. if ($arabic OR ($this->tmprtl == 'R') OR preg_match($this->unicode->uni_RE_PATTERN_RTL, $s)) {
  6515. $rtlmode = true;
  6516. } else {
  6517. $rtlmode = false;
  6518. }
  6519. // get a char width
  6520. $chrwidth = $this->GetCharWidth(46); // dot character
  6521. // get array of unicode values
  6522. $chars = $this->UTF8StringToArray($s);
  6523. // get array of chars
  6524. $uchars = $this->UTF8ArrayToUniArray($chars);
  6525. // get the number of characters
  6526. $nb = count($chars);
  6527. // replacement for SHY character (minus symbol)
  6528. $shy_replacement = 45;
  6529. $shy_replacement_char = $this->unichr($shy_replacement);
  6530. // widht for SHY replacement
  6531. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  6532. // max Y
  6533. $maxy = $this->y + $maxh - $h - $this->cell_padding['T'] - $this->cell_padding['B'];
  6534. // page width
  6535. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  6536. // calculate remaining line width ($w)
  6537. if ($this->rtl) {
  6538. $w = $this->x - $this->lMargin;
  6539. } else {
  6540. $w = $this->w - $this->rMargin - $this->x;
  6541. }
  6542. // max column width
  6543. $wmax = $w - $wadj;
  6544. if (!$firstline) {
  6545. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  6546. }
  6547. if ((!$firstline) AND (($chrwidth > $wmax) OR ($this->GetCharWidth($chars[0]) > $wmax))) {
  6548. // a single character do not fit on column
  6549. return '';
  6550. }
  6551. // minimum row height
  6552. $row_height = max($h, $this->FontSize * $this->cell_height_ratio);
  6553. $start_page = $this->page;
  6554. $i = 0; // character position
  6555. $j = 0; // current starting position
  6556. $sep = -1; // position of the last blank space
  6557. $shy = false; // true if the last blank is a soft hypen (SHY)
  6558. $l = 0; // current string length
  6559. $nl = 0; //number of lines
  6560. $linebreak = false;
  6561. $pc = 0; // previous character
  6562. // for each character
  6563. while ($i < $nb) {
  6564. if (($maxh > 0) AND ($this->y >= $maxy) ) {
  6565. break;
  6566. }
  6567. //Get the current character
  6568. $c = $chars[$i];
  6569. if ($c == 10) { // 10 = "\n" = new line
  6570. //Explicit line break
  6571. if ($align == 'J') {
  6572. if ($this->rtl) {
  6573. $talign = 'R';
  6574. } else {
  6575. $talign = 'L';
  6576. }
  6577. } else {
  6578. $talign = $align;
  6579. }
  6580. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  6581. if ($firstline) {
  6582. $startx = $this->x;
  6583. $tmparr = array_slice($chars, $j, ($i - $j));
  6584. if ($rtlmode) {
  6585. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  6586. }
  6587. $linew = $this->GetArrStringWidth($tmparr);
  6588. unset($tmparr);
  6589. if ($this->rtl) {
  6590. $this->endlinex = $startx - $linew;
  6591. } else {
  6592. $this->endlinex = $startx + $linew;
  6593. }
  6594. $w = $linew;
  6595. $tmpcellpadding = $this->cell_padding;
  6596. if ($maxh == 0) {
  6597. $this->SetCellPadding(0);
  6598. }
  6599. }
  6600. if ($firstblock AND $this->isRTLTextDir()) {
  6601. $tmpstr = $this->stringRightTrim($tmpstr);
  6602. }
  6603. // Skip newlines at the begining of a page or column
  6604. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6605. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6606. }
  6607. unset($tmpstr);
  6608. if ($firstline) {
  6609. $this->cell_padding = $tmpcellpadding;
  6610. return ($this->UniArrSubString($uchars, $i));
  6611. }
  6612. ++$nl;
  6613. $j = $i + 1;
  6614. $l = 0;
  6615. $sep = -1;
  6616. $shy = false;
  6617. // account for margin changes
  6618. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6619. $this->AcceptPageBreak();
  6620. if ($this->rtl) {
  6621. $this->x -= $margin['R'];
  6622. } else {
  6623. $this->x += $margin['L'];
  6624. }
  6625. $this->lMargin += $margin['L'];
  6626. $this->rMargin += $margin['R'];
  6627. }
  6628. $w = $this->getRemainingWidth();
  6629. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6630. } else {
  6631. // 160 is the non-breaking space.
  6632. // 173 is SHY (Soft Hypen).
  6633. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6634. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6635. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6636. if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
  6637. // update last blank space position
  6638. $sep = $i;
  6639. // check if is a SHY
  6640. if ($c == 173) {
  6641. $shy = true;
  6642. if ($pc == 45) {
  6643. $tmp_shy_replacement_width = 0;
  6644. $tmp_shy_replacement_char = '';
  6645. } else {
  6646. $tmp_shy_replacement_width = $shy_replacement_width;
  6647. $tmp_shy_replacement_char = $shy_replacement_char;
  6648. }
  6649. } else {
  6650. $shy = false;
  6651. }
  6652. }
  6653. // update string length
  6654. if ($this->isUnicodeFont() AND ($arabic)) {
  6655. // with bidirectional algorithm some chars may be changed affecting the line length
  6656. // *** very slow ***
  6657. $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl));
  6658. } else {
  6659. $l += $this->GetCharWidth($c);
  6660. }
  6661. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) ) {
  6662. // we have reached the end of column
  6663. if ($sep == -1) {
  6664. // check if the line was already started
  6665. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
  6666. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
  6667. // print a void cell and go to next line
  6668. $this->Cell($w, $h, '', 0, 1);
  6669. $linebreak = true;
  6670. if ($firstline) {
  6671. return ($this->UniArrSubString($uchars, $j));
  6672. }
  6673. } else {
  6674. // truncate the word because do not fit on column
  6675. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  6676. if ($firstline) {
  6677. $startx = $this->x;
  6678. $tmparr = array_slice($chars, $j, ($i - $j));
  6679. if ($rtlmode) {
  6680. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  6681. }
  6682. $linew = $this->GetArrStringWidth($tmparr);
  6683. unset($tmparr);
  6684. if ($this->rtl) {
  6685. $this->endlinex = $startx - $linew;
  6686. } else {
  6687. $this->endlinex = $startx + $linew;
  6688. }
  6689. $w = $linew;
  6690. $tmpcellpadding = $this->cell_padding;
  6691. if ($maxh == 0) {
  6692. $this->SetCellPadding(0);
  6693. }
  6694. }
  6695. if ($firstblock AND $this->isRTLTextDir()) {
  6696. $tmpstr = $this->stringRightTrim($tmpstr);
  6697. }
  6698. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6699. unset($tmpstr);
  6700. if ($firstline) {
  6701. $this->cell_padding = $tmpcellpadding;
  6702. return ($this->UniArrSubString($uchars, $i));
  6703. }
  6704. $j = $i;
  6705. --$i;
  6706. }
  6707. } else {
  6708. // word wrapping
  6709. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  6710. $endspace = 1;
  6711. } else {
  6712. $endspace = 0;
  6713. }
  6714. // check the length of the next string
  6715. $strrest = $this->UniArrSubString($uchars, ($sep + $endspace));
  6716. $nextstr = preg_split('/'.$this->re_space['p'].'/'.$this->re_space['m'], $this->stringTrim($strrest));
  6717. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  6718. // truncate the word because do not fit on a full page width
  6719. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  6720. if ($firstline) {
  6721. $startx = $this->x;
  6722. $tmparr = array_slice($chars, $j, ($i - $j));
  6723. if ($rtlmode) {
  6724. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  6725. }
  6726. $linew = $this->GetArrStringWidth($tmparr);
  6727. unset($tmparr);
  6728. if ($this->rtl) {
  6729. $this->endlinex = $startx - $linew;
  6730. } else {
  6731. $this->endlinex = $startx + $linew;
  6732. }
  6733. $w = $linew;
  6734. $tmpcellpadding = $this->cell_padding;
  6735. if ($maxh == 0) {
  6736. $this->SetCellPadding(0);
  6737. }
  6738. }
  6739. if ($firstblock AND $this->isRTLTextDir()) {
  6740. $tmpstr = $this->stringRightTrim($tmpstr);
  6741. }
  6742. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6743. unset($tmpstr);
  6744. if ($firstline) {
  6745. $this->cell_padding = $tmpcellpadding;
  6746. return ($this->UniArrSubString($uchars, $i));
  6747. }
  6748. $j = $i;
  6749. --$i;
  6750. } else {
  6751. // word wrapping
  6752. if ($shy) {
  6753. // add hypen (minus symbol) at the end of the line
  6754. $shy_width = $tmp_shy_replacement_width;
  6755. if ($this->rtl) {
  6756. $shy_char_left = $tmp_shy_replacement_char;
  6757. $shy_char_right = '';
  6758. } else {
  6759. $shy_char_left = '';
  6760. $shy_char_right = $tmp_shy_replacement_char;
  6761. }
  6762. } else {
  6763. $shy_width = 0;
  6764. $shy_char_left = '';
  6765. $shy_char_right = '';
  6766. }
  6767. $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
  6768. if ($firstline) {
  6769. $startx = $this->x;
  6770. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  6771. if ($rtlmode) {
  6772. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  6773. }
  6774. $linew = $this->GetArrStringWidth($tmparr);
  6775. unset($tmparr);
  6776. if ($this->rtl) {
  6777. $this->endlinex = $startx - $linew - $shy_width;
  6778. } else {
  6779. $this->endlinex = $startx + $linew + $shy_width;
  6780. }
  6781. $w = $linew;
  6782. $tmpcellpadding = $this->cell_padding;
  6783. if ($maxh == 0) {
  6784. $this->SetCellPadding(0);
  6785. }
  6786. }
  6787. // print the line
  6788. if ($firstblock AND $this->isRTLTextDir()) {
  6789. $tmpstr = $this->stringRightTrim($tmpstr);
  6790. }
  6791. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  6792. unset($tmpstr);
  6793. if ($firstline) {
  6794. // return the remaining text
  6795. $this->cell_padding = $tmpcellpadding;
  6796. return ($this->UniArrSubString($uchars, ($sep + $endspace)));
  6797. }
  6798. $i = $sep;
  6799. $sep = -1;
  6800. $shy = false;
  6801. $j = ($i+1);
  6802. }
  6803. }
  6804. // account for margin changes
  6805. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6806. $this->AcceptPageBreak();
  6807. if ($this->rtl) {
  6808. $this->x -= $margin['R'];
  6809. } else {
  6810. $this->x += $margin['L'];
  6811. }
  6812. $this->lMargin += $margin['L'];
  6813. $this->rMargin += $margin['R'];
  6814. }
  6815. $w = $this->getRemainingWidth();
  6816. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6817. if ($linebreak) {
  6818. $linebreak = false;
  6819. } else {
  6820. ++$nl;
  6821. $l = 0;
  6822. }
  6823. }
  6824. }
  6825. // save last character
  6826. $pc = $c;
  6827. ++$i;
  6828. } // end while i < nb
  6829. // print last substring (if any)
  6830. if ($l > 0) {
  6831. switch ($align) {
  6832. case 'J':
  6833. case 'C': {
  6834. $w = $w;
  6835. break;
  6836. }
  6837. case 'L': {
  6838. if ($this->rtl) {
  6839. $w = $w;
  6840. } else {
  6841. $w = $l;
  6842. }
  6843. break;
  6844. }
  6845. case 'R': {
  6846. if ($this->rtl) {
  6847. $w = $l;
  6848. } else {
  6849. $w = $w;
  6850. }
  6851. break;
  6852. }
  6853. default: {
  6854. $w = $l;
  6855. break;
  6856. }
  6857. }
  6858. $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
  6859. if ($firstline) {
  6860. $startx = $this->x;
  6861. $tmparr = array_slice($chars, $j, ($nb - $j));
  6862. if ($rtlmode) {
  6863. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  6864. }
  6865. $linew = $this->GetArrStringWidth($tmparr);
  6866. unset($tmparr);
  6867. if ($this->rtl) {
  6868. $this->endlinex = $startx - $linew;
  6869. } else {
  6870. $this->endlinex = $startx + $linew;
  6871. }
  6872. $w = $linew;
  6873. $tmpcellpadding = $this->cell_padding;
  6874. if ($maxh == 0) {
  6875. $this->SetCellPadding(0);
  6876. }
  6877. }
  6878. if ($firstblock AND $this->isRTLTextDir()) {
  6879. $tmpstr = $this->stringRightTrim($tmpstr);
  6880. }
  6881. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  6882. unset($tmpstr);
  6883. if ($firstline) {
  6884. $this->cell_padding = $tmpcellpadding;
  6885. return ($this->UniArrSubString($uchars, $nb));
  6886. }
  6887. ++$nl;
  6888. }
  6889. if ($firstline) {
  6890. return '';
  6891. }
  6892. return $nl;
  6893. }
  6894. /**
  6895. * Returns the remaining width between the current position and margins.
  6896. * @return int Return the remaining width
  6897. * @protected
  6898. */
  6899. protected function getRemainingWidth() {
  6900. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  6901. if ($this->rtl) {
  6902. return ($this->x - $this->lMargin);
  6903. } else {
  6904. return ($this->w - $this->rMargin - $this->x);
  6905. }
  6906. }
  6907. /**
  6908. * Extract a slice of the $strarr array and return it as string.
  6909. * @param $strarr (string) The input array of characters.
  6910. * @param $start (int) the starting element of $strarr.
  6911. * @param $end (int) first element that will not be returned.
  6912. * @return Return part of a string
  6913. * @public
  6914. */
  6915. public function UTF8ArrSubString($strarr, $start='', $end='') {
  6916. if (strlen($start) == 0) {
  6917. $start = 0;
  6918. }
  6919. if (strlen($end) == 0) {
  6920. $end = count($strarr);
  6921. }
  6922. $string = '';
  6923. for ($i=$start; $i < $end; ++$i) {
  6924. $string .= $this->unichr($strarr[$i]);
  6925. }
  6926. return $string;
  6927. }
  6928. /**
  6929. * Extract a slice of the $uniarr array and return it as string.
  6930. * @param $uniarr (string) The input array of characters.
  6931. * @param $start (int) the starting element of $strarr.
  6932. * @param $end (int) first element that will not be returned.
  6933. * @return Return part of a string
  6934. * @public
  6935. * @since 4.5.037 (2009-04-07)
  6936. */
  6937. public function UniArrSubString($uniarr, $start='', $end='') {
  6938. if (strlen($start) == 0) {
  6939. $start = 0;
  6940. }
  6941. if (strlen($end) == 0) {
  6942. $end = count($uniarr);
  6943. }
  6944. $string = '';
  6945. for ($i=$start; $i < $end; ++$i) {
  6946. $string .= $uniarr[$i];
  6947. }
  6948. return $string;
  6949. }
  6950. /**
  6951. * Convert an array of UTF8 values to array of unicode characters
  6952. * @param $ta (string) The input array of UTF8 values.
  6953. * @return Return array of unicode characters
  6954. * @public
  6955. * @since 4.5.037 (2009-04-07)
  6956. */
  6957. public function UTF8ArrayToUniArray($ta) {
  6958. return array_map(array($this, 'unichr'), $ta);
  6959. }
  6960. /**
  6961. * Returns the unicode caracter specified by UTF-8 value
  6962. * @param $c (int) UTF-8 value
  6963. * @return Returns the specified character.
  6964. * @author Miguel Perez, Nicola Asuni
  6965. * @public
  6966. * @since 2.3.000 (2008-03-05)
  6967. */
  6968. public function unichr($c) {
  6969. if (!$this->isunicode) {
  6970. return chr($c);
  6971. } elseif ($c <= 0x7F) {
  6972. // one byte
  6973. return chr($c);
  6974. } elseif ($c <= 0x7FF) {
  6975. // two bytes
  6976. return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
  6977. } elseif ($c <= 0xFFFF) {
  6978. // three bytes
  6979. return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  6980. } elseif ($c <= 0x10FFFF) {
  6981. // four bytes
  6982. return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  6983. } else {
  6984. return '';
  6985. }
  6986. }
  6987. /**
  6988. * Return the image type given the file name or array returned by getimagesize() function.
  6989. * @param $imgfile (string) image file name
  6990. * @param $iminfo (array) array of image information returned by getimagesize() function.
  6991. * @return string image type
  6992. * @since 4.8.017 (2009-11-27)
  6993. */
  6994. public function getImageFileType($imgfile, $iminfo=array()) {
  6995. $type = '';
  6996. if (isset($iminfo['mime']) AND !empty($iminfo['mime'])) {
  6997. $mime = explode('/', $iminfo['mime']);
  6998. if ((count($mime) > 1) AND ($mime[0] == 'image') AND (!empty($mime[1]))) {
  6999. $type = strtolower(trim($mime[1]));
  7000. }
  7001. }
  7002. if (empty($type)) {
  7003. $fileinfo = pathinfo($imgfile);
  7004. if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
  7005. $type = strtolower(trim($fileinfo['extension']));
  7006. }
  7007. }
  7008. if ($type == 'jpg') {
  7009. $type = 'jpeg';
  7010. }
  7011. return $type;
  7012. }
  7013. /**
  7014. * Set the block dimensions accounting for page breaks and page/column fitting
  7015. * @param $w (float) width
  7016. * @param $h (float) height
  7017. * @param $x (float) X coordinate
  7018. * @param $y (float) Y coodiante
  7019. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  7020. * @return array($w, $h, $x, $y)
  7021. * @protected
  7022. * @since 5.5.009 (2010-07-05)
  7023. */
  7024. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  7025. if ($w <= 0) {
  7026. // set maximum width
  7027. $w = ($this->w - $this->lMargin - $this->rMargin);
  7028. }
  7029. if ($h <= 0) {
  7030. // set maximum height
  7031. $h = ($this->PageBreakTrigger - $this->tMargin);
  7032. }
  7033. // resize the block to be vertically contained on a single page or single column
  7034. if ($fitonpage OR $this->AutoPageBreak) {
  7035. $ratio_wh = ($w / $h);
  7036. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  7037. $h = $this->PageBreakTrigger - $this->tMargin;
  7038. $w = ($h * $ratio_wh);
  7039. }
  7040. // resize the block to be horizontally contained on a single page or single column
  7041. if ($fitonpage) {
  7042. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  7043. if ($w > $maxw) {
  7044. $w = $maxw;
  7045. $h = ($w / $ratio_wh);
  7046. }
  7047. }
  7048. }
  7049. // Check whether we need a new page or new column first as this does not fit
  7050. $prev_x = $this->x;
  7051. $prev_y = $this->y;
  7052. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  7053. $y = $this->y;
  7054. if ($this->rtl) {
  7055. $x += ($prev_x - $this->x);
  7056. } else {
  7057. $x += ($this->x - $prev_x);
  7058. }
  7059. $this->newline = true;
  7060. }
  7061. // resize the block to be contained on the remaining available page or column space
  7062. if ($fitonpage) {
  7063. $ratio_wh = ($w / $h);
  7064. if (($y + $h) > $this->PageBreakTrigger) {
  7065. $h = $this->PageBreakTrigger - $y;
  7066. $w = ($h * $ratio_wh);
  7067. }
  7068. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  7069. $w = $this->w - $this->rMargin - $x;
  7070. $h = ($w / $ratio_wh);
  7071. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  7072. $w = $x - $this->lMargin;
  7073. $h = ($w / $ratio_wh);
  7074. }
  7075. }
  7076. return array($w, $h, $x, $y);
  7077. }
  7078. /**
  7079. * Puts an image in the page.
  7080. * The upper-left corner must be given.
  7081. * The dimensions can be specified in different ways:<ul>
  7082. * <li>explicit width and height (expressed in user unit)</li>
  7083. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  7084. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  7085. * 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;
  7086. * The format can be specified explicitly or inferred from the file extension.<br />
  7087. * It is possible to put a link on the image.<br />
  7088. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  7089. * @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').
  7090. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  7091. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  7092. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  7093. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  7094. * @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.
  7095. * @param $link (mixed) URL or identifier returned by AddLink().
  7096. * @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>
  7097. * @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).
  7098. * @param $dpi (int) dot-per-inch resolution used on resize
  7099. * @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>
  7100. * @param $ismask (boolean) true if this image is a mask, false otherwise
  7101. * @param $imgmask (mixed) image object returned by this function or false
  7102. * @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)))
  7103. * @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).
  7104. * @param $hidden (boolean) If true do not display the image.
  7105. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  7106. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  7107. * @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.
  7108. * @return image information
  7109. * @public
  7110. * @since 1.1
  7111. */
  7112. 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()) {
  7113. if ($x === '') {
  7114. $x = $this->x;
  7115. }
  7116. if ($y === '') {
  7117. $y = $this->y;
  7118. }
  7119. // check page for no-write regions and adapt page margins if necessary
  7120. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  7121. $cached_file = false; // true when the file is cached
  7122. $exurl = ''; // external streams
  7123. // check if we are passing an image as file or string
  7124. if ($file[0] === '@') {
  7125. // image from string
  7126. $imgdata = substr($file, 1);
  7127. $file = K_PATH_CACHE.'img_'.md5($imgdata);
  7128. $fp = fopen($file, 'w');
  7129. fwrite($fp, $imgdata);
  7130. fclose($fp);
  7131. unset($imgdata);
  7132. $cached_file = true;
  7133. $imsize = @getimagesize($file);
  7134. if ($imsize === FALSE) {
  7135. unlink($file);
  7136. $cached_file = false;
  7137. }
  7138. } else { // image file
  7139. if ($file{0} === '*') {
  7140. // image as external stream
  7141. $file = substr($file, 1);
  7142. $exurl = $file;
  7143. }
  7144. // check if is local file
  7145. if (!@file_exists($file)) {
  7146. // encode spaces on filename (file is probably an URL)
  7147. $file = str_replace(' ', '%20', $file);
  7148. }
  7149. if (@file_exists($file)) {
  7150. // get image dimensions
  7151. $imsize = @getimagesize($file);
  7152. } else {
  7153. $imsize = false;
  7154. }
  7155. if ($imsize === FALSE) {
  7156. if (function_exists('curl_init')) {
  7157. // try to get remote file data using cURL
  7158. $cs = curl_init(); // curl session
  7159. curl_setopt($cs, CURLOPT_URL, $file);
  7160. curl_setopt($cs, CURLOPT_BINARYTRANSFER, true);
  7161. curl_setopt($cs, CURLOPT_FAILONERROR, true);
  7162. curl_setopt($cs, CURLOPT_RETURNTRANSFER, true);
  7163. curl_setopt($cs, CURLOPT_FOLLOWLOCATION, true);
  7164. curl_setopt($cs, CURLOPT_CONNECTTIMEOUT, 5);
  7165. curl_setopt($cs, CURLOPT_TIMEOUT, 30);
  7166. curl_setopt($cs, CURLOPT_SSL_VERIFYPEER, false);
  7167. curl_setopt($cs, CURLOPT_SSL_VERIFYHOST, false);
  7168. curl_setopt($cs, CURLOPT_USERAGENT, 'TCPDF');
  7169. $imgdata = curl_exec($cs);
  7170. curl_close($cs);
  7171. if ($imgdata !== FALSE) {
  7172. // copy image to cache
  7173. $file = K_PATH_CACHE.'img_'.md5($imgdata);
  7174. $fp = fopen($file, 'w');
  7175. fwrite($fp, $imgdata);
  7176. fclose($fp);
  7177. unset($imgdata);
  7178. $cached_file = true;
  7179. $imsize = @getimagesize($file);
  7180. if ($imsize === FALSE) {
  7181. unlink($file);
  7182. $cached_file = false;
  7183. }
  7184. }
  7185. } elseif (($w > 0) AND ($h > 0)) {
  7186. // get measures from specified data
  7187. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7188. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7189. $imsize = array($pw, $ph);
  7190. }
  7191. }
  7192. }
  7193. if ($imsize === FALSE) {
  7194. if (substr($file, 0, -34) == K_PATH_CACHE.'msk') { // mask file
  7195. // get measures from specified data
  7196. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7197. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7198. $imsize = array($pw, $ph);
  7199. } else {
  7200. $this->Error('[Image] Unable to get image: '.$file);
  7201. }
  7202. }
  7203. // get original image width and height in pixels
  7204. list($pixw, $pixh) = $imsize;
  7205. // calculate image width and height on document
  7206. if (($w <= 0) AND ($h <= 0)) {
  7207. // convert image size to document unit
  7208. $w = $this->pixelsToUnits($pixw);
  7209. $h = $this->pixelsToUnits($pixh);
  7210. } elseif ($w <= 0) {
  7211. $w = $h * $pixw / $pixh;
  7212. } elseif ($h <= 0) {
  7213. $h = $w * $pixh / $pixw;
  7214. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  7215. if (strlen($fitbox) !== 2) {
  7216. // set default alignment
  7217. $fitbox = '--';
  7218. }
  7219. // scale image dimensions proportionally to fit within the ($w, $h) box
  7220. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  7221. // store current height
  7222. $oldh = $h;
  7223. // calculate new height
  7224. $h = $w * $pixh / $pixw;
  7225. // height difference
  7226. $hdiff = ($oldh - $h);
  7227. // vertical alignment
  7228. switch (strtoupper($fitbox{1})) {
  7229. case 'T': {
  7230. break;
  7231. }
  7232. case 'M': {
  7233. $y += ($hdiff / 2);
  7234. break;
  7235. }
  7236. case 'B': {
  7237. $y += $hdiff;
  7238. break;
  7239. }
  7240. }
  7241. } else {
  7242. // store current width
  7243. $oldw = $w;
  7244. // calculate new width
  7245. $w = $h * $pixw / $pixh;
  7246. // width difference
  7247. $wdiff = ($oldw - $w);
  7248. // horizontal alignment
  7249. switch (strtoupper($fitbox{0})) {
  7250. case 'L': {
  7251. if ($this->rtl) {
  7252. $x -= $wdiff;
  7253. }
  7254. break;
  7255. }
  7256. case 'C': {
  7257. if ($this->rtl) {
  7258. $x -= ($wdiff / 2);
  7259. } else {
  7260. $x += ($wdiff / 2);
  7261. }
  7262. break;
  7263. }
  7264. case 'R': {
  7265. if (!$this->rtl) {
  7266. $x += $wdiff;
  7267. }
  7268. break;
  7269. }
  7270. }
  7271. }
  7272. }
  7273. // fit the image on available space
  7274. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  7275. // calculate new minimum dimensions in pixels
  7276. $neww = round($w * $this->k * $dpi / $this->dpi);
  7277. $newh = round($h * $this->k * $dpi / $this->dpi);
  7278. // check if resize is necessary (resize is used only to reduce the image)
  7279. $newsize = ($neww * $newh);
  7280. $pixsize = ($pixw * $pixh);
  7281. if (intval($resize) == 2) {
  7282. $resize = true;
  7283. } elseif ($newsize >= $pixsize) {
  7284. $resize = false;
  7285. }
  7286. // check if image has been already added on document
  7287. $newimage = true;
  7288. if (in_array($file, $this->imagekeys)) {
  7289. $newimage = false;
  7290. // get existing image data
  7291. $info = $this->getImageBuffer($file);
  7292. if (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
  7293. // check if the newer image is larger
  7294. $oldsize = ($info['w'] * $info['h']);
  7295. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  7296. $newimage = true;
  7297. }
  7298. }
  7299. } elseif (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
  7300. // check for cached images with alpha channel
  7301. $filehash = md5($file);
  7302. $tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
  7303. $tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
  7304. if (in_array($tempfile_plain, $this->imagekeys)) {
  7305. // get existing image data
  7306. $info = $this->getImageBuffer($tempfile_plain);
  7307. // check if the newer image is larger
  7308. $oldsize = ($info['w'] * $info['h']);
  7309. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  7310. $newimage = true;
  7311. } else {
  7312. $newimage = false;
  7313. // embed mask image
  7314. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  7315. // embed image, masked with previously embedded mask
  7316. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  7317. }
  7318. }
  7319. }
  7320. if ($newimage) {
  7321. //First use of image, get info
  7322. $type = strtolower($type);
  7323. if ($type == '') {
  7324. $type = $this->getImageFileType($file, $imsize);
  7325. } elseif ($type == 'jpg') {
  7326. $type = 'jpeg';
  7327. }
  7328. $mqr = $this->get_mqr();
  7329. $this->set_mqr(false);
  7330. // Specific image handlers
  7331. $mtd = '_parse'.$type;
  7332. // GD image handler function
  7333. $gdfunction = 'imagecreatefrom'.$type;
  7334. $info = false;
  7335. if ((method_exists($this, $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  7336. // TCPDF image functions
  7337. $info = $this->$mtd($file);
  7338. if ($info == 'pngalpha') {
  7339. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  7340. }
  7341. }
  7342. if (!$info) {
  7343. if (function_exists($gdfunction)) {
  7344. // GD library
  7345. $img = $gdfunction($file);
  7346. if ($resize) {
  7347. $imgr = imagecreatetruecolor($neww, $newh);
  7348. if (($type == 'gif') OR ($type == 'png')) {
  7349. $imgr = $this->_setGDImageTransparency($imgr, $img);
  7350. }
  7351. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  7352. if (($type == 'gif') OR ($type == 'png')) {
  7353. $info = $this->_toPNG($imgr);
  7354. } else {
  7355. $info = $this->_toJPEG($imgr);
  7356. }
  7357. } else {
  7358. if (($type == 'gif') OR ($type == 'png')) {
  7359. $info = $this->_toPNG($img);
  7360. } else {
  7361. $info = $this->_toJPEG($img);
  7362. }
  7363. }
  7364. } elseif (extension_loaded('imagick')) {
  7365. // ImageMagick library
  7366. $img = new Imagick();
  7367. if ($type == 'SVG') {
  7368. // get SVG file content
  7369. $svgimg = file_get_contents($file);
  7370. // get width and height
  7371. $regs = array();
  7372. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  7373. $svgtag = $regs[1];
  7374. $tmp = array();
  7375. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  7376. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  7377. $owu = sprintf('%.3F', ($ow * $dpi / 72)).$this->pdfunit;
  7378. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  7379. } else {
  7380. $ow = $w;
  7381. }
  7382. $tmp = array();
  7383. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  7384. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  7385. $ohu = sprintf('%.3F', ($oh * $dpi / 72)).$this->pdfunit;
  7386. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  7387. } else {
  7388. $oh = $h;
  7389. }
  7390. $tmp = array();
  7391. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  7392. $vbw = ($ow * $this->imgscale * $this->k);
  7393. $vbh = ($oh * $this->imgscale * $this->k);
  7394. $vbox = sprintf(' viewBox="0 0 %.3F %.3F" ', $vbw, $vbh);
  7395. $svgtag = $vbox.$svgtag;
  7396. }
  7397. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  7398. }
  7399. $img->readImageBlob($svgimg);
  7400. } else {
  7401. $img->readImage($file);
  7402. }
  7403. if ($resize) {
  7404. $img->resizeImage($neww, $newh, 10, 1, false);
  7405. }
  7406. $img->setCompressionQuality($this->jpeg_quality);
  7407. $img->setImageFormat('jpeg');
  7408. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  7409. $img->writeImage($tempname);
  7410. $info = $this->_parsejpeg($tempname);
  7411. unlink($tempname);
  7412. $img->destroy();
  7413. } else {
  7414. return;
  7415. }
  7416. }
  7417. if ($info === false) {
  7418. //If false, we cannot process image
  7419. return;
  7420. }
  7421. $this->set_mqr($mqr);
  7422. if ($ismask) {
  7423. // force grayscale
  7424. $info['cs'] = 'DeviceGray';
  7425. }
  7426. $info['i'] = $this->numimages;
  7427. if (!in_array($file, $this->imagekeys)) {
  7428. ++$info['i'];
  7429. }
  7430. if ($imgmask !== false) {
  7431. $info['masked'] = $imgmask;
  7432. }
  7433. if (!empty($exurl)) {
  7434. $info['exurl'] = $exurl;
  7435. }
  7436. // array of alternative images
  7437. $info['altimgs'] = $altimgs;
  7438. // add image to document
  7439. $this->setImageBuffer($file, $info);
  7440. }
  7441. if ($cached_file) {
  7442. // remove cached file
  7443. unlink($file);
  7444. }
  7445. // set alignment
  7446. $this->img_rb_y = $y + $h;
  7447. // set alignment
  7448. if ($this->rtl) {
  7449. if ($palign == 'L') {
  7450. $ximg = $this->lMargin;
  7451. } elseif ($palign == 'C') {
  7452. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  7453. } elseif ($palign == 'R') {
  7454. $ximg = $this->w - $this->rMargin - $w;
  7455. } else {
  7456. $ximg = $x - $w;
  7457. }
  7458. $this->img_rb_x = $ximg;
  7459. } else {
  7460. if ($palign == 'L') {
  7461. $ximg = $this->lMargin;
  7462. } elseif ($palign == 'C') {
  7463. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  7464. } elseif ($palign == 'R') {
  7465. $ximg = $this->w - $this->rMargin - $w;
  7466. } else {
  7467. $ximg = $x;
  7468. }
  7469. $this->img_rb_x = $ximg + $w;
  7470. }
  7471. if ($ismask OR $hidden) {
  7472. // image is not displayed
  7473. return $info['i'];
  7474. }
  7475. $xkimg = $ximg * $this->k;
  7476. if (!$alt) {
  7477. // only non-alternative immages will be set
  7478. $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
  7479. }
  7480. if (!empty($border)) {
  7481. $bx = $this->x;
  7482. $by = $this->y;
  7483. $this->x = $ximg;
  7484. if ($this->rtl) {
  7485. $this->x += $w;
  7486. }
  7487. $this->y = $y;
  7488. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  7489. $this->x = $bx;
  7490. $this->y = $by;
  7491. }
  7492. if ($link) {
  7493. $this->Link($ximg, $y, $w, $h, $link, 0);
  7494. }
  7495. // set pointer to align the next text/objects
  7496. switch($align) {
  7497. case 'T': {
  7498. $this->y = $y;
  7499. $this->x = $this->img_rb_x;
  7500. break;
  7501. }
  7502. case 'M': {
  7503. $this->y = $y + round($h/2);
  7504. $this->x = $this->img_rb_x;
  7505. break;
  7506. }
  7507. case 'B': {
  7508. $this->y = $this->img_rb_y;
  7509. $this->x = $this->img_rb_x;
  7510. break;
  7511. }
  7512. case 'N': {
  7513. $this->SetY($this->img_rb_y);
  7514. break;
  7515. }
  7516. default:{
  7517. break;
  7518. }
  7519. }
  7520. $this->endlinex = $this->img_rb_x;
  7521. if ($this->inxobj) {
  7522. // we are inside an XObject template
  7523. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  7524. }
  7525. return $info['i'];
  7526. }
  7527. /**
  7528. * Sets the current active configuration setting of magic_quotes_runtime (if the set_magic_quotes_runtime function exist)
  7529. * @param $mqr (boolean) FALSE for off, TRUE for on.
  7530. * @since 4.6.025 (2009-08-17)
  7531. */
  7532. public function set_mqr($mqr) {
  7533. if (!defined('PHP_VERSION_ID')) {
  7534. $version = PHP_VERSION;
  7535. define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4}));
  7536. }
  7537. if (PHP_VERSION_ID < 50300) {
  7538. @set_magic_quotes_runtime($mqr);
  7539. }
  7540. }
  7541. /**
  7542. * Gets the current active configuration setting of magic_quotes_runtime (if the get_magic_quotes_runtime function exist)
  7543. * @return Returns 0 if magic quotes runtime is off or get_magic_quotes_runtime doesn't exist, 1 otherwise.
  7544. * @since 4.6.025 (2009-08-17)
  7545. */
  7546. public function get_mqr() {
  7547. if (!defined('PHP_VERSION_ID')) {
  7548. $version = PHP_VERSION;
  7549. define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4}));
  7550. }
  7551. if (PHP_VERSION_ID < 50300) {
  7552. return @get_magic_quotes_runtime();
  7553. }
  7554. return 0;
  7555. }
  7556. /**
  7557. * Convert the loaded image to a JPEG and then return a structure for the PDF creator.
  7558. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
  7559. * @param $image (image) Image object.
  7560. * return image JPEG image object.
  7561. * @protected
  7562. */
  7563. protected function _toJPEG($image) {
  7564. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  7565. imagejpeg($image, $tempname, $this->jpeg_quality);
  7566. imagedestroy($image);
  7567. $retvars = $this->_parsejpeg($tempname);
  7568. // tidy up by removing temporary image
  7569. unlink($tempname);
  7570. return $retvars;
  7571. }
  7572. /**
  7573. * Convert the loaded image to a PNG and then return a structure for the PDF creator.
  7574. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
  7575. * @param $image (image) Image object.
  7576. * return image PNG image object.
  7577. * @protected
  7578. * @since 4.9.016 (2010-04-20)
  7579. */
  7580. protected function _toPNG($image) {
  7581. // set temporary image file name
  7582. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  7583. // turn off interlaced mode
  7584. imageinterlace($image, 0);
  7585. // create temporary PNG image
  7586. imagepng($image, $tempname);
  7587. // remove image from memory
  7588. imagedestroy($image);
  7589. // get PNG image data
  7590. $retvars = $this->_parsepng($tempname);
  7591. // tidy up by removing temporary image
  7592. unlink($tempname);
  7593. return $retvars;
  7594. }
  7595. /**
  7596. * Set the transparency for the given GD image.
  7597. * @param $new_image (image) GD image object
  7598. * @param $image (image) GD image object.
  7599. * return GD image object.
  7600. * @protected
  7601. * @since 4.9.016 (2010-04-20)
  7602. */
  7603. protected function _setGDImageTransparency($new_image, $image) {
  7604. // transparency index
  7605. $tid = imagecolortransparent($image);
  7606. // default transparency color
  7607. $tcol = array('red' => 255, 'green' => 255, 'blue' => 255);
  7608. if ($tid >= 0) {
  7609. // get the colors for the transparency index
  7610. $tcol = imagecolorsforindex($image, $tid);
  7611. }
  7612. $tid = imagecolorallocate($new_image, $tcol['red'], $tcol['green'], $tcol['blue']);
  7613. imagefill($new_image, 0, 0, $tid);
  7614. imagecolortransparent($new_image, $tid);
  7615. return $new_image;
  7616. }
  7617. /**
  7618. * Extract info from a JPEG file without using the GD library.
  7619. * @param $file (string) image file to parse
  7620. * @return array structure containing the image data
  7621. * @protected
  7622. */
  7623. protected function _parsejpeg($file) {
  7624. $a = getimagesize($file);
  7625. if (empty($a)) {
  7626. $this->Error('Missing or incorrect image file: '.$file);
  7627. }
  7628. if ($a[2] != 2) {
  7629. $this->Error('Not a JPEG file: '.$file);
  7630. }
  7631. // bits per pixel
  7632. $bpc = isset($a['bits']) ? intval($a['bits']) : 8;
  7633. // number of image channels
  7634. if (!isset($a['channels'])) {
  7635. $channels = 3;
  7636. } else {
  7637. $channels = intval($a['channels']);
  7638. }
  7639. // default colour space
  7640. switch ($channels) {
  7641. case 1: {
  7642. $colspace = 'DeviceGray';
  7643. break;
  7644. }
  7645. case 3: {
  7646. $colspace = 'DeviceRGB';
  7647. break;
  7648. }
  7649. case 4: {
  7650. $colspace = 'DeviceCMYK';
  7651. break;
  7652. }
  7653. default: {
  7654. $channels = 3;
  7655. $colspace = 'DeviceRGB';
  7656. break;
  7657. }
  7658. }
  7659. // get file content
  7660. $data = file_get_contents($file);
  7661. // check for embedded ICC profile
  7662. $icc = array();
  7663. $offset = 0;
  7664. while (($pos = strpos($data, "ICC_PROFILE\0", $offset)) !== false) {
  7665. // get ICC sequence length
  7666. $length = ($this->_getUSHORT($data, ($pos - 2)) - 16);
  7667. // marker sequence number
  7668. $msn = max(1, ord($data[($pos + 12)]));
  7669. // number of markers (total of APP2 used)
  7670. $nom = max(1, ord($data[($pos + 13)]));
  7671. // get sequence segment
  7672. $icc[($msn - 1)] = substr($data, ($pos + 14), $length);
  7673. // move forward to next sequence
  7674. $offset = ($pos + 14 + $length);
  7675. }
  7676. // order and compact ICC segments
  7677. if (count($icc) > 0) {
  7678. ksort($icc);
  7679. $icc = implode('', $icc);
  7680. if ((ord($icc{36}) != 0x61) OR (ord($icc{37}) != 0x63) OR (ord($icc{38}) != 0x73) OR (ord($icc{39}) != 0x70)) {
  7681. // invalid ICC profile
  7682. $icc = false;
  7683. }
  7684. } else {
  7685. $icc = false;
  7686. }
  7687. return array('w' => $a[0], 'h' => $a[1], 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
  7688. }
  7689. /**
  7690. * Extract info from a PNG file without using the GD library.
  7691. * @param $file (string) image file to parse
  7692. * @return array structure containing the image data
  7693. * @protected
  7694. */
  7695. protected function _parsepng($file) {
  7696. $f = fopen($file, 'rb');
  7697. if ($f === false) {
  7698. $this->Error('Can\'t open image file: '.$file);
  7699. }
  7700. //Check signature
  7701. if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
  7702. $this->Error('Not a PNG file: '.$file);
  7703. }
  7704. //Read header chunk
  7705. fread($f, 4);
  7706. if (fread($f, 4) != 'IHDR') {
  7707. $this->Error('Incorrect PNG file: '.$file);
  7708. }
  7709. $w = $this->_freadint($f);
  7710. $h = $this->_freadint($f);
  7711. $bpc = ord(fread($f, 1));
  7712. if ($bpc > 8) {
  7713. //$this->Error('16-bit depth not supported: '.$file);
  7714. fclose($f);
  7715. return false;
  7716. }
  7717. $ct = ord(fread($f, 1));
  7718. if ($ct == 0) {
  7719. $colspace = 'DeviceGray';
  7720. } elseif ($ct == 2) {
  7721. $colspace = 'DeviceRGB';
  7722. } elseif ($ct == 3) {
  7723. $colspace = 'Indexed';
  7724. } else {
  7725. // alpha channel
  7726. fclose($f);
  7727. return 'pngalpha';
  7728. }
  7729. if (ord(fread($f, 1)) != 0) {
  7730. //$this->Error('Unknown compression method: '.$file);
  7731. fclose($f);
  7732. return false;
  7733. }
  7734. if (ord(fread($f, 1)) != 0) {
  7735. //$this->Error('Unknown filter method: '.$file);
  7736. fclose($f);
  7737. return false;
  7738. }
  7739. if (ord(fread($f, 1)) != 0) {
  7740. //$this->Error('Interlacing not supported: '.$file);
  7741. fclose($f);
  7742. return false;
  7743. }
  7744. fread($f, 4);
  7745. $channels = ($ct == 2 ? 3 : 1);
  7746. $parms = '/DecodeParms << /Predictor 15 /Colors '.$channels.' /BitsPerComponent '.$bpc.' /Columns '.$w.' >>';
  7747. //Scan chunks looking for palette, transparency and image data
  7748. $pal = '';
  7749. $trns = '';
  7750. $data = '';
  7751. $icc = false;
  7752. do {
  7753. $n = $this->_freadint($f);
  7754. $type = fread($f, 4);
  7755. if ($type == 'PLTE') {
  7756. // read palette
  7757. $pal = $this->rfread($f, $n);
  7758. fread($f, 4);
  7759. } elseif ($type == 'tRNS') {
  7760. // read transparency info
  7761. $t = $this->rfread($f, $n);
  7762. if ($ct == 0) {
  7763. $trns = array(ord($t{1}));
  7764. } elseif ($ct == 2) {
  7765. $trns = array(ord($t{1}), ord($t{3}), ord($t{5}));
  7766. } else {
  7767. $pos = strpos($t, chr(0));
  7768. if ($pos !== false) {
  7769. $trns = array($pos);
  7770. }
  7771. }
  7772. fread($f, 4);
  7773. } elseif ($type == 'IDAT') {
  7774. // read image data block
  7775. $data .= $this->rfread($f, $n);
  7776. fread($f, 4);
  7777. } elseif ($type == 'iCCP') {
  7778. // skip profile name and null separator
  7779. $len = 0;
  7780. while ((ord(fread($f, 1)) > 0) AND ($len < 80)) {
  7781. ++$len;
  7782. }
  7783. // get compression method
  7784. if (ord(fread($f, 1)) != 0) {
  7785. //$this->Error('Unknown filter method: '.$file);
  7786. fclose($f);
  7787. return false;
  7788. }
  7789. // read ICC Color Profile
  7790. $icc = $this->rfread($f, ($n - $len - 2));
  7791. // decompress profile
  7792. $icc = gzuncompress($icc);
  7793. fread($f, 4);
  7794. } elseif ($type == 'IEND') {
  7795. break;
  7796. } else {
  7797. $this->rfread($f, $n + 4);
  7798. }
  7799. } while ($n);
  7800. if (($colspace == 'Indexed') AND (empty($pal))) {
  7801. //$this->Error('Missing palette in '.$file);
  7802. fclose($f);
  7803. return false;
  7804. }
  7805. fclose($f);
  7806. return array('w' => $w, 'h' => $h, 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
  7807. }
  7808. /**
  7809. * Binary-safe and URL-safe file read.
  7810. * Reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read; EOF (end of file) is reached.
  7811. * @param $handle (resource)
  7812. * @param $length (int)
  7813. * @return Returns the read string or FALSE in case of error.
  7814. * @author Nicola Asuni
  7815. * @protected
  7816. * @since 4.5.027 (2009-03-16)
  7817. */
  7818. protected function rfread($handle, $length) {
  7819. $data = fread($handle, $length);
  7820. if ($data === false) {
  7821. return false;
  7822. }
  7823. $rest = $length - strlen($data);
  7824. if ($rest > 0) {
  7825. $data .= $this->rfread($handle, $rest);
  7826. }
  7827. return $data;
  7828. }
  7829. /**
  7830. * Extract info from a PNG image with alpha channel using the GD library.
  7831. * @param $file (string) Name of the file containing the image.
  7832. * @param $x (float) Abscissa of the upper-left corner.
  7833. * @param $y (float) Ordinate of the upper-left corner.
  7834. * @param $wpx (float) Original width of the image in pixels.
  7835. * @param $hpx (float) original height of the image in pixels.
  7836. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  7837. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  7838. * @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.
  7839. * @param $link (mixed) URL or identifier returned by AddLink().
  7840. * @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>
  7841. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  7842. * @param $dpi (int) dot-per-inch resolution used on resize
  7843. * @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>
  7844. * @param $filehash (string) File hash used to build unique file names.
  7845. * @author Nicola Asuni
  7846. * @protected
  7847. * @since 4.3.007 (2008-12-04)
  7848. * @see Image()
  7849. */
  7850. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  7851. if (empty($filehash)) {
  7852. $filehash = md5($file);
  7853. }
  7854. // create temp image file (without alpha channel)
  7855. $tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
  7856. // create temp alpha file
  7857. $tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
  7858. if (extension_loaded('imagick')) { // ImageMagick extension
  7859. // ImageMagick library
  7860. $img = new Imagick();
  7861. $img->readImage($file);
  7862. // clone image object
  7863. $imga = $img->clone();
  7864. // extract alpha channel
  7865. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  7866. $img->negateImage(true);
  7867. $img->setImageFormat('png');
  7868. $img->writeImage($tempfile_alpha);
  7869. // remove alpha channel
  7870. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  7871. $imga->setImageFormat('png');
  7872. $imga->writeImage($tempfile_plain);
  7873. } elseif (function_exists('imagecreatefrompng')) { // GD extension
  7874. // generate images
  7875. $img = imagecreatefrompng($file);
  7876. $imgalpha = imagecreate($wpx, $hpx);
  7877. // generate gray scale palette (0 -> 255)
  7878. for ($c = 0; $c < 256; ++$c) {
  7879. ImageColorAllocate($imgalpha, $c, $c, $c);
  7880. }
  7881. // extract alpha channel
  7882. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  7883. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  7884. $color = imagecolorat($img, $xpx, $ypx);
  7885. $alpha = ($color >> 24); // shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha)
  7886. $alpha = (((127 - $alpha) / 127) * 255); // GD alpha is only 7 bit (0 -> 127)
  7887. $alpha = $this->getGDgamma($alpha); // correct gamma
  7888. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  7889. }
  7890. }
  7891. imagepng($imgalpha, $tempfile_alpha);
  7892. imagedestroy($imgalpha);
  7893. // extract image without alpha channel
  7894. $imgplain = imagecreatetruecolor($wpx, $hpx);
  7895. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  7896. imagepng($imgplain, $tempfile_plain);
  7897. imagedestroy($imgplain);
  7898. } else {
  7899. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  7900. }
  7901. // embed mask image
  7902. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  7903. // embed image, masked with previously embedded mask
  7904. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  7905. // remove temp files
  7906. unlink($tempfile_alpha);
  7907. unlink($tempfile_plain);
  7908. }
  7909. /**
  7910. * Correct the gamma value to be used with GD library
  7911. * @param $v (float) the gamma value to be corrected
  7912. * @protected
  7913. * @since 4.3.007 (2008-12-04)
  7914. */
  7915. protected function getGDgamma($v) {
  7916. return (pow(($v / 255), 2.2) * 255);
  7917. }
  7918. /**
  7919. * Performs a line break.
  7920. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  7921. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  7922. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  7923. * @public
  7924. * @since 1.0
  7925. * @see Cell()
  7926. */
  7927. public function Ln($h='', $cell=false) {
  7928. 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'])) {
  7929. // revove vertical space from the top of the column
  7930. return;
  7931. }
  7932. if ($cell) {
  7933. if ($this->rtl) {
  7934. $cellpadding = $this->cell_padding['R'];
  7935. } else {
  7936. $cellpadding = $this->cell_padding['L'];
  7937. }
  7938. } else {
  7939. $cellpadding = 0;
  7940. }
  7941. if ($this->rtl) {
  7942. $this->x = $this->w - $this->rMargin - $cellpadding;
  7943. } else {
  7944. $this->x = $this->lMargin + $cellpadding;
  7945. }
  7946. if (is_string($h)) {
  7947. $this->y += $this->lasth;
  7948. } else {
  7949. $this->y += $h;
  7950. }
  7951. $this->newline = true;
  7952. }
  7953. /**
  7954. * Returns the relative X value of current position.
  7955. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  7956. * @return float
  7957. * @public
  7958. * @since 1.2
  7959. * @see SetX(), GetY(), SetY()
  7960. */
  7961. public function GetX() {
  7962. //Get x position
  7963. if ($this->rtl) {
  7964. return ($this->w - $this->x);
  7965. } else {
  7966. return $this->x;
  7967. }
  7968. }
  7969. /**
  7970. * Returns the absolute X value of current position.
  7971. * @return float
  7972. * @public
  7973. * @since 1.2
  7974. * @see SetX(), GetY(), SetY()
  7975. */
  7976. public function GetAbsX() {
  7977. return $this->x;
  7978. }
  7979. /**
  7980. * Returns the ordinate of the current position.
  7981. * @return float
  7982. * @public
  7983. * @since 1.0
  7984. * @see SetY(), GetX(), SetX()
  7985. */
  7986. public function GetY() {
  7987. return $this->y;
  7988. }
  7989. /**
  7990. * Defines the abscissa of the current position.
  7991. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  7992. * @param $x (float) The value of the abscissa.
  7993. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7994. * @public
  7995. * @since 1.2
  7996. * @see GetX(), GetY(), SetY(), SetXY()
  7997. */
  7998. public function SetX($x, $rtloff=false) {
  7999. if (!$rtloff AND $this->rtl) {
  8000. if ($x >= 0) {
  8001. $this->x = $this->w - $x;
  8002. } else {
  8003. $this->x = abs($x);
  8004. }
  8005. } else {
  8006. if ($x >= 0) {
  8007. $this->x = $x;
  8008. } else {
  8009. $this->x = $this->w + $x;
  8010. }
  8011. }
  8012. if ($this->x < 0) {
  8013. $this->x = 0;
  8014. }
  8015. if ($this->x > $this->w) {
  8016. $this->x = $this->w;
  8017. }
  8018. }
  8019. /**
  8020. * Moves the current abscissa back to the left margin and sets the ordinate.
  8021. * If the passed value is negative, it is relative to the bottom of the page.
  8022. * @param $y (float) The value of the ordinate.
  8023. * @param $resetx (bool) if true (default) reset the X position.
  8024. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  8025. * @public
  8026. * @since 1.0
  8027. * @see GetX(), GetY(), SetY(), SetXY()
  8028. */
  8029. public function SetY($y, $resetx=true, $rtloff=false) {
  8030. if ($resetx) {
  8031. //reset x
  8032. if (!$rtloff AND $this->rtl) {
  8033. $this->x = $this->w - $this->rMargin;
  8034. } else {
  8035. $this->x = $this->lMargin;
  8036. }
  8037. }
  8038. if ($y >= 0) {
  8039. $this->y = $y;
  8040. } else {
  8041. $this->y = $this->h + $y;
  8042. }
  8043. if ($this->y < 0) {
  8044. $this->y = 0;
  8045. }
  8046. if ($this->y > $this->h) {
  8047. $this->y = $this->h;
  8048. }
  8049. }
  8050. /**
  8051. * Defines the abscissa and ordinate of the current position.
  8052. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  8053. * @param $x (float) The value of the abscissa.
  8054. * @param $y (float) The value of the ordinate.
  8055. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  8056. * @public
  8057. * @since 1.2
  8058. * @see SetX(), SetY()
  8059. */
  8060. public function SetXY($x, $y, $rtloff=false) {
  8061. $this->SetY($y, false, $rtloff);
  8062. $this->SetX($x, $rtloff);
  8063. }
  8064. /**
  8065. * Ouput input data and compress it if possible.
  8066. * @param $data (string) Data to output.
  8067. * @param $length (int) Data length in bytes.
  8068. * @protected
  8069. * @since 5.9.086
  8070. */
  8071. protected function sendOutputData($data, $length) {
  8072. if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) OR empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
  8073. // the content length may vary if the server is using compression
  8074. header('Content-Length: '.$length);
  8075. }
  8076. echo $data;
  8077. }
  8078. /**
  8079. * Send the document to a given destination: string, local file or browser.
  8080. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  8081. * The method first calls Close() if necessary to terminate the document.
  8082. * @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.
  8083. * @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>
  8084. * @public
  8085. * @since 1.0
  8086. * @see Close()
  8087. */
  8088. public function Output($name='doc.pdf', $dest='I') {
  8089. //Output PDF to some destination
  8090. //Finish document if necessary
  8091. if ($this->state < 3) {
  8092. $this->Close();
  8093. }
  8094. //Normalize parameters
  8095. if (is_bool($dest)) {
  8096. $dest = $dest ? 'D' : 'F';
  8097. }
  8098. $dest = strtoupper($dest);
  8099. if ($dest{0} != 'F') {
  8100. $name = preg_replace('/[\s]+/', '_', $name);
  8101. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  8102. }
  8103. if ($this->sign) {
  8104. // *** apply digital signature to the document ***
  8105. // get the document content
  8106. $pdfdoc = $this->getBuffer();
  8107. // remove last newline
  8108. $pdfdoc = substr($pdfdoc, 0, -1);
  8109. // Remove the original buffer
  8110. if (isset($this->diskcache) AND $this->diskcache) {
  8111. // remove buffer file from cache
  8112. unlink($this->buffer);
  8113. }
  8114. unset($this->buffer);
  8115. // remove filler space
  8116. $byterange_string_len = strlen($this->byterange_string);
  8117. // define the ByteRange
  8118. $byte_range = array();
  8119. $byte_range[0] = 0;
  8120. $byte_range[1] = strpos($pdfdoc, $this->byterange_string) + $byterange_string_len + 10;
  8121. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  8122. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  8123. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  8124. // replace the ByteRange
  8125. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  8126. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  8127. $pdfdoc = str_replace($this->byterange_string, $byterange, $pdfdoc);
  8128. // write the document to a temporary folder
  8129. $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
  8130. $f = fopen($tempdoc, 'wb');
  8131. if (!$f) {
  8132. $this->Error('Unable to create temporary file: '.$tempdoc);
  8133. }
  8134. $pdfdoc_length = strlen($pdfdoc);
  8135. fwrite($f, $pdfdoc, $pdfdoc_length);
  8136. fclose($f);
  8137. // get digital signature via openssl library
  8138. $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
  8139. if (empty($this->signature_data['extracerts'])) {
  8140. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  8141. } else {
  8142. 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']);
  8143. }
  8144. unlink($tempdoc);
  8145. // read signature
  8146. $signature = file_get_contents($tempsign);
  8147. unlink($tempsign);
  8148. // extract signature
  8149. $signature = substr($signature, $pdfdoc_length);
  8150. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  8151. $tmparr = explode("\n\n", $signature);
  8152. $signature = $tmparr[1];
  8153. unset($tmparr);
  8154. // decode signature
  8155. $signature = base64_decode(trim($signature));
  8156. // convert signature to hex
  8157. $signature = current(unpack('H*', $signature));
  8158. $signature = str_pad($signature, $this->signature_max_length, '0');
  8159. // disable disk caching
  8160. $this->diskcache = false;
  8161. // Add signature to the document
  8162. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  8163. $this->bufferlen = strlen($this->buffer);
  8164. }
  8165. switch($dest) {
  8166. case 'I': {
  8167. // Send PDF to the standard output
  8168. if (ob_get_contents()) {
  8169. $this->Error('Some data has already been output, can\'t send PDF file');
  8170. }
  8171. if (php_sapi_name() != 'cli') {
  8172. // send output to a browser
  8173. header('Content-Type: application/pdf');
  8174. if (headers_sent()) {
  8175. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  8176. }
  8177. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8178. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  8179. header('Pragma: public');
  8180. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8181. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8182. header('Content-Disposition: inline; filename="'.basename($name).'";');
  8183. $this->sendOutputData($this->getBuffer(), $this->bufferlen);
  8184. } else {
  8185. echo $this->getBuffer();
  8186. }
  8187. break;
  8188. }
  8189. case 'D': {
  8190. // download PDF as file
  8191. if (ob_get_contents()) {
  8192. $this->Error('Some data has already been output, can\'t send PDF file');
  8193. }
  8194. header('Content-Description: File Transfer');
  8195. if (headers_sent()) {
  8196. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  8197. }
  8198. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8199. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  8200. header('Pragma: public');
  8201. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8202. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8203. // force download dialog
  8204. if (strpos(php_sapi_name(), 'cgi') === false) {
  8205. header('Content-Type: application/force-download');
  8206. header('Content-Type: application/octet-stream', false);
  8207. header('Content-Type: application/download', false);
  8208. header('Content-Type: application/pdf', false);
  8209. } else {
  8210. header('Content-Type: application/pdf');
  8211. }
  8212. // use the Content-Disposition header to supply a recommended filename
  8213. header('Content-Disposition: attachment; filename="'.basename($name).'";');
  8214. header('Content-Transfer-Encoding: binary');
  8215. $this->sendOutputData($this->getBuffer(), $this->bufferlen);
  8216. break;
  8217. }
  8218. case 'F':
  8219. case 'FI':
  8220. case 'FD': {
  8221. // save PDF to a local file
  8222. if ($this->diskcache) {
  8223. copy($this->buffer, $name);
  8224. } else {
  8225. $f = fopen($name, 'wb');
  8226. if (!$f) {
  8227. $this->Error('Unable to create output file: '.$name);
  8228. }
  8229. fwrite($f, $this->getBuffer(), $this->bufferlen);
  8230. fclose($f);
  8231. }
  8232. if ($dest == 'FI') {
  8233. // send headers to browser
  8234. header('Content-Type: application/pdf');
  8235. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8236. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  8237. header('Pragma: public');
  8238. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8239. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8240. header('Content-Disposition: inline; filename="'.basename($name).'";');
  8241. $this->sendOutputData(file_get_contents($name), filesize($name));
  8242. } elseif ($dest == 'FD') {
  8243. // send headers to browser
  8244. if (ob_get_contents()) {
  8245. $this->Error('Some data has already been output, can\'t send PDF file');
  8246. }
  8247. header('Content-Description: File Transfer');
  8248. if (headers_sent()) {
  8249. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  8250. }
  8251. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8252. header('Pragma: public');
  8253. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8254. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8255. // force download dialog
  8256. if (strpos(php_sapi_name(), 'cgi') === false) {
  8257. header('Content-Type: application/force-download');
  8258. header('Content-Type: application/octet-stream', false);
  8259. header('Content-Type: application/download', false);
  8260. header('Content-Type: application/pdf', false);
  8261. } else {
  8262. header('Content-Type: application/pdf');
  8263. }
  8264. // use the Content-Disposition header to supply a recommended filename
  8265. header('Content-Disposition: attachment; filename="'.basename($name).'";');
  8266. header('Content-Transfer-Encoding: binary');
  8267. $this->sendOutputData(file_get_contents($name), filesize($name));
  8268. }
  8269. break;
  8270. }
  8271. case 'E': {
  8272. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  8273. $retval = 'Content-Type: application/pdf;'."\r\n";
  8274. $retval .= ' name="'.$name.'"'."\r\n";
  8275. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  8276. $retval .= 'Content-Disposition: attachment;'."\r\n";
  8277. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  8278. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  8279. return $retval;
  8280. }
  8281. case 'S': {
  8282. // returns PDF as a string
  8283. return $this->getBuffer();
  8284. }
  8285. default: {
  8286. $this->Error('Incorrect output destination: '.$dest);
  8287. }
  8288. }
  8289. return '';
  8290. }
  8291. /**
  8292. * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
  8293. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  8294. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  8295. * @public
  8296. * @since 4.5.016 (2009-02-24)
  8297. */
  8298. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  8299. if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
  8300. // remove buffer file from cache
  8301. unlink($this->buffer);
  8302. }
  8303. foreach (array_keys(get_object_vars($this)) as $val) {
  8304. if ($destroyall OR (
  8305. ($val != 'internal_encoding')
  8306. AND ($val != 'state')
  8307. AND ($val != 'bufferlen')
  8308. AND ($val != 'buffer')
  8309. AND ($val != 'diskcache')
  8310. AND ($val != 'sign')
  8311. AND ($val != 'signature_data')
  8312. AND ($val != 'signature_max_length')
  8313. AND ($val != 'byterange_string')
  8314. )) {
  8315. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND isset($this->$val)) {
  8316. unset($this->$val);
  8317. }
  8318. }
  8319. }
  8320. }
  8321. /**
  8322. * Check for locale-related bug
  8323. * @protected
  8324. */
  8325. protected function _dochecks() {
  8326. //Check for locale-related bug
  8327. if (1.1 == 1) {
  8328. $this->Error('Don\'t alter the locale before including class file');
  8329. }
  8330. //Check for decimal separator
  8331. if (sprintf('%.1F', 1.0) != '1.0') {
  8332. setlocale(LC_NUMERIC, 'C');
  8333. }
  8334. }
  8335. /**
  8336. * Return fonts path
  8337. * @return string
  8338. * @protected
  8339. */
  8340. protected function _getfontpath() {
  8341. if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
  8342. define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
  8343. }
  8344. return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
  8345. }
  8346. /**
  8347. * Return an array containing variations for the basic page number alias.
  8348. * @param $a (string) Base alias.
  8349. * @return array of page number aliases
  8350. * @protected
  8351. */
  8352. protected function getInternalPageNumberAliases($a= '') {
  8353. $alias = array();
  8354. // build array of Unicode + ASCII variants (the order is important)
  8355. $alias = array('u' => array(), 'a' => array());
  8356. $u = '{'.$a.'}';
  8357. $alias['u'][] = $this->_escape($u);
  8358. if ($this->isunicode) {
  8359. $alias['u'][] = $this->_escape($this->UTF8ToLatin1($u));
  8360. $alias['u'][] = $this->_escape($this->utf8StrRev($u, false, $this->tmprtl));
  8361. $alias['a'][] = $this->_escape($this->UTF8ToLatin1($a));
  8362. $alias['a'][] = $this->_escape($this->utf8StrRev($a, false, $this->tmprtl));
  8363. }
  8364. $alias['a'][] = $this->_escape($a);
  8365. return $alias;
  8366. }
  8367. /**
  8368. * Return an array containing all internal page aliases.
  8369. * @return array of page number aliases
  8370. * @protected
  8371. */
  8372. protected function getAllInternalPageNumberAliases() {
  8373. $basic_alias = array($this->alias_tot_pages, $this->alias_num_page, $this->alias_group_tot_pages, $this->alias_group_num_page, $this->alias_right_shift);
  8374. $pnalias = array();
  8375. foreach($basic_alias as $k => $a) {
  8376. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  8377. }
  8378. return $pnalias;
  8379. }
  8380. /**
  8381. * Replace page number aliases with number.
  8382. * @param $page (string) Page content.
  8383. * @param $replace (array) Array of replacements (array keys are replacement strings, values are alias arrays).
  8384. * @param $diff (int) If passed, this will be set to the total char number difference between alias and replacements.
  8385. * @return replaced page content and updated $diff parameter as array.
  8386. * @protected
  8387. */
  8388. protected function replacePageNumAliases($page, $replace, $diff=0) {
  8389. foreach ($replace as $rep) {
  8390. foreach ($rep[3] as $a) {
  8391. if (strpos($page, $a) !== false) {
  8392. $page = str_replace($a, $rep[0], $page);
  8393. $diff += ($rep[2] - $rep[1]);
  8394. }
  8395. }
  8396. }
  8397. return array($page, $diff);
  8398. }
  8399. /**
  8400. * Replace right shift page number aliases with spaces to correct right alignment.
  8401. * This works perfectly only when using monospaced fonts.
  8402. * @param $page (string) Page content.
  8403. * @param $aliases (array) Array of page aliases.
  8404. * @param $diff (int) initial difference to add.
  8405. * @return replaced page content.
  8406. * @protected
  8407. */
  8408. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  8409. foreach ($aliases as $type => $alias) {
  8410. foreach ($alias as $a) {
  8411. // find position of compensation factor
  8412. $startnum = (strpos($a, ':') + 1);
  8413. $a = substr($a, 0, $startnum);
  8414. if (($pos = strpos($page, $a)) !== false) {
  8415. // end of alias
  8416. $endnum = strpos($page, '}', $pos);
  8417. // string to be replaced
  8418. $aa = substr($page, $pos, ($endnum - $pos + 1));
  8419. // get compensation factor
  8420. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  8421. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  8422. $ratio = floatval($ratio);
  8423. if ($type == 'u') {
  8424. $chrdiff = floor(($diff + 12) * $ratio);
  8425. $shift = str_repeat(' ', $chrdiff);
  8426. $shift = $this->UTF8ToUTF16BE($shift, false);
  8427. } else {
  8428. $chrdiff = floor(($diff + 11) * $ratio);
  8429. $shift = str_repeat(' ', $chrdiff);
  8430. }
  8431. $page = str_replace($aa, $shift, $page);
  8432. }
  8433. }
  8434. }
  8435. return $page;
  8436. }
  8437. /**
  8438. * Output pages (and replace page number aliases).
  8439. * @protected
  8440. */
  8441. protected function _putpages() {
  8442. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8443. // get internal aliases for page numbers
  8444. $pnalias = $this->getAllInternalPageNumberAliases();
  8445. $num_pages = $this->numpages;
  8446. $ptpa = $this->formatPageNumber(($this->starting_page_number + $num_pages - 1));
  8447. $ptpu = $this->UTF8ToUTF16BE($ptpa, false);
  8448. $ptp_num_chars = $this->GetNumChars($ptpa);
  8449. $pagegroupnum = 0;
  8450. $groupnum = 0;
  8451. $ptgu = 1;
  8452. $ptga = 1;
  8453. for ($n = 1; $n <= $num_pages; ++$n) {
  8454. // get current page
  8455. $temppage = $this->getPageBuffer($n);
  8456. $pagelen = strlen($temppage);
  8457. // set replacements for total pages number
  8458. $pnpa = $this->formatPageNumber(($this->starting_page_number + $n - 1));
  8459. $pnpu = $this->UTF8ToUTF16BE($pnpa, false);
  8460. $pnp_num_chars = $this->GetNumChars($pnpa);
  8461. $pdiff = 0; // difference used for right shift alignment of page numbers
  8462. $gdiff = 0; // difference used for right shift alignment of page group numbers
  8463. if (!empty($this->pagegroups)) {
  8464. if (isset($this->newpagegroup[$n])) {
  8465. $pagegroupnum = 0;
  8466. ++$groupnum;
  8467. $ptga = $this->formatPageNumber($this->pagegroups[$groupnum]);
  8468. $ptgu = $this->UTF8ToUTF16BE($ptga, false);
  8469. $ptg_num_chars = $this->GetNumChars($ptga);
  8470. }
  8471. ++$pagegroupnum;
  8472. $pnga = $this->formatPageNumber($pagegroupnum);
  8473. $pngu = $this->UTF8ToUTF16BE($pnga, false);
  8474. $png_num_chars = $this->GetNumChars($pnga);
  8475. // replace page numbers
  8476. $replace = array();
  8477. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  8478. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  8479. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  8480. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  8481. list($temppage, $gdiff) = $this->replacePageNumAliases($temppage, $replace, $gdiff);
  8482. }
  8483. // replace page numbers
  8484. $replace = array();
  8485. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  8486. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  8487. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  8488. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  8489. list($temppage, $pdiff) = $this->replacePageNumAliases($temppage, $replace, $pdiff);
  8490. // replace right shift alias
  8491. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  8492. // replace EPS marker
  8493. $temppage = str_replace($this->epsmarker, '', $temppage);
  8494. //Page
  8495. $this->page_obj_id[$n] = $this->_newobj();
  8496. $out = '<<';
  8497. $out .= ' /Type /Page';
  8498. $out .= ' /Parent 1 0 R';
  8499. $out .= ' /LastModified '.$this->_datestring();
  8500. $out .= ' /Resources 2 0 R';
  8501. $boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  8502. foreach ($boxes as $box) {
  8503. $out .= ' /'.$box;
  8504. $out .= sprintf(' [%.2F %.2F %.2F %.2F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']);
  8505. }
  8506. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  8507. $out .= ' /BoxColorInfo <<';
  8508. foreach ($boxes as $box) {
  8509. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  8510. $out .= ' /'.$box.' <<';
  8511. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  8512. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  8513. $out .= ' /C [';
  8514. $out .= sprintf(' %.3F %.3F %.3F', $color[0]/255, $color[1]/255, $color[2]/255);
  8515. $out .= ' ]';
  8516. }
  8517. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  8518. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  8519. }
  8520. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  8521. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  8522. }
  8523. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  8524. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  8525. $out .= ' /D [';
  8526. foreach ($dashes as $dash) {
  8527. $out .= sprintf(' %.3F', ($dash * $this->k));
  8528. }
  8529. $out .= ' ]';
  8530. }
  8531. $out .= ' >>';
  8532. }
  8533. }
  8534. $out .= ' >>';
  8535. }
  8536. $out .= ' /Contents '.($this->n + 1).' 0 R';
  8537. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  8538. if (!$this->pdfa_mode) {
  8539. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  8540. }
  8541. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  8542. // page transitions
  8543. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  8544. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  8545. }
  8546. $out .= ' /Trans <<';
  8547. $out .= ' /Type /Trans';
  8548. if (isset($this->pagedim[$n]['trans']['S'])) {
  8549. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  8550. }
  8551. if (isset($this->pagedim[$n]['trans']['D'])) {
  8552. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  8553. }
  8554. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  8555. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  8556. }
  8557. if (isset($this->pagedim[$n]['trans']['M'])) {
  8558. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  8559. }
  8560. if (isset($this->pagedim[$n]['trans']['Di'])) {
  8561. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  8562. }
  8563. if (isset($this->pagedim[$n]['trans']['SS'])) {
  8564. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  8565. }
  8566. if (isset($this->pagedim[$n]['trans']['B'])) {
  8567. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  8568. }
  8569. $out .= ' >>';
  8570. }
  8571. $out .= $this->_getannotsrefs($n);
  8572. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  8573. $out .= ' >>';
  8574. $out .= "\n".'endobj';
  8575. $this->_out($out);
  8576. //Page content
  8577. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  8578. $this->_newobj();
  8579. $p = $this->_getrawstream($p);
  8580. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  8581. if ($this->diskcache) {
  8582. // remove temporary files
  8583. unlink($this->pages[$n]);
  8584. }
  8585. }
  8586. //Pages root
  8587. $out = $this->_getobj(1)."\n";
  8588. $out .= '<< /Type /Pages /Kids [';
  8589. foreach($this->page_obj_id as $page_obj) {
  8590. $out .= ' '.$page_obj.' 0 R';
  8591. }
  8592. $out .= ' ] /Count '.$num_pages.' >>';
  8593. $out .= "\n".'endobj';
  8594. $this->_out($out);
  8595. }
  8596. /**
  8597. * Output references to page annotations
  8598. * @param $n (int) page number
  8599. * @protected
  8600. * @author Nicola Asuni
  8601. * @since 4.7.000 (2008-08-29)
  8602. * @deprecated
  8603. */
  8604. protected function _putannotsrefs($n) {
  8605. $this->_out($this->_getannotsrefs($n));
  8606. }
  8607. /**
  8608. * Get references to page annotations.
  8609. * @param $n (int) page number
  8610. * @return string
  8611. * @protected
  8612. * @author Nicola Asuni
  8613. * @since 5.0.010 (2010-05-17)
  8614. */
  8615. protected function _getannotsrefs($n) {
  8616. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  8617. return '';
  8618. }
  8619. $out = ' /Annots [';
  8620. if (isset($this->PageAnnots[$n])) {
  8621. foreach ($this->PageAnnots[$n] as $key => $val) {
  8622. if (!in_array($val['n'], $this->radio_groups)) {
  8623. $out .= ' '.$val['n'].' 0 R';
  8624. }
  8625. }
  8626. // add radiobutton groups
  8627. if (isset($this->radiobutton_groups[$n])) {
  8628. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  8629. if (isset($data['n'])) {
  8630. $out .= ' '.$data['n'].' 0 R';
  8631. }
  8632. }
  8633. }
  8634. }
  8635. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  8636. // set reference for signature object
  8637. $out .= ' '.$this->sig_obj_id.' 0 R';
  8638. }
  8639. if (!empty($this->empty_signature_appearance)) {
  8640. foreach ($this->empty_signature_appearance as $esa) {
  8641. if ($esa['page'] == $n) {
  8642. // set reference for empty signature objects
  8643. $out .= ' '.$esa['objid'].' 0 R';
  8644. }
  8645. }
  8646. }
  8647. $out .= ' ]';
  8648. return $out;
  8649. }
  8650. /**
  8651. * Output annotations objects for all pages.
  8652. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  8653. * See section 12.5 of PDF 32000_2008 reference.
  8654. * @protected
  8655. * @author Nicola Asuni
  8656. * @since 4.0.018 (2008-08-06)
  8657. */
  8658. protected function _putannotsobjs() {
  8659. // reset object counter
  8660. for ($n=1; $n <= $this->numpages; ++$n) {
  8661. if (isset($this->PageAnnots[$n])) {
  8662. // set page annotations
  8663. foreach ($this->PageAnnots[$n] as $key => $pl) {
  8664. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  8665. // create annotation object for grouping radiobuttons
  8666. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  8667. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  8668. $annots = '<<';
  8669. $annots .= ' /Type /Annot';
  8670. $annots .= ' /Subtype /Widget';
  8671. $annots .= ' /Rect [0 0 0 0]';
  8672. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  8673. // read only
  8674. $annots .= ' /F 68';
  8675. $annots .= ' /Ff 49153';
  8676. } else {
  8677. $annots .= ' /F 4'; // default print for PDF/A
  8678. $annots .= ' /Ff 49152';
  8679. }
  8680. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  8681. $annots .= ' /FT /Btn';
  8682. $annots .= ' /Kids [';
  8683. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  8684. if (isset($data['kid'])) {
  8685. $annots .= ' '.$data['kid'].' 0 R';
  8686. if ($data['def'] !== 'Off') {
  8687. $defval = $data['def'];
  8688. }
  8689. }
  8690. }
  8691. $annots .= ' ]';
  8692. if (isset($defval)) {
  8693. $annots .= ' /V /'.$defval;
  8694. }
  8695. $annots .= ' >>';
  8696. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  8697. $this->form_obj_id[] = $radio_button_obj_id;
  8698. // store object id to be used on Parent entry of Kids
  8699. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  8700. }
  8701. $formfield = false;
  8702. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  8703. $a = $pl['x'] * $this->k;
  8704. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  8705. $c = $pl['w'] * $this->k;
  8706. $d = $pl['h'] * $this->k;
  8707. $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b+$d);
  8708. // create new annotation object
  8709. $annots = '<</Type /Annot';
  8710. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  8711. $annots .= ' /Rect ['.$rect.']';
  8712. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  8713. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  8714. $annots .= ' /FT /'.$pl['opt']['ft'];
  8715. $formfield = true;
  8716. }
  8717. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  8718. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  8719. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  8720. $annots .= ' /M '.$this->_datestring($annot_obj_id);
  8721. if (isset($pl['opt']['f'])) {
  8722. $fval = 0;
  8723. if (is_array($pl['opt']['f'])) {
  8724. foreach ($pl['opt']['f'] as $f) {
  8725. switch (strtolower($f)) {
  8726. case 'invisible': {
  8727. $fval += 1 << 0;
  8728. break;
  8729. }
  8730. case 'hidden': {
  8731. $fval += 1 << 1;
  8732. break;
  8733. }
  8734. case 'print': {
  8735. $fval += 1 << 2;
  8736. break;
  8737. }
  8738. case 'nozoom': {
  8739. $fval += 1 << 3;
  8740. break;
  8741. }
  8742. case 'norotate': {
  8743. $fval += 1 << 4;
  8744. break;
  8745. }
  8746. case 'noview': {
  8747. $fval += 1 << 5;
  8748. break;
  8749. }
  8750. case 'readonly': {
  8751. $fval += 1 << 6;
  8752. break;
  8753. }
  8754. case 'locked': {
  8755. $fval += 1 << 8;
  8756. break;
  8757. }
  8758. case 'togglenoview': {
  8759. $fval += 1 << 9;
  8760. break;
  8761. }
  8762. case 'lockedcontents': {
  8763. $fval += 1 << 10;
  8764. break;
  8765. }
  8766. default: {
  8767. break;
  8768. }
  8769. }
  8770. }
  8771. } else {
  8772. $fval = intval($pl['opt']['f']);
  8773. }
  8774. } else {
  8775. $fval = 4;
  8776. }
  8777. if ($this->pdfa_mode) {
  8778. // force print flag for PDF/A mode
  8779. $fval |= 4;
  8780. }
  8781. $annots .= ' /F '.intval($fval);
  8782. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  8783. $annots .= ' /AS /'.$pl['opt']['as'];
  8784. }
  8785. if (isset($pl['opt']['ap'])) {
  8786. // appearance stream
  8787. $annots .= ' /AP <<';
  8788. if (is_array($pl['opt']['ap'])) {
  8789. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  8790. // $apmode can be: n = normal; r = rollover; d = down;
  8791. $annots .= ' /'.strtoupper($apmode);
  8792. if (is_array($apdef)) {
  8793. $annots .= ' <<';
  8794. foreach ($apdef as $apstate => $stream) {
  8795. // reference to XObject that define the appearance for this mode-state
  8796. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  8797. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  8798. }
  8799. $annots .= ' >>';
  8800. } else {
  8801. // reference to XObject that define the appearance for this mode
  8802. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  8803. $annots .= ' '.$apsobjid.' 0 R';
  8804. }
  8805. }
  8806. } else {
  8807. $annots .= $pl['opt']['ap'];
  8808. }
  8809. $annots .= ' >>';
  8810. }
  8811. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  8812. $annots .= ' /BS <<';
  8813. $annots .= ' /Type /Border';
  8814. if (isset($pl['opt']['bs']['w'])) {
  8815. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  8816. }
  8817. $bstyles = array('S', 'D', 'B', 'I', 'U');
  8818. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  8819. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  8820. }
  8821. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  8822. $annots .= ' /D [';
  8823. foreach ($pl['opt']['bs']['d'] as $cord) {
  8824. $annots .= ' '.intval($cord);
  8825. }
  8826. $annots .= ']';
  8827. }
  8828. $annots .= ' >>';
  8829. } else {
  8830. $annots .= ' /Border [';
  8831. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  8832. $annots .= intval($pl['opt']['border'][0]).' ';
  8833. $annots .= intval($pl['opt']['border'][1]).' ';
  8834. $annots .= intval($pl['opt']['border'][2]);
  8835. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  8836. $annots .= ' [';
  8837. foreach ($pl['opt']['border'][3] as $dash) {
  8838. $annots .= intval($dash).' ';
  8839. }
  8840. $annots .= ']';
  8841. }
  8842. } else {
  8843. $annots .= '0 0 0';
  8844. }
  8845. $annots .= ']';
  8846. }
  8847. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  8848. $annots .= ' /BE <<';
  8849. $bstyles = array('S', 'C');
  8850. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
  8851. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  8852. } else {
  8853. $annots .= ' /S /S';
  8854. }
  8855. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  8856. $annots .= ' /I '.sprintf(' %.4F', $pl['opt']['be']['i']);
  8857. }
  8858. $annots .= '>>';
  8859. }
  8860. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  8861. $annots .= ' /C '.$this->getColorStringFromArray($pl['opt']['c']);
  8862. }
  8863. //$annots .= ' /StructParent ';
  8864. //$annots .= ' /OC ';
  8865. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  8866. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  8867. // this is a markup type
  8868. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  8869. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  8870. }
  8871. //$annots .= ' /Popup ';
  8872. if (isset($pl['opt']['ca'])) {
  8873. $annots .= ' /CA '.sprintf('%.4F', floatval($pl['opt']['ca']));
  8874. }
  8875. if (isset($pl['opt']['rc'])) {
  8876. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8877. }
  8878. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id);
  8879. //$annots .= ' /IRT ';
  8880. if (isset($pl['opt']['subj'])) {
  8881. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  8882. }
  8883. //$annots .= ' /RT ';
  8884. //$annots .= ' /IT ';
  8885. //$annots .= ' /ExData ';
  8886. }
  8887. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  8888. // Annotation types
  8889. switch (strtolower($pl['opt']['subtype'])) {
  8890. case 'text': {
  8891. if (isset($pl['opt']['open'])) {
  8892. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  8893. }
  8894. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  8895. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8896. $annots .= ' /Name /'.$pl['opt']['name'];
  8897. } else {
  8898. $annots .= ' /Name /Note';
  8899. }
  8900. $statemodels = array('Marked', 'Review');
  8901. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  8902. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  8903. } else {
  8904. $pl['opt']['statemodel'] = 'Marked';
  8905. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  8906. }
  8907. if ($pl['opt']['statemodel'] == 'Marked') {
  8908. $states = array('Accepted', 'Unmarked');
  8909. } else {
  8910. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  8911. }
  8912. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  8913. $annots .= ' /State /'.$pl['opt']['state'];
  8914. } else {
  8915. if ($pl['opt']['statemodel'] == 'Marked') {
  8916. $annots .= ' /State /Unmarked';
  8917. } else {
  8918. $annots .= ' /State /None';
  8919. }
  8920. }
  8921. break;
  8922. }
  8923. case 'link': {
  8924. if (is_string($pl['txt'])) {
  8925. // external URI link
  8926. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  8927. } else {
  8928. // internal link
  8929. $l = $this->links[$pl['txt']];
  8930. if (isset($this->page_obj_id[($l[0])])) {
  8931. $annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($l[0])], ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
  8932. }
  8933. }
  8934. $hmodes = array('N', 'I', 'O', 'P');
  8935. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  8936. $annots .= ' /H /'.$pl['opt']['h'];
  8937. } else {
  8938. $annots .= ' /H /I';
  8939. }
  8940. //$annots .= ' /PA ';
  8941. //$annots .= ' /Quadpoints ';
  8942. break;
  8943. }
  8944. case 'freetext': {
  8945. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8946. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8947. }
  8948. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8949. $annots .= ' /Q '.intval($pl['opt']['q']);
  8950. }
  8951. if (isset($pl['opt']['rc'])) {
  8952. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8953. }
  8954. if (isset($pl['opt']['ds'])) {
  8955. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  8956. }
  8957. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  8958. $annots .= ' /CL [';
  8959. foreach ($pl['opt']['cl'] as $cl) {
  8960. $annots .= sprintf('%.4F ', $cl * $this->k);
  8961. }
  8962. $annots .= ']';
  8963. }
  8964. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  8965. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  8966. $annots .= ' /IT /'.$pl['opt']['it'];
  8967. }
  8968. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  8969. $l = $pl['opt']['rd'][0] * $this->k;
  8970. $r = $pl['opt']['rd'][1] * $this->k;
  8971. $t = $pl['opt']['rd'][2] * $this->k;
  8972. $b = $pl['opt']['rd'][3] * $this->k;
  8973. $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
  8974. }
  8975. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  8976. $annots .= ' /LE /'.$pl['opt']['le'];
  8977. }
  8978. break;
  8979. }
  8980. case 'line': {
  8981. break;
  8982. }
  8983. case 'square': {
  8984. break;
  8985. }
  8986. case 'circle': {
  8987. break;
  8988. }
  8989. case 'polygon': {
  8990. break;
  8991. }
  8992. case 'polyline': {
  8993. break;
  8994. }
  8995. case 'highlight': {
  8996. break;
  8997. }
  8998. case 'underline': {
  8999. break;
  9000. }
  9001. case 'squiggly': {
  9002. break;
  9003. }
  9004. case 'strikeout': {
  9005. break;
  9006. }
  9007. case 'stamp': {
  9008. break;
  9009. }
  9010. case 'caret': {
  9011. break;
  9012. }
  9013. case 'ink': {
  9014. break;
  9015. }
  9016. case 'popup': {
  9017. break;
  9018. }
  9019. case 'fileattachment': {
  9020. if ($this->pdfa_mode) {
  9021. // embedded files are not allowed in PDF/A mode
  9022. break;
  9023. }
  9024. if (!isset($pl['opt']['fs'])) {
  9025. break;
  9026. }
  9027. $filename = basename($pl['opt']['fs']);
  9028. if (isset($this->embeddedfiles[$filename]['n'])) {
  9029. $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
  9030. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  9031. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  9032. $annots .= ' /Name /'.$pl['opt']['name'];
  9033. } else {
  9034. $annots .= ' /Name /PushPin';
  9035. }
  9036. }
  9037. break;
  9038. }
  9039. case 'sound': {
  9040. if (!isset($pl['opt']['fs'])) {
  9041. break;
  9042. }
  9043. $filename = basename($pl['opt']['fs']);
  9044. if (isset($this->embeddedfiles[$filename]['n'])) {
  9045. // ... TO BE COMPLETED ...
  9046. // /R /C /B /E /CO /CP
  9047. $annots .= ' /Sound <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
  9048. $iconsapp = array('Speaker', 'Mic');
  9049. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  9050. $annots .= ' /Name /'.$pl['opt']['name'];
  9051. } else {
  9052. $annots .= ' /Name /Speaker';
  9053. }
  9054. }
  9055. break;
  9056. }
  9057. case 'movie': {
  9058. break;
  9059. }
  9060. case 'widget': {
  9061. $hmode = array('N', 'I', 'O', 'P', 'T');
  9062. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  9063. $annots .= ' /H /'.$pl['opt']['h'];
  9064. }
  9065. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  9066. $annots .= ' /MK <<';
  9067. if (isset($pl['opt']['mk']['r'])) {
  9068. $annots .= ' /R '.$pl['opt']['mk']['r'];
  9069. }
  9070. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  9071. $annots .= ' /BC '.$this->getColorStringFromArray($pl['opt']['mk']['bc']);
  9072. }
  9073. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  9074. $annots .= ' /BG '.$this->getColorStringFromArray($pl['opt']['mk']['bg']);
  9075. }
  9076. if (isset($pl['opt']['mk']['ca'])) {
  9077. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  9078. }
  9079. if (isset($pl['opt']['mk']['rc'])) {
  9080. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  9081. }
  9082. if (isset($pl['opt']['mk']['ac'])) {
  9083. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  9084. }
  9085. if (isset($pl['opt']['mk']['i'])) {
  9086. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  9087. if ($info !== false) {
  9088. $annots .= ' /I '.$info['n'].' 0 R';
  9089. }
  9090. }
  9091. if (isset($pl['opt']['mk']['ri'])) {
  9092. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  9093. if ($info !== false) {
  9094. $annots .= ' /RI '.$info['n'].' 0 R';
  9095. }
  9096. }
  9097. if (isset($pl['opt']['mk']['ix'])) {
  9098. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  9099. if ($info !== false) {
  9100. $annots .= ' /IX '.$info['n'].' 0 R';
  9101. }
  9102. }
  9103. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  9104. $annots .= ' /IF <<';
  9105. $if_sw = array('A', 'B', 'S', 'N');
  9106. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  9107. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  9108. }
  9109. $if_s = array('A', 'P');
  9110. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  9111. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  9112. }
  9113. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  9114. $annots .= sprintf(' /A [%.2F %.2F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  9115. }
  9116. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  9117. $annots .= ' /FB true';
  9118. }
  9119. $annots .= '>>';
  9120. }
  9121. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  9122. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  9123. }
  9124. $annots .= '>>';
  9125. } // end MK
  9126. // --- Entries for field dictionaries ---
  9127. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  9128. // set parent
  9129. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  9130. }
  9131. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  9132. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  9133. }
  9134. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  9135. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  9136. }
  9137. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  9138. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  9139. }
  9140. if (isset($pl['opt']['ff'])) {
  9141. if (is_array($pl['opt']['ff'])) {
  9142. // array of bit settings
  9143. $flag = 0;
  9144. foreach($pl['opt']['ff'] as $val) {
  9145. $flag += 1 << ($val - 1);
  9146. }
  9147. } else {
  9148. $flag = intval($pl['opt']['ff']);
  9149. }
  9150. $annots .= ' /Ff '.$flag;
  9151. }
  9152. if (isset($pl['opt']['maxlen'])) {
  9153. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  9154. }
  9155. if (isset($pl['opt']['v'])) {
  9156. $annots .= ' /V';
  9157. if (is_array($pl['opt']['v'])) {
  9158. foreach ($pl['opt']['v'] AS $optval) {
  9159. if (is_float($optval)) {
  9160. $optval = sprintf('%.2F', $optval);
  9161. }
  9162. $annots .= ' '.$optval;
  9163. }
  9164. } else {
  9165. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  9166. }
  9167. }
  9168. if (isset($pl['opt']['dv'])) {
  9169. $annots .= ' /DV';
  9170. if (is_array($pl['opt']['dv'])) {
  9171. foreach ($pl['opt']['dv'] AS $optval) {
  9172. if (is_float($optval)) {
  9173. $optval = sprintf('%.2F', $optval);
  9174. }
  9175. $annots .= ' '.$optval;
  9176. }
  9177. } else {
  9178. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  9179. }
  9180. }
  9181. if (isset($pl['opt']['rv'])) {
  9182. $annots .= ' /RV';
  9183. if (is_array($pl['opt']['rv'])) {
  9184. foreach ($pl['opt']['rv'] AS $optval) {
  9185. if (is_float($optval)) {
  9186. $optval = sprintf('%.2F', $optval);
  9187. }
  9188. $annots .= ' '.$optval;
  9189. }
  9190. } else {
  9191. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  9192. }
  9193. }
  9194. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  9195. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  9196. }
  9197. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  9198. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  9199. }
  9200. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  9201. $annots .= ' /DA ('.$pl['opt']['da'].')';
  9202. }
  9203. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  9204. $annots .= ' /Q '.intval($pl['opt']['q']);
  9205. }
  9206. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  9207. $annots .= ' /Opt [';
  9208. foreach($pl['opt']['opt'] AS $copt) {
  9209. if (is_array($copt)) {
  9210. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  9211. } else {
  9212. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  9213. }
  9214. }
  9215. $annots .= ']';
  9216. }
  9217. if (isset($pl['opt']['ti'])) {
  9218. $annots .= ' /TI '.intval($pl['opt']['ti']);
  9219. }
  9220. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  9221. $annots .= ' /I [';
  9222. foreach($pl['opt']['i'] AS $copt) {
  9223. $annots .= intval($copt).' ';
  9224. }
  9225. $annots .= ']';
  9226. }
  9227. break;
  9228. }
  9229. case 'screen': {
  9230. break;
  9231. }
  9232. case 'printermark': {
  9233. break;
  9234. }
  9235. case 'trapnet': {
  9236. break;
  9237. }
  9238. case 'watermark': {
  9239. break;
  9240. }
  9241. case '3d': {
  9242. break;
  9243. }
  9244. default: {
  9245. break;
  9246. }
  9247. }
  9248. $annots .= '>>';
  9249. // create new annotation object
  9250. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  9251. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  9252. // store reference of form object
  9253. $this->form_obj_id[] = $annot_obj_id;
  9254. }
  9255. }
  9256. }
  9257. } // end for each page
  9258. }
  9259. /**
  9260. * Put appearance streams XObject used to define annotation's appearance states.
  9261. * @param $w (int) annotation width
  9262. * @param $h (int) annotation height
  9263. * @param $stream (string) appearance stream
  9264. * @return int object ID
  9265. * @protected
  9266. * @since 4.8.001 (2009-09-09)
  9267. */
  9268. protected function _putAPXObject($w=0, $h=0, $stream='') {
  9269. $stream = trim($stream);
  9270. $out = $this->_getobj()."\n";
  9271. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  9272. $out .= '<<';
  9273. $out .= ' /Type /XObject';
  9274. $out .= ' /Subtype /Form';
  9275. $out .= ' /FormType 1';
  9276. if ($this->compress) {
  9277. $stream = gzcompress($stream);
  9278. $out .= ' /Filter /FlateDecode';
  9279. }
  9280. $rect = sprintf('%.2F %.2F', $w, $h);
  9281. $out .= ' /BBox [0 0 '.$rect.']';
  9282. $out .= ' /Matrix [1 0 0 1 0 0]';
  9283. $out .= ' /Resources 2 0 R';
  9284. $stream = $this->_getrawstream($stream);
  9285. $out .= ' /Length '.strlen($stream);
  9286. $out .= ' >>';
  9287. $out .= ' stream'."\n".$stream."\n".'endstream';
  9288. $out .= "\n".'endobj';
  9289. $this->_out($out);
  9290. return $this->n;
  9291. }
  9292. /**
  9293. * Get ULONG from string (Big Endian 32-bit unsigned integer).
  9294. * @param $str (string) string from where to extract value
  9295. * @param $offset (int) point from where to read the data
  9296. * @return int 32 bit value
  9297. * @author Nicola Asuni
  9298. * @protected
  9299. * @since 5.2.000 (2010-06-02)
  9300. */
  9301. protected function _getULONG($str, $offset) {
  9302. $v = unpack('Ni', substr($str, $offset, 4));
  9303. return $v['i'];
  9304. }
  9305. /**
  9306. * Get USHORT from string (Big Endian 16-bit unsigned integer).
  9307. * @param $str (string) string from where to extract value
  9308. * @param $offset (int) point from where to read the data
  9309. * @return int 16 bit value
  9310. * @author Nicola Asuni
  9311. * @protected
  9312. * @since 5.2.000 (2010-06-02)
  9313. */
  9314. protected function _getUSHORT($str, $offset) {
  9315. $v = unpack('ni', substr($str, $offset, 2));
  9316. return $v['i'];
  9317. }
  9318. /**
  9319. * Get SHORT from string (Big Endian 16-bit signed integer).
  9320. * @param $str (string) string from where to extract value
  9321. * @param $offset (int) point from where to read the data
  9322. * @return int 16 bit value
  9323. * @author Nicola Asuni
  9324. * @protected
  9325. * @since 5.2.000 (2010-06-02)
  9326. */
  9327. protected function _getSHORT($str, $offset) {
  9328. $v = unpack('si', substr($str, $offset, 2));
  9329. return $v['i'];
  9330. }
  9331. /**
  9332. * Get FWORD from string (Big Endian 16-bit signed integer).
  9333. * @param $str (string) string from where to extract value
  9334. * @param $offset (int) point from where to read the data
  9335. * @return int 16 bit value
  9336. * @author Nicola Asuni
  9337. * @protected
  9338. * @since 5.9.123 (2011-09-30)
  9339. */
  9340. protected function _getFWORD($str, $offset) {
  9341. $v = $this->_getUSHORT($str, $offset);
  9342. if ($v > 0x7fff) {
  9343. $v -= 0x10000;
  9344. }
  9345. return $v;
  9346. }
  9347. /**
  9348. * Get UFWORD from string (Big Endian 16-bit unsigned integer).
  9349. * @param $str (string) string from where to extract value
  9350. * @param $offset (int) point from where to read the data
  9351. * @return int 16 bit value
  9352. * @author Nicola Asuni
  9353. * @protected
  9354. * @since 5.9.123 (2011-09-30)
  9355. */
  9356. protected function _getUFWORD($str, $offset) {
  9357. $v = $this->_getUSHORT($str, $offset);
  9358. return $v;
  9359. }
  9360. /**
  9361. * Get FIXED from string (32-bit signed fixed-point number (16.16).
  9362. * @param $str (string) string from where to extract value
  9363. * @param $offset (int) point from where to read the data
  9364. * @return int 16 bit value
  9365. * @author Nicola Asuni
  9366. * @protected
  9367. * @since 5.9.123 (2011-09-30)
  9368. */
  9369. protected function _getFIXED($str, $offset) {
  9370. // mantissa
  9371. $m = $this->_getFWORD($str, $offset);
  9372. // fraction
  9373. $f = $this->_getUSHORT($str, ($offset + 2));
  9374. $v = floatval(''.$m.'.'.$f.'');
  9375. return $v;
  9376. }
  9377. /**
  9378. * Get BYTE from string (8-bit unsigned integer).
  9379. * @param $str (string) String from where to extract value.
  9380. * @param $offset (int) Point from where to read the data.
  9381. * @return int 8 bit value
  9382. * @author Nicola Asuni
  9383. * @protected
  9384. * @since 5.2.000 (2010-06-02)
  9385. */
  9386. protected function _getBYTE($str, $offset) {
  9387. $v = unpack('Ci', substr($str, $offset, 1));
  9388. return $v['i'];
  9389. }
  9390. /**
  9391. * Update the CIDToGIDMap string with a new value.
  9392. * @param $map (string) CIDToGIDMap.
  9393. * @param $cid (int) CID value.
  9394. * @param $gid (int) GID value.
  9395. * @return (string) CIDToGIDMap.
  9396. * @author Nicola Asuni
  9397. * @protected
  9398. * @since 5.9.123 (2011-09-29)
  9399. */
  9400. protected function updateCIDtoGIDmap($map, $cid, $gid) {
  9401. if (($cid >= 0) AND ($cid <= 0xFFFF) AND ($gid >= 0)) {
  9402. if ($gid > 0xFFFF) {
  9403. $gid -= 0x10000;
  9404. }
  9405. $map[($cid * 2)] = chr($gid >> 8);
  9406. $map[(($cid * 2) + 1)] = chr($gid & 0xFF);
  9407. }
  9408. return $map;
  9409. }
  9410. /**
  9411. * Convert and add the selected TrueType or Type1 font to the fonts folder (that must be writeable).
  9412. * @param $fontfile (string) TrueType or Type1 font file (full path).
  9413. * @param $fonttype (string) Font type. Leave empty for autodetect mode. Valid values are: TrueTypeUnicode, TrueType, Type1, CID0JP = CID-0 Japanese, CID0KR = CID-0 Korean, CID0CS = CID-0 Chinese Simplified, CID0CT = CID-0 Chinese Traditional.
  9414. * @param $enc (string) Name of the encoding table to use. Leave empty for default mode. Omit this parameter for TrueType Unicode and symbolic fonts like Symbol or ZapfDingBats.
  9415. * @param $flags (int) Unsigned 32-bit integer containing flags specifying various characteristics of the font (PDF32000:2008 - 9.8.2 Font Descriptor Flags): +1 for fixed font; +4 for symbol or +32 for non-symbol; +64 for italic. Fixed and Italic mode are generally autodetected so you have to set it to 32 = non-symbolic font (default) or 4 = symbolic font.
  9416. * @param $outpath (string) Output path for generated font files (must be writeable by the web server). Leave empty for default font folder.
  9417. * @return (string) TCPDF font name.
  9418. * @author Nicola Asuni
  9419. * @public
  9420. * @since 5.9.123 (2010-09-30)
  9421. */
  9422. public function addTTFfont($fontfile, $fonttype='', $enc='', $flags=32, $outpath='') {
  9423. if (!file_exists($fontfile)) {
  9424. $this->Error('Could not find file: '.$fontfile.'');
  9425. }
  9426. // font metrics
  9427. $fmetric = array();
  9428. // build new font name for TCPDF compatibility
  9429. $font_path_parts = pathinfo($fontfile);
  9430. if (!isset($font_path_parts['filename'])) {
  9431. $font_path_parts['filename'] = substr($font_path_parts['basename'], 0, -(strlen($font_path_parts['extension']) + 1));
  9432. }
  9433. $font_name = strtolower($font_path_parts['filename']);
  9434. $font_name = preg_replace('/[^a-z0-9_]/', '', $font_name);
  9435. $search = array('bold', 'oblique', 'italic', 'regular');
  9436. $replace = array('b', 'i', 'i', '');
  9437. $font_name = str_replace($search, $replace, $font_name);
  9438. if (empty($font_name)) {
  9439. // set generic name
  9440. $font_name = 'tcpdffont';
  9441. }
  9442. // set output path
  9443. if (empty($outpath)) {
  9444. $outpath = $this->_getfontpath();
  9445. }
  9446. // check if this font already exist
  9447. if (file_exists($outpath.$font_name.'.php')) {
  9448. // this font already exist (delete it from fonts folder to rebuild it)
  9449. return $font_name;
  9450. }
  9451. $fmetric['file'] = $font_name.'.z';
  9452. $fmetric['ctg'] = $font_name.'.ctg.z';
  9453. // get font data
  9454. $font = file_get_contents($fontfile);
  9455. $fmetric['originalsize'] = strlen($font);
  9456. // autodetect font type
  9457. if (empty($fonttype)) {
  9458. if ($this->_getULONG($font, 0) == 0x10000) {
  9459. // True Type (Unicode or not)
  9460. $fonttype = 'TrueTypeUnicode';
  9461. } elseif (substr($font, 0, 4) == 'OTTO') {
  9462. // Open Type (Unicode or not)
  9463. $this->Error('Unsupported font format: OpenType with CFF data.');
  9464. } else {
  9465. // Type 1
  9466. $fonttype = 'Type1';
  9467. }
  9468. }
  9469. // set font type
  9470. switch ($fonttype) {
  9471. case 'CID0CT':
  9472. case 'CID0CS':
  9473. case 'CID0KR':
  9474. case 'CID0JP': {
  9475. $fmetric['type'] = 'cidfont0';
  9476. break;
  9477. }
  9478. case 'Type1': {
  9479. $fmetric['type'] = 'Type1';
  9480. if (empty($enc) AND (($flags & 4) == 0)) {
  9481. $enc = 'cp1252';
  9482. }
  9483. break;
  9484. }
  9485. case 'TrueType': {
  9486. $fmetric['type'] = 'TrueType';
  9487. break;
  9488. }
  9489. case 'TrueTypeUnicode':
  9490. default: {
  9491. $fmetric['type'] = 'TrueTypeUnicode';
  9492. break;
  9493. }
  9494. }
  9495. // set encoding maps (if any)
  9496. $fmetric['enc'] = preg_replace('/[^A-Za-z0-9_\-]/', '', $enc);
  9497. $fmetric['diff'] = '';
  9498. if (($fmetric['type'] == 'TrueType') OR ($fmetric['type'] == 'Type1')) {
  9499. if (!empty($enc) AND ($enc != 'cp1252') AND isset($this->encmaps->encmap[$enc])) {
  9500. // build differences from reference encoding
  9501. $enc_ref = $this->encmaps->encmap['cp1252'];
  9502. $enc_target = $this->encmaps->encmap[$enc];
  9503. $last = 0;
  9504. for ($i = 32; $i <= 255; ++$i) {
  9505. if ($enc_target != $enc_ref[$i]) {
  9506. if ($i != ($last + 1)) {
  9507. $fmetric['diff'] .= $i.' ';
  9508. }
  9509. $last = $i;
  9510. $fmetric['diff'] .= '/'.$enc_target[$i].' ';
  9511. }
  9512. }
  9513. }
  9514. }
  9515. // parse the font by type
  9516. if ($fmetric['type'] == 'Type1') {
  9517. // ---------- TYPE 1 ----------
  9518. // read first segment
  9519. $a = unpack('Cmarker/Ctype/Vsize', substr($font, 0, 6));
  9520. if ($a['marker'] != 128) {
  9521. $this->Error('Font file is not a valid binary Type1');
  9522. }
  9523. $fmetric['size1'] = $a['size'];
  9524. $data = substr($font, 6, $fmetric['size1']);
  9525. // read second segment
  9526. $a = unpack('Cmarker/Ctype/Vsize', substr($font, (6 + $fmetric['size1']), 6));
  9527. if ($a['marker'] != 128) {
  9528. $this->Error('Font file is not a valid binary Type1');
  9529. }
  9530. $fmetric['size2'] = $a['size'];
  9531. $encrypted = substr($font, (12 + $fmetric['size1']), $fmetric['size2']);
  9532. $data .= $encrypted;
  9533. // store compressed font
  9534. $fp = fopen($outpath.$fmetric['file'], 'wb');
  9535. fwrite($fp, gzcompress($data));
  9536. fclose($fp);
  9537. // get font info
  9538. $fmetric['Flags'] = $flags;
  9539. preg_match ('#/FullName[\s]*\(([^\)]*)#', $font, $matches);
  9540. $fmetric['name'] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $matches[1]);
  9541. preg_match('#/FontBBox[\s]*{([^}]*)#', $font, $matches);
  9542. $fmetric['bbox'] = trim($matches[1]);
  9543. $bv = explode(' ', $fmetric['bbox']);
  9544. $fmetric['Ascent'] = intval($bv[3]);
  9545. $fmetric['Descent'] = intval($bv[1]);
  9546. preg_match('#/ItalicAngle[\s]*([0-9\+\-]*)#', $font, $matches);
  9547. $fmetric['italicAngle'] = intval($matches[1]);
  9548. if ($fmetric['italicAngle'] != 0) {
  9549. $fmetric['Flags'] |= 64;
  9550. }
  9551. preg_match('#/UnderlinePosition[\s]*([0-9\+\-]*)#', $font, $matches);
  9552. $fmetric['underlinePosition'] = intval($matches[1]);
  9553. preg_match('#/UnderlineThickness[\s]*([0-9\+\-]*)#', $font, $matches);
  9554. $fmetric['underlineThickness'] = intval($matches[1]);
  9555. preg_match('#/isFixedPitch[\s]*([^\s]*)#', $font, $matches);
  9556. if ($matches[1] == 'true') {
  9557. $fmetric['Flags'] |= 1;
  9558. }
  9559. // get internal map
  9560. $imap = array();
  9561. if (preg_match_all('#dup[\s]([0-9]+)[\s]*/([^\s]*)[\s]put#sU', $font, $fmap, PREG_SET_ORDER) > 0) {
  9562. foreach ($fmap as $v) {
  9563. $imap[$v[2]] = $v[1];
  9564. }
  9565. }
  9566. // decrypt eexec encrypted part
  9567. $r = 55665; // eexec encryption constant
  9568. $c1 = 52845;
  9569. $c2 = 22719;
  9570. $elen = strlen($encrypted);
  9571. $eplain = '';
  9572. for ($i = 0; $i < $elen; ++$i) {
  9573. $chr = ord($encrypted[$i]);
  9574. $eplain .= chr($chr ^ ($r >> 8));
  9575. $r = ((($chr + $r) * $c1 + $c2) % 65536);
  9576. }
  9577. if (preg_match('#/ForceBold[\s]*([^\s]*)#', $eplain, $matches) > 0) {
  9578. if ($matches[1] == 'true') {
  9579. $fmetric['Flags'] |= 0x40000;
  9580. }
  9581. }
  9582. if (preg_match('#/StdVW[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  9583. $fmetric['StemV'] = intval($matches[1]);
  9584. } else {
  9585. $fmetric['StemV'] = 70;
  9586. }
  9587. if (preg_match('#/StdHW[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  9588. $fmetric['StemH'] = intval($matches[1]);
  9589. } else {
  9590. $fmetric['StemH'] = 30;
  9591. }
  9592. if (preg_match('#/BlueValues[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  9593. $bv = explode(' ', $matches[1]);
  9594. if (count($bv) >= 6) {
  9595. $v1 = intval($bv[2]);
  9596. $v2 = intval($bv[4]);
  9597. if ($v1 <= $v2) {
  9598. $fmetric['XHeight'] = $v1;
  9599. $fmetric['CapHeight'] = $v2;
  9600. } else {
  9601. $fmetric['XHeight'] = $v2;
  9602. $fmetric['CapHeight'] = $v1;
  9603. }
  9604. } else {
  9605. $fmetric['XHeight'] = 450;
  9606. $fmetric['CapHeight'] = 700;
  9607. }
  9608. } else {
  9609. $fmetric['XHeight'] = 450;
  9610. $fmetric['CapHeight'] = 700;
  9611. }
  9612. // get the number of random bytes at the beginning of charstrings
  9613. if (preg_match('#/lenIV[\s]*([0-9]*)#', $eplain, $matches) > 0) {
  9614. $lenIV = intval($matches[1]);
  9615. } else {
  9616. $lenIV = 4;
  9617. }
  9618. $fmetric['Leading'] = 0;
  9619. // get charstring data
  9620. $eplain = substr($eplain, (strpos($eplain, '/CharStrings') + 1));
  9621. preg_match_all('#/([A-Za-z0-9\.]*)[\s][0-9]+[\s]RD[\s](.*)[\s]ND#sU', $eplain, $matches, PREG_SET_ORDER);
  9622. if (!empty($enc) AND isset($this->encmaps->encmap[$enc])) {
  9623. $enc_map = $this->encmaps->encmap[$enc];
  9624. } else {
  9625. $enc_map = false;
  9626. }
  9627. $fmetric['cw'] = '';
  9628. $fmetric['MaxWidth'] = 0;
  9629. $cwidths = array();
  9630. foreach ($matches as $k => $v) {
  9631. $cid = 0;
  9632. if (isset($imap[$v[1]])) {
  9633. $cid = $imap[$v[1]];
  9634. } elseif ($enc_map !== false) {
  9635. $cid = array_search($v[1], $enc_map);
  9636. if ($cid === false) {
  9637. $cid = 0;
  9638. } elseif ($cid > 1000) {
  9639. $cid -= 1000;
  9640. }
  9641. }
  9642. // decrypt charstring encrypted part
  9643. $r = 4330; // charstring encryption constant
  9644. $c1 = 52845;
  9645. $c2 = 22719;
  9646. $cd = $v[2];
  9647. $clen = strlen($cd);
  9648. $ccom = array();
  9649. for ($i = 0; $i < $clen; ++$i) {
  9650. $chr = ord($cd[$i]);
  9651. $ccom[] = ($chr ^ ($r >> 8));
  9652. $r = ((($chr + $r) * $c1 + $c2) % 65536);
  9653. }
  9654. // decode numbers
  9655. $cdec = array();
  9656. $ck = 0;
  9657. $i = $lenIV;
  9658. while ($i < $clen) {
  9659. if ($ccom[$i] < 32) {
  9660. $cdec[$ck] = $ccom[$i];
  9661. if (($ck > 0) AND ($cdec[$ck] == 13)) {
  9662. // hsbw command: update width
  9663. $cwidths[$cid] = $cdec[($ck - 1)];
  9664. }
  9665. ++$i;
  9666. } elseif (($ccom[$i] >= 32) AND ($ccom[$i] <= 246)) {
  9667. $cdec[$ck] = ($ccom[$i] - 139);
  9668. ++$i;
  9669. } elseif (($ccom[$i] >= 247) AND ($ccom[$i] <= 250)) {
  9670. $cdec[$ck] = ((($ccom[$i] - 247) * 256) + $ccom[($i + 1)] + 108);
  9671. $i += 2;
  9672. } elseif (($ccom[$i] >= 251) AND ($ccom[$i] <= 254)) {
  9673. $cdec[$ck] = ((-($ccom[$i] - 251) * 256) - $ccom[($i + 1)] - 108);
  9674. $i += 2;
  9675. } elseif ($ccom[$i] == 255) {
  9676. $sval = chr($ccom[($i + 1)]).chr($ccom[($i + 2)]).chr($ccom[($i + 3)]).chr($ccom[($i + 4)]);
  9677. $vsval = unpack('li', $sval);
  9678. $cdec[$ck] = $vsval['i'];
  9679. $i += 5;
  9680. }
  9681. ++$ck;
  9682. }
  9683. } // end for each matches
  9684. $fmetric['MissingWidth'] = $cwidths[0];
  9685. $fmetric['MaxWidth'] = $fmetric['MissingWidth'];
  9686. $fmetric['AvgWidth'] = 0;
  9687. // set chars widths
  9688. for ($cid = 0; $cid <= 255; ++$cid) {
  9689. if (isset($cwidths[$cid])) {
  9690. if ($cwidths[$cid] > $fmetric['MaxWidth']) {
  9691. $fmetric['MaxWidth'] = $cwidths[$cid];
  9692. }
  9693. $fmetric['AvgWidth'] += $cwidths[$cid];
  9694. $fmetric['cw'] .= ','.$cid.'=>'.$cwidths[$cid];
  9695. } else {
  9696. $fmetric['cw'] .= ','.$cid.'=>'.$fmetric['MissingWidth'];
  9697. }
  9698. }
  9699. $fmetric['AvgWidth'] = round($fmetric['AvgWidth'] / count($cwidths));
  9700. } else {
  9701. // ---------- TRUE TYPE ----------
  9702. if ($fmetric['type'] != 'cidfont0') {
  9703. // store compressed font
  9704. $fp = fopen($outpath.$fmetric['file'], 'wb');
  9705. fwrite($fp, gzcompress($font));
  9706. fclose($fp);
  9707. }
  9708. $offset = 0; // offset position of the font data
  9709. if ($this->_getULONG($font, $offset) != 0x10000) {
  9710. // sfnt version must be 0x00010000 for TrueType version 1.0.
  9711. return $font;
  9712. }
  9713. $offset += 4;
  9714. // get number of tables
  9715. $numTables = $this->_getUSHORT($font, $offset);
  9716. $offset += 2;
  9717. // skip searchRange, entrySelector and rangeShift
  9718. $offset += 6;
  9719. // tables array
  9720. $table = array();
  9721. // ---------- get tables ----------
  9722. for ($i = 0; $i < $numTables; ++$i) {
  9723. // get table info
  9724. $tag = substr($font, $offset, 4);
  9725. $offset += 4;
  9726. $table[$tag] = array();
  9727. $table[$tag]['checkSum'] = $this->_getULONG($font, $offset);
  9728. $offset += 4;
  9729. $table[$tag]['offset'] = $this->_getULONG($font, $offset);
  9730. $offset += 4;
  9731. $table[$tag]['length'] = $this->_getULONG($font, $offset);
  9732. $offset += 4;
  9733. }
  9734. // check magicNumber
  9735. $offset = $table['head']['offset'] + 12;
  9736. if ($this->_getULONG($font, $offset) != 0x5F0F3CF5) {
  9737. // magicNumber must be 0x5F0F3CF5
  9738. return $font;
  9739. }
  9740. $offset += 4;
  9741. $offset += 2; // skip flags
  9742. // get FUnits
  9743. $fmetric['unitsPerEm'] = $this->_getUSHORT($font, $offset);
  9744. $offset += 2;
  9745. // units ratio constant
  9746. $urk = (1000 / $fmetric['unitsPerEm']);
  9747. $offset += 16; // skip created, modified
  9748. $xMin = round($this->_getFWORD($font, $offset) * $urk);
  9749. $offset += 2;
  9750. $yMin = round($this->_getFWORD($font, $offset) * $urk);
  9751. $offset += 2;
  9752. $xMax = round($this->_getFWORD($font, $offset) * $urk);
  9753. $offset += 2;
  9754. $yMax = round($this->_getFWORD($font, $offset) * $urk);
  9755. $offset += 2;
  9756. $fmetric['bbox'] = ''.$xMin.' '.$yMin.' '.$xMax.' '.$yMax.'';
  9757. $macStyle = $this->_getUSHORT($font, $offset);
  9758. $offset += 2;
  9759. // PDF font flags
  9760. $fmetric['Flags'] = $flags;
  9761. if (($macStyle & 2) == 2) {
  9762. // italic flag
  9763. $fmetric['Flags'] |= 64;
  9764. }
  9765. // get offset mode (indexToLocFormat : 0 = short, 1 = long)
  9766. $offset = $table['head']['offset'] + 50;
  9767. $short_offset = ($this->_getSHORT($font, $offset) == 0);
  9768. $offset += 2;
  9769. // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
  9770. $indexToLoc = array();
  9771. $offset = $table['loca']['offset'];
  9772. if ($short_offset) {
  9773. // short version
  9774. $tot_num_glyphs = ($table['loca']['length'] / 2); // numGlyphs + 1
  9775. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  9776. $indexToLoc[$i] = $this->_getUSHORT($font, $offset) * 2;
  9777. $offset += 2;
  9778. }
  9779. } else {
  9780. // long version
  9781. $tot_num_glyphs = ($table['loca']['length'] / 4); // numGlyphs + 1
  9782. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  9783. $indexToLoc[$i] = $this->_getULONG($font, $offset);
  9784. $offset += 4;
  9785. }
  9786. }
  9787. // get glyphs indexes of chars from cmap table
  9788. $offset = $table['cmap']['offset'] + 2;
  9789. $numEncodingTables = $this->_getUSHORT($font, $offset);
  9790. $offset += 2;
  9791. $encodingTables = array();
  9792. for ($i = 0; $i < $numEncodingTables; ++$i) {
  9793. $encodingTables[$i]['platformID'] = $this->_getUSHORT($font, $offset);
  9794. $offset += 2;
  9795. $encodingTables[$i]['encodingID'] = $this->_getUSHORT($font, $offset);
  9796. $offset += 2;
  9797. $encodingTables[$i]['offset'] = $this->_getULONG($font, $offset);
  9798. $offset += 4;
  9799. }
  9800. // ---------- get os/2 metrics ----------
  9801. $offset = $table['OS/2']['offset'];
  9802. $offset += 2; // skip version
  9803. // xAvgCharWidth
  9804. $fmetric['AvgWidth'] = round($this->_getFWORD($font, $offset) * $urk);
  9805. $offset += 2;
  9806. // usWeightClass
  9807. $usWeightClass = round($this->_getUFWORD($font, $offset) * $urk);
  9808. // estimate StemV and StemH (400 = usWeightClass for Normal - Regular font)
  9809. $fmetric['StemV'] = round((70 * $usWeightClass) / 400);
  9810. $fmetric['StemH'] = round((30 * $usWeightClass) / 400);
  9811. $offset += 2;
  9812. $offset += 2; // usWidthClass
  9813. $fsType = $this->_getSHORT($font, $offset);
  9814. $offset += 2;
  9815. if ($fsType == 2) {
  9816. $this->Error('This Font cannot be modified, embedded or exchanged in any manner without first obtaining permission of the legal owner.');
  9817. }
  9818. // ---------- get font name ----------
  9819. $fmetric['name'] = '';
  9820. $offset = $table['name']['offset'];
  9821. $offset += 2; // skip Format selector (=0).
  9822. // Number of NameRecords that follow n.
  9823. $numNameRecords = $this->_getUSHORT($font, $offset);
  9824. $offset += 2;
  9825. // Offset to start of string storage (from start of table).
  9826. $stringStorageOffset = $this->_getUSHORT($font, $offset);
  9827. $offset += 2;
  9828. for ($i = 0; $i < $numNameRecords; ++$i) {
  9829. $offset += 6; // skip Platform ID, Platform-specific encoding ID, Language ID.
  9830. // Name ID.
  9831. $nameID = $this->_getUSHORT($font, $offset);
  9832. $offset += 2;
  9833. if ($nameID == 6) {
  9834. // String length (in bytes).
  9835. $stringLength = $this->_getUSHORT($font, $offset);
  9836. $offset += 2;
  9837. // String offset from start of storage area (in bytes).
  9838. $stringOffset = $this->_getUSHORT($font, $offset);
  9839. $offset += 2;
  9840. $offset = ($table['name']['offset'] + $stringStorageOffset + $stringOffset);
  9841. $fmetric['name'] = substr($font, $offset, $stringLength);
  9842. $fmetric['name'] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $fmetric['name']);
  9843. break;
  9844. } else {
  9845. $offset += 4; // skip String length, String offset
  9846. }
  9847. }
  9848. if (empty($fmetric['name'])) {
  9849. $fmetric['name'] = $font_name;
  9850. }
  9851. // ---------- get post data ----------
  9852. $offset = $table['post']['offset'];
  9853. $offset += 4; // skip Format Type
  9854. $fmetric['italicAngle'] = $this->_getFIXED($font, $offset);
  9855. $offset += 4;
  9856. $fmetric['underlinePosition'] = round($this->_getFWORD($font, $offset) * $urk);
  9857. $offset += 2;
  9858. $fmetric['underlineThickness'] = round($this->_getFWORD($font, $offset) * $urk);
  9859. $offset += 2;
  9860. $isFixedPitch = ($this->_getULONG($font, $offset) == 0) ? false : true;
  9861. $offset += 2;
  9862. if ($isFixedPitch) {
  9863. $fmetric['Flags'] |= 1;
  9864. }
  9865. // ---------- get hhea data ----------
  9866. $offset = $table['hhea']['offset'];
  9867. $offset += 4; // skip Table version number
  9868. // Ascender
  9869. $fmetric['Ascent'] = round($this->_getFWORD($font, $offset) * $urk);
  9870. $offset += 2;
  9871. // Descender
  9872. $fmetric['Descent'] = round($this->_getFWORD($font, $offset) * $urk);
  9873. $offset += 2;
  9874. // LineGap
  9875. $fmetric['Leading'] = round($this->_getFWORD($font, $offset) * $urk);
  9876. $offset += 2;
  9877. // advanceWidthMax
  9878. $fmetric['MaxWidth'] = round($this->_getUFWORD($font, $offset) * $urk);
  9879. $offset += 2;
  9880. $offset += 22; // skip some values
  9881. // get the number of hMetric entries in hmtx table
  9882. $numberOfHMetrics = $this->_getUSHORT($font, $offset);
  9883. // ---------- get maxp data ----------
  9884. $offset = $table['maxp']['offset'];
  9885. $offset += 4; // skip Table version number
  9886. // get the the number of glyphs in the font.
  9887. $numGlyphs = $this->_getUSHORT($font, $offset);
  9888. // ---------- get CIDToGIDMap ----------
  9889. $ctg = array();
  9890. foreach ($encodingTables as $enctable) {
  9891. if (($enctable['platformID'] == 3) AND ($enctable['encodingID'] == 0)) {
  9892. $modesymbol = true;
  9893. } else {
  9894. $modesymbol = false;
  9895. }
  9896. $offset = $table['cmap']['offset'] + $enctable['offset'];
  9897. $format = $this->_getUSHORT($font, $offset);
  9898. $offset += 2;
  9899. switch ($format) {
  9900. case 0: { // Format 0: Byte encoding table
  9901. $offset += 4; // skip length and version/language
  9902. for ($c = 0; $c < 256; ++$c) {
  9903. $g = $this->_getBYTE($font, $offset);
  9904. $ctg[$c] = $g;
  9905. ++$offset;
  9906. }
  9907. break;
  9908. }
  9909. case 2: { // Format 2: High-byte mapping through table
  9910. $offset += 4; // skip length and version/language
  9911. $numSubHeaders = 0;
  9912. for ($i = 0; $i < 256; ++$i) {
  9913. // Array that maps high bytes to subHeaders: value is subHeader index * 8.
  9914. $subHeaderKeys[$i] = ($this->_getUSHORT($font, $offset) / 8);
  9915. $offset += 2;
  9916. if ($numSubHeaders < $subHeaderKeys[$i]) {
  9917. $numSubHeaders = $subHeaderKeys[$i];
  9918. }
  9919. }
  9920. // the number of subHeaders is equal to the max of subHeaderKeys + 1
  9921. ++$numSubHeaders;
  9922. // read subHeader structures
  9923. $subHeaders = array();
  9924. $numGlyphIndexArray = 0;
  9925. for ($k = 0; $k < $numSubHeaders; ++$k) {
  9926. $subHeaders[$k]['firstCode'] = $this->_getUSHORT($font, $offset);
  9927. $offset += 2;
  9928. $subHeaders[$k]['entryCount'] = $this->_getUSHORT($font, $offset);
  9929. $offset += 2;
  9930. $subHeaders[$k]['idDelta'] = $this->_getSHORT($font, $offset);
  9931. $offset += 2;
  9932. $subHeaders[$k]['idRangeOffset'] = $this->_getUSHORT($font, $offset);
  9933. $offset += 2;
  9934. $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
  9935. $subHeaders[$k]['idRangeOffset'] /= 2;
  9936. $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
  9937. }
  9938. for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
  9939. $glyphIndexArray[$k] = $this->_getUSHORT($font, $offset);
  9940. $offset += 2;
  9941. }
  9942. for ($i = 0; $i < 256; ++$i) {
  9943. $k = $subHeaderKeys[$i];
  9944. if ($k == 0) {
  9945. // one byte code
  9946. $c = $i;
  9947. $g = $glyphIndexArray[0];
  9948. $ctg[$c] = $g;
  9949. } else {
  9950. // two bytes code
  9951. $start_byte = $subHeaders[$k]['firstCode'];
  9952. $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
  9953. for ($j = $start_byte; $j < $end_byte; ++$j) {
  9954. // combine high and low bytes
  9955. $c = (($i << 8) + $j);
  9956. $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
  9957. $g = $glyphIndexArray[$idRangeOffset];
  9958. $g += ($idDelta[$k] - 65536);
  9959. if ($g < 0) {
  9960. $g = 0;
  9961. }
  9962. $ctg[$c] = $g;
  9963. }
  9964. }
  9965. }
  9966. break;
  9967. }
  9968. case 4: { // Format 4: Segment mapping to delta values
  9969. $length = $this->_getUSHORT($font, $offset);
  9970. $offset += 2;
  9971. $offset += 2; // skip version/language
  9972. $segCount = ($this->_getUSHORT($font, $offset) / 2);
  9973. $offset += 2;
  9974. $offset += 6; // skip searchRange, entrySelector, rangeShift
  9975. $endCount = array(); // array of end character codes for each segment
  9976. for ($k = 0; $k < $segCount; ++$k) {
  9977. $endCount[$k] = $this->_getUSHORT($font, $offset);
  9978. $offset += 2;
  9979. }
  9980. $offset += 2; // skip reservedPad
  9981. $startCount = array(); // array of start character codes for each segment
  9982. for ($k = 0; $k < $segCount; ++$k) {
  9983. $startCount[$k] = $this->_getUSHORT($font, $offset);
  9984. $offset += 2;
  9985. }
  9986. $idDelta = array(); // delta for all character codes in segment
  9987. for ($k = 0; $k < $segCount; ++$k) {
  9988. $idDelta[$k] = $this->_getUSHORT($font, $offset);
  9989. $offset += 2;
  9990. }
  9991. $idRangeOffset = array(); // Offsets into glyphIdArray or 0
  9992. for ($k = 0; $k < $segCount; ++$k) {
  9993. $idRangeOffset[$k] = $this->_getUSHORT($font, $offset);
  9994. $offset += 2;
  9995. }
  9996. $gidlen = ($length / 2) - 8 - (4 * $segCount);
  9997. $glyphIdArray = array(); // glyph index array
  9998. for ($k = 0; $k < $gidlen; ++$k) {
  9999. $glyphIdArray[$k] = $this->_getUSHORT($font, $offset);
  10000. $offset += 2;
  10001. }
  10002. for ($k = 0; $k < $segCount; ++$k) {
  10003. for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
  10004. if ($idRangeOffset[$k] == 0) {
  10005. $g = $c;
  10006. } else {
  10007. $gid = (($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
  10008. $g = $glyphIdArray[$gid];
  10009. }
  10010. $g += ($idDelta[$k] - 65536);
  10011. if ($g < 0) {
  10012. $g = 0;
  10013. }
  10014. $ctg[$c] = $g;
  10015. }
  10016. }
  10017. break;
  10018. }
  10019. case 6: { // Format 6: Trimmed table mapping
  10020. $offset += 4; // skip length and version/language
  10021. $firstCode = $this->_getUSHORT($font, $offset);
  10022. $offset += 2;
  10023. $entryCount = $this->_getUSHORT($font, $offset);
  10024. $offset += 2;
  10025. for ($k = 0; $k < $entryCount; ++$k) {
  10026. $c = ($k + $firstCode);
  10027. $g = $this->_getUSHORT($font, $offset);
  10028. $ctg[$c] = $g;
  10029. $offset += 2;
  10030. }
  10031. break;
  10032. }
  10033. case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
  10034. $offset += 10; // skip reserved, length and version/language
  10035. for ($k = 0; $k < 8192; ++$k) {
  10036. $is32[$k] = $this->_getBYTE($font, $offset);
  10037. ++$offset;
  10038. }
  10039. $nGroups = $this->_getULONG($font, $offset);
  10040. $offset += 4;
  10041. for ($i = 0; $i < $nGroups; ++$i) {
  10042. $startCharCode = $this->_getULONG($font, $offset);
  10043. $offset += 4;
  10044. $endCharCode = $this->_getULONG($font, $offset);
  10045. $offset += 4;
  10046. $startGlyphID = $this->_getULONG($font, $offset);
  10047. $offset += 4;
  10048. for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
  10049. $is32idx = floor($c / 8);
  10050. if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
  10051. $c = $k;
  10052. } else {
  10053. // 32 bit format
  10054. // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
  10055. //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
  10056. //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
  10057. $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
  10058. }
  10059. $ctg[$c] = $g;
  10060. ++$startGlyphID;
  10061. }
  10062. }
  10063. break;
  10064. }
  10065. case 10: { // Format 10: Trimmed array
  10066. $offset += 10; // skip reserved, length and version/language
  10067. $startCharCode = $this->_getULONG($font, $offset);
  10068. $offset += 4;
  10069. $numChars = $this->_getULONG($font, $offset);
  10070. $offset += 4;
  10071. for ($k = 0; $k < $numChars; ++$k) {
  10072. $c = ($k + $startCharCode);
  10073. $g = $this->_getUSHORT($font, $offset);
  10074. $ctg[$c] = $g;
  10075. $offset += 2;
  10076. }
  10077. break;
  10078. }
  10079. case 12: { // Format 12: Segmented coverage
  10080. $offset += 10; // skip length and version/language
  10081. $nGroups = $this->_getULONG($font, $offset);
  10082. $offset += 4;
  10083. for ($k = 0; $k < $nGroups; ++$k) {
  10084. $startCharCode = $this->_getULONG($font, $offset);
  10085. $offset += 4;
  10086. $endCharCode = $this->_getULONG($font, $offset);
  10087. $offset += 4;
  10088. $startGlyphCode = $this->_getULONG($font, $offset);
  10089. $offset += 4;
  10090. for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
  10091. $ctg[$c] = $startGlyphCode;
  10092. ++$startGlyphCode;
  10093. }
  10094. }
  10095. break;
  10096. }
  10097. case 13: { // Format 13: Many-to-one range mappings
  10098. // to be implemented ...
  10099. break;
  10100. }
  10101. case 14: { // Format 14: Unicode Variation Sequences
  10102. // to be implemented ...
  10103. break;
  10104. }
  10105. }
  10106. }
  10107. if (!isset($ctg[0])) {
  10108. $ctg[0] = 0;
  10109. }
  10110. // get xHeight (height of x)
  10111. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[120]] + 4);
  10112. $yMin = $this->_getFWORD($font, $offset);
  10113. $offset += 4;
  10114. $yMax = $this->_getFWORD($font, $offset);
  10115. $offset += 2;
  10116. $fmetric['XHeight'] = round(($yMax - $yMin) * $urk);
  10117. // get CapHeight (height of H)
  10118. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[72]] + 4);
  10119. $yMin = $this->_getFWORD($font, $offset);
  10120. $offset += 4;
  10121. $yMax = $this->_getFWORD($font, $offset);
  10122. $offset += 2;
  10123. $fmetric['CapHeight'] = round(($yMax - $yMin) * $urk);
  10124. // ceate widths array
  10125. $cw = array();
  10126. $offset = $table['hmtx']['offset'];
  10127. for ($i = 0 ; $i < $numberOfHMetrics; ++$i) {
  10128. $cw[$i] = round($this->_getUFWORD($font, $offset) * $urk);
  10129. $offset += 4; // skip lsb
  10130. }
  10131. if ($numberOfHMetrics < $numGlyphs) {
  10132. // fill missing widths with the last value
  10133. $cw = array_pad($cw, $numGlyphs, $cw[($numberOfHMetrics - 1)]);
  10134. }
  10135. $fmetric['MissingWidth'] = $cw[0];
  10136. $fmetric['cw'] = '';
  10137. for ($cid = 0; $cid <= 65535; ++$cid) {
  10138. if (isset($ctg[$cid]) AND isset($cw[$ctg[$cid]])) {
  10139. $fmetric['cw'] .= ','.$cid.'=>'.$cw[$ctg[$cid]];
  10140. }
  10141. }
  10142. } // end of true type
  10143. if (($fmetric['type'] == 'TrueTypeUnicode') AND (count($ctg) == 256)) {
  10144. $fmetric['type'] == 'TrueType';
  10145. }
  10146. // ---------- create php font file ----------
  10147. $pfile = '<'.'?'.'php'."\n";
  10148. $pfile .= '// TCPDF FONT FILE DESCRIPTION'."\n";
  10149. $pfile .= '$type=\''.$fmetric['type'].'\';'."\n";
  10150. $pfile .= '$name=\''.$fmetric['name'].'\';'."\n";
  10151. $pfile .= '$up='.$fmetric['underlinePosition'].';'."\n";
  10152. $pfile .= '$ut='.$fmetric['underlineThickness'].';'."\n";
  10153. if ($fmetric['MissingWidth'] > 0) {
  10154. $pfile .= '$dw='.$fmetric['MissingWidth'].';'."\n";
  10155. } else {
  10156. $pfile .= '$dw='.$fmetric['AvgWidth'].';'."\n";
  10157. }
  10158. $pfile .= '$diff=\''.$fmetric['diff'].'\';'."\n";
  10159. if ($fmetric['type'] == 'Type1') {
  10160. // Type 1
  10161. $pfile .= '$enc=\''.$fmetric['enc'].'\';'."\n";
  10162. $pfile .= '$file=\''.$fmetric['file'].'\';'."\n";
  10163. $pfile .= '$size1='.$fmetric['size1'].';'."\n";
  10164. $pfile .= '$size2='.$fmetric['size2'].';'."\n";
  10165. } else {
  10166. $pfile .= '$originalsize='.$fmetric['originalsize'].';'."\n";
  10167. if ($fmetric['type'] == 'cidfont0') {
  10168. // CID-0
  10169. switch ($fonttype) {
  10170. case 'CID0JP': {
  10171. $pfile .= '// Japanese'."\n";
  10172. $pfile .= '$enc=\'UniJIS-UTF16-H\';'."\n";
  10173. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'Japan1\',\'Supplement\'=>5);'."\n";
  10174. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_aj16.php\');'."\n";
  10175. break;
  10176. }
  10177. case 'CID0KR': {
  10178. $pfile .= '// Korean'."\n";
  10179. $pfile .= '$enc=\'UniKS-UTF16-H\';'."\n";
  10180. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'Korea1\',\'Supplement\'=>0);'."\n";
  10181. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_ak12.php\');'."\n";
  10182. break;
  10183. }
  10184. case 'CID0CS': {
  10185. $pfile .= '// Chinese Simplified'."\n";
  10186. $pfile .= '$enc=\'UniGB-UTF16-H\';'."\n";
  10187. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'GB1\',\'Supplement\'=>2);'."\n";
  10188. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_ag15.php\');'."\n";
  10189. break;
  10190. }
  10191. case 'CID0CT':
  10192. default: {
  10193. $pfile .= '// Chinese Traditional'."\n";
  10194. $pfile .= '$enc=\'UniCNS-UTF16-H\';'."\n";
  10195. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'CNS1\',\'Supplement\'=>0);'."\n";
  10196. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_aj16.php\');'."\n";
  10197. break;
  10198. }
  10199. }
  10200. } else {
  10201. // TrueType
  10202. $pfile .= '$enc=\''.$fmetric['enc'].'\';'."\n";
  10203. $pfile .= '$file=\''.$fmetric['file'].'\';'."\n";
  10204. $pfile .= '$ctg=\''.$fmetric['ctg'].'\';'."\n";
  10205. // create CIDToGIDMap
  10206. $cidtogidmap = str_pad('', 131072, "\x00"); // (256 * 256 * 2) = 131072
  10207. foreach ($ctg as $cid => $gid) {
  10208. $cidtogidmap = $this->updateCIDtoGIDmap($cidtogidmap, $cid, $ctg[$cid]);
  10209. }
  10210. // store compressed CIDToGIDMap
  10211. $fp = fopen($outpath.$fmetric['ctg'], 'wb');
  10212. fwrite($fp, gzcompress($cidtogidmap));
  10213. fclose($fp);
  10214. }
  10215. }
  10216. $pfile .= '$desc=array(';
  10217. $pfile .= '\'Flags\'=>'.$fmetric['Flags'].',';
  10218. $pfile .= '\'FontBBox\'=>\'['.$fmetric['bbox'].']\',';
  10219. $pfile .= '\'ItalicAngle\'=>'.$fmetric['italicAngle'].',';
  10220. $pfile .= '\'Ascent\'=>'.$fmetric['Ascent'].',';
  10221. $pfile .= '\'Descent\'=>'.$fmetric['Descent'].',';
  10222. $pfile .= '\'Leading\'=>'.$fmetric['Leading'].',';
  10223. $pfile .= '\'CapHeight\'=>'.$fmetric['CapHeight'].',';
  10224. $pfile .= '\'XHeight\'=>'.$fmetric['XHeight'].',';
  10225. $pfile .= '\'StemV\'=>'.$fmetric['StemV'].',';
  10226. $pfile .= '\'StemH\'=>'.$fmetric['StemH'].',';
  10227. $pfile .= '\'AvgWidth\'=>'.$fmetric['AvgWidth'].',';
  10228. $pfile .= '\'MaxWidth\'=>'.$fmetric['MaxWidth'].',';
  10229. $pfile .= '\'MissingWidth\'=>'.$fmetric['MissingWidth'].'';
  10230. $pfile .= ');'."\n";
  10231. $pfile .= '$cw=array('.substr($fmetric['cw'], 1).');'."\n";
  10232. $pfile .= '// --- EOF ---'."\n";
  10233. // store file
  10234. $fp = fopen($outpath.$font_name.'.php', 'w');
  10235. fwrite($fp, $pfile);
  10236. fclose($fp);
  10237. // return TCPDF font name
  10238. return $font_name;
  10239. }
  10240. /**
  10241. * Returns a subset of the TrueType font data without the unused glyphs.
  10242. * @param $font (string) TrueType font data.
  10243. * @param $subsetchars (array) Array of used characters (the glyphs to keep).
  10244. * @return (string) A subset of TrueType font data without the unused glyphs.
  10245. * @author Nicola Asuni
  10246. * @protected
  10247. * @since 5.2.000 (2010-06-02)
  10248. */
  10249. protected function _getTrueTypeFontSubset($font, $subsetchars) {
  10250. ksort($subsetchars);
  10251. $offset = 0; // offset position of the font data
  10252. if ($this->_getULONG($font, $offset) != 0x10000) {
  10253. // sfnt version must be 0x00010000 for TrueType version 1.0.
  10254. return $font;
  10255. }
  10256. $offset += 4;
  10257. // get number of tables
  10258. $numTables = $this->_getUSHORT($font, $offset);
  10259. $offset += 2;
  10260. // skip searchRange, entrySelector and rangeShift
  10261. $offset += 6;
  10262. // tables array
  10263. $table = array();
  10264. // for each table
  10265. for ($i = 0; $i < $numTables; ++$i) {
  10266. // get table info
  10267. $tag = substr($font, $offset, 4);
  10268. $offset += 4;
  10269. $table[$tag] = array();
  10270. $table[$tag]['checkSum'] = $this->_getULONG($font, $offset);
  10271. $offset += 4;
  10272. $table[$tag]['offset'] = $this->_getULONG($font, $offset);
  10273. $offset += 4;
  10274. $table[$tag]['length'] = $this->_getULONG($font, $offset);
  10275. $offset += 4;
  10276. }
  10277. // check magicNumber
  10278. $offset = $table['head']['offset'] + 12;
  10279. if ($this->_getULONG($font, $offset) != 0x5F0F3CF5) {
  10280. // magicNumber must be 0x5F0F3CF5
  10281. return $font;
  10282. }
  10283. $offset += 4;
  10284. // get offset mode (indexToLocFormat : 0 = short, 1 = long)
  10285. $offset = $table['head']['offset'] + 50;
  10286. $short_offset = ($this->_getSHORT($font, $offset) == 0);
  10287. $offset += 2;
  10288. // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
  10289. $indexToLoc = array();
  10290. $offset = $table['loca']['offset'];
  10291. if ($short_offset) {
  10292. // short version
  10293. $tot_num_glyphs = ($table['loca']['length'] / 2); // numGlyphs + 1
  10294. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10295. $indexToLoc[$i] = $this->_getUSHORT($font, $offset) * 2;
  10296. $offset += 2;
  10297. }
  10298. } else {
  10299. // long version
  10300. $tot_num_glyphs = ($table['loca']['length'] / 4); // numGlyphs + 1
  10301. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10302. $indexToLoc[$i] = $this->_getULONG($font, $offset);
  10303. $offset += 4;
  10304. }
  10305. }
  10306. // get glyphs indexes of chars from cmap table
  10307. $subsetglyphs = array(); // glyph IDs on key
  10308. $subsetglyphs[0] = true; // character codes that do not correspond to any glyph in the font should be mapped to glyph index 0
  10309. $offset = $table['cmap']['offset'] + 2;
  10310. $numEncodingTables = $this->_getUSHORT($font, $offset);
  10311. $offset += 2;
  10312. $encodingTables = array();
  10313. for ($i = 0; $i < $numEncodingTables; ++$i) {
  10314. $encodingTables[$i]['platformID'] = $this->_getUSHORT($font, $offset);
  10315. $offset += 2;
  10316. $encodingTables[$i]['encodingID'] = $this->_getUSHORT($font, $offset);
  10317. $offset += 2;
  10318. $encodingTables[$i]['offset'] = $this->_getULONG($font, $offset);
  10319. $offset += 4;
  10320. }
  10321. foreach ($encodingTables as $enctable) {
  10322. if (($enctable['platformID'] == 3) AND ($enctable['encodingID'] == 0)) {
  10323. $modesymbol = true;
  10324. } else {
  10325. $modesymbol = false;
  10326. }
  10327. $offset = $table['cmap']['offset'] + $enctable['offset'];
  10328. $format = $this->_getUSHORT($font, $offset);
  10329. $offset += 2;
  10330. switch ($format) {
  10331. case 0: { // Format 0: Byte encoding table
  10332. $offset += 4; // skip length and version/language
  10333. for ($c = 0; $c < 256; ++$c) {
  10334. if (isset($subsetchars[$c])) {
  10335. $g = $this->_getBYTE($font, $offset);
  10336. $subsetglyphs[$g] = true;
  10337. }
  10338. ++$offset;
  10339. }
  10340. break;
  10341. }
  10342. case 2: { // Format 2: High-byte mapping through table
  10343. $offset += 4; // skip length and version/language
  10344. $numSubHeaders = 0;
  10345. for ($i = 0; $i < 256; ++$i) {
  10346. // Array that maps high bytes to subHeaders: value is subHeader index * 8.
  10347. $subHeaderKeys[$i] = ($this->_getUSHORT($font, $offset) / 8);
  10348. $offset += 2;
  10349. if ($numSubHeaders < $subHeaderKeys[$i]) {
  10350. $numSubHeaders = $subHeaderKeys[$i];
  10351. }
  10352. }
  10353. // the number of subHeaders is equal to the max of subHeaderKeys + 1
  10354. ++$numSubHeaders;
  10355. // read subHeader structures
  10356. $subHeaders = array();
  10357. $numGlyphIndexArray = 0;
  10358. for ($k = 0; $k < $numSubHeaders; ++$k) {
  10359. $subHeaders[$k]['firstCode'] = $this->_getUSHORT($font, $offset);
  10360. $offset += 2;
  10361. $subHeaders[$k]['entryCount'] = $this->_getUSHORT($font, $offset);
  10362. $offset += 2;
  10363. $subHeaders[$k]['idDelta'] = $this->_getSHORT($font, $offset);
  10364. $offset += 2;
  10365. $subHeaders[$k]['idRangeOffset'] = $this->_getUSHORT($font, $offset);
  10366. $offset += 2;
  10367. $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
  10368. $subHeaders[$k]['idRangeOffset'] /= 2;
  10369. $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
  10370. }
  10371. for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
  10372. $glyphIndexArray[$k] = $this->_getUSHORT($font, $offset);
  10373. $offset += 2;
  10374. }
  10375. for ($i = 0; $i < 256; ++$i) {
  10376. $k = $subHeaderKeys[$i];
  10377. if ($k == 0) {
  10378. // one byte code
  10379. $c = $i;
  10380. if (isset($subsetchars[$c])) {
  10381. $g = $glyphIndexArray[0];
  10382. $subsetglyphs[$g] = true;
  10383. }
  10384. } else {
  10385. // two bytes code
  10386. $start_byte = $subHeaders[$k]['firstCode'];
  10387. $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
  10388. for ($j = $start_byte; $j < $end_byte; ++$j) {
  10389. // combine high and low bytes
  10390. $c = (($i << 8) + $j);
  10391. if (isset($subsetchars[$c])) {
  10392. $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
  10393. $g = $glyphIndexArray[$idRangeOffset];
  10394. $g += ($idDelta[$k] - 65536);
  10395. if ($g < 0) {
  10396. $g = 0;
  10397. }
  10398. $subsetglyphs[$g] = true;
  10399. }
  10400. }
  10401. }
  10402. }
  10403. break;
  10404. }
  10405. case 4: { // Format 4: Segment mapping to delta values
  10406. $length = $this->_getUSHORT($font, $offset);
  10407. $offset += 2;
  10408. $offset += 2; // skip version/language
  10409. $segCount = ($this->_getUSHORT($font, $offset) / 2);
  10410. $offset += 2;
  10411. $offset += 6; // skip searchRange, entrySelector, rangeShift
  10412. $endCount = array(); // array of end character codes for each segment
  10413. for ($k = 0; $k < $segCount; ++$k) {
  10414. $endCount[$k] = $this->_getUSHORT($font, $offset);
  10415. $offset += 2;
  10416. }
  10417. $offset += 2; // skip reservedPad
  10418. $startCount = array(); // array of start character codes for each segment
  10419. for ($k = 0; $k < $segCount; ++$k) {
  10420. $startCount[$k] = $this->_getUSHORT($font, $offset);
  10421. $offset += 2;
  10422. }
  10423. $idDelta = array(); // delta for all character codes in segment
  10424. for ($k = 0; $k < $segCount; ++$k) {
  10425. $idDelta[$k] = $this->_getUSHORT($font, $offset);
  10426. $offset += 2;
  10427. }
  10428. $idRangeOffset = array(); // Offsets into glyphIdArray or 0
  10429. for ($k = 0; $k < $segCount; ++$k) {
  10430. $idRangeOffset[$k] = $this->_getUSHORT($font, $offset);
  10431. $offset += 2;
  10432. }
  10433. $gidlen = ($length / 2) - 8 - (4 * $segCount);
  10434. $glyphIdArray = array(); // glyph index array
  10435. for ($k = 0; $k < $gidlen; ++$k) {
  10436. $glyphIdArray[$k] = $this->_getUSHORT($font, $offset);
  10437. $offset += 2;
  10438. }
  10439. for ($k = 0; $k < $segCount; ++$k) {
  10440. for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
  10441. if (isset($subsetchars[$c])) {
  10442. if ($idRangeOffset[$k] == 0) {
  10443. $g = $c;
  10444. } else {
  10445. $gid = (($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
  10446. $g = $glyphIdArray[$gid];
  10447. }
  10448. $g += ($idDelta[$k] - 65536);
  10449. if ($g < 0) {
  10450. $g = 0;
  10451. }
  10452. $subsetglyphs[$g] = true;
  10453. }
  10454. }
  10455. }
  10456. break;
  10457. }
  10458. case 6: { // Format 6: Trimmed table mapping
  10459. $offset += 4; // skip length and version/language
  10460. $firstCode = $this->_getUSHORT($font, $offset);
  10461. $offset += 2;
  10462. $entryCount = $this->_getUSHORT($font, $offset);
  10463. $offset += 2;
  10464. for ($k = 0; $k < $entryCount; ++$k) {
  10465. $c = ($k + $firstCode);
  10466. if (isset($subsetchars[$c])) {
  10467. $g = $this->_getUSHORT($font, $offset);
  10468. $subsetglyphs[$g] = true;
  10469. }
  10470. $offset += 2;
  10471. }
  10472. break;
  10473. }
  10474. case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
  10475. $offset += 10; // skip reserved, length and version/language
  10476. for ($k = 0; $k < 8192; ++$k) {
  10477. $is32[$k] = $this->_getBYTE($font, $offset);
  10478. ++$offset;
  10479. }
  10480. $nGroups = $this->_getULONG($font, $offset);
  10481. $offset += 4;
  10482. for ($i = 0; $i < $nGroups; ++$i) {
  10483. $startCharCode = $this->_getULONG($font, $offset);
  10484. $offset += 4;
  10485. $endCharCode = $this->_getULONG($font, $offset);
  10486. $offset += 4;
  10487. $startGlyphID = $this->_getULONG($font, $offset);
  10488. $offset += 4;
  10489. for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
  10490. $is32idx = floor($c / 8);
  10491. if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
  10492. $c = $k;
  10493. } else {
  10494. // 32 bit format
  10495. // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
  10496. //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
  10497. //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
  10498. $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
  10499. }
  10500. if (isset($subsetchars[$c])) {
  10501. $subsetglyphs[$startGlyphID] = true;
  10502. }
  10503. ++$startGlyphID;
  10504. }
  10505. }
  10506. break;
  10507. }
  10508. case 10: { // Format 10: Trimmed array
  10509. $offset += 10; // skip reserved, length and version/language
  10510. $startCharCode = $this->_getULONG($font, $offset);
  10511. $offset += 4;
  10512. $numChars = $this->_getULONG($font, $offset);
  10513. $offset += 4;
  10514. for ($k = 0; $k < $numChars; ++$k) {
  10515. $c = ($k + $startCharCode);
  10516. if (isset($subsetchars[$c])) {
  10517. $g = $this->_getUSHORT($font, $offset);
  10518. $subsetglyphs[$g] = true;
  10519. }
  10520. $offset += 2;
  10521. }
  10522. break;
  10523. }
  10524. case 12: { // Format 12: Segmented coverage
  10525. $offset += 10; // skip length and version/language
  10526. $nGroups = $this->_getULONG($font, $offset);
  10527. $offset += 4;
  10528. for ($k = 0; $k < $nGroups; ++$k) {
  10529. $startCharCode = $this->_getULONG($font, $offset);
  10530. $offset += 4;
  10531. $endCharCode = $this->_getULONG($font, $offset);
  10532. $offset += 4;
  10533. $startGlyphCode = $this->_getULONG($font, $offset);
  10534. $offset += 4;
  10535. for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
  10536. if (isset($subsetchars[$c])) {
  10537. $subsetglyphs[$startGlyphCode] = true;
  10538. }
  10539. ++$startGlyphCode;
  10540. }
  10541. }
  10542. break;
  10543. }
  10544. case 13: { // Format 13: Many-to-one range mappings
  10545. // to be implemented ...
  10546. break;
  10547. }
  10548. case 14: { // Format 14: Unicode Variation Sequences
  10549. // to be implemented ...
  10550. break;
  10551. }
  10552. }
  10553. }
  10554. // include all parts of composite glyphs
  10555. $new_sga = $subsetglyphs;
  10556. while (!empty($new_sga)) {
  10557. $sga = $new_sga;
  10558. $new_sga = array();
  10559. foreach ($sga as $key => $val) {
  10560. if (isset($indexToLoc[$key])) {
  10561. $offset = ($table['glyf']['offset'] + $indexToLoc[$key]);
  10562. $numberOfContours = $this->_getSHORT($font, $offset);
  10563. $offset += 2;
  10564. if ($numberOfContours < 0) { // composite glyph
  10565. $offset += 8; // skip xMin, yMin, xMax, yMax
  10566. do {
  10567. $flags = $this->_getUSHORT($font, $offset);
  10568. $offset += 2;
  10569. $glyphIndex = $this->_getUSHORT($font, $offset);
  10570. $offset += 2;
  10571. if (!isset($subsetglyphs[$glyphIndex])) {
  10572. // add missing glyphs
  10573. $new_sga[$glyphIndex] = true;
  10574. }
  10575. // skip some bytes by case
  10576. if ($flags & 1) {
  10577. $offset += 4;
  10578. } else {
  10579. $offset += 2;
  10580. }
  10581. if ($flags & 8) {
  10582. $offset += 2;
  10583. } elseif ($flags & 64) {
  10584. $offset += 4;
  10585. } elseif ($flags & 128) {
  10586. $offset += 8;
  10587. }
  10588. } while ($flags & 32);
  10589. }
  10590. }
  10591. }
  10592. $subsetglyphs += $new_sga;
  10593. }
  10594. // sort glyphs by key (and remove duplicates)
  10595. ksort($subsetglyphs);
  10596. // build new glyf and loca tables
  10597. $glyf = '';
  10598. $loca = '';
  10599. $offset = 0;
  10600. $glyf_offset = $table['glyf']['offset'];
  10601. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10602. if (isset($subsetglyphs[$i])) {
  10603. $length = ($indexToLoc[($i + 1)] - $indexToLoc[$i]);
  10604. $glyf .= substr($font, ($glyf_offset + $indexToLoc[$i]), $length);
  10605. } else {
  10606. $length = 0;
  10607. }
  10608. if ($short_offset) {
  10609. $loca .= pack('n', ($offset / 2));
  10610. } else {
  10611. $loca .= pack('N', $offset);
  10612. }
  10613. $offset += $length;
  10614. }
  10615. // array of table names to preserve (loca and glyf tables will be added later)
  10616. // the cmap table is not needed and shall not be present, since the mapping from character codes to glyph descriptions is provided separately
  10617. $table_names = array ('head', 'hhea', 'hmtx', 'maxp', 'cvt ', 'fpgm', 'prep'); // minimum required table names
  10618. // get the tables to preserve
  10619. $offset = 12;
  10620. foreach ($table as $tag => $val) {
  10621. if (in_array($tag, $table_names)) {
  10622. $table[$tag]['data'] = substr($font, $table[$tag]['offset'], $table[$tag]['length']);
  10623. if ($tag == 'head') {
  10624. // set the checkSumAdjustment to 0
  10625. $table[$tag]['data'] = substr($table[$tag]['data'], 0, 8)."\x0\x0\x0\x0".substr($table[$tag]['data'], 12);
  10626. }
  10627. $pad = 4 - ($table[$tag]['length'] % 4);
  10628. if ($pad != 4) {
  10629. // the length of a table must be a multiple of four bytes
  10630. $table[$tag]['length'] += $pad;
  10631. $table[$tag]['data'] .= str_repeat("\x0", $pad);
  10632. }
  10633. $table[$tag]['offset'] = $offset;
  10634. $offset += $table[$tag]['length'];
  10635. // check sum is not changed (so keep the following line commented)
  10636. //$table[$tag]['checkSum'] = $this->_getTTFtableChecksum($table[$tag]['data'], $table[$tag]['length']);
  10637. } else {
  10638. unset($table[$tag]);
  10639. }
  10640. }
  10641. // add loca
  10642. $table['loca']['data'] = $loca;
  10643. $table['loca']['length'] = strlen($loca);
  10644. $pad = 4 - ($table['loca']['length'] % 4);
  10645. if ($pad != 4) {
  10646. // the length of a table must be a multiple of four bytes
  10647. $table['loca']['length'] += $pad;
  10648. $table['loca']['data'] .= str_repeat("\x0", $pad);
  10649. }
  10650. $table['loca']['offset'] = $offset;
  10651. $table['loca']['checkSum'] = $this->_getTTFtableChecksum($table['loca']['data'], $table['loca']['length']);
  10652. $offset += $table['loca']['length'];
  10653. // add glyf
  10654. $table['glyf']['data'] = $glyf;
  10655. $table['glyf']['length'] = strlen($glyf);
  10656. $pad = 4 - ($table['glyf']['length'] % 4);
  10657. if ($pad != 4) {
  10658. // the length of a table must be a multiple of four bytes
  10659. $table['glyf']['length'] += $pad;
  10660. $table['glyf']['data'] .= str_repeat("\x0", $pad);
  10661. }
  10662. $table['glyf']['offset'] = $offset;
  10663. $table['glyf']['checkSum'] = $this->_getTTFtableChecksum($table['glyf']['data'], $table['glyf']['length']);
  10664. // rebuild font
  10665. $font = '';
  10666. $font .= pack('N', 0x10000); // sfnt version
  10667. $numTables = count($table);
  10668. $font .= pack('n', $numTables); // numTables
  10669. $entrySelector = floor(log($numTables, 2));
  10670. $searchRange = pow(2, $entrySelector) * 16;
  10671. $rangeShift = ($numTables * 16) - $searchRange;
  10672. $font .= pack('n', $searchRange); // searchRange
  10673. $font .= pack('n', $entrySelector); // entrySelector
  10674. $font .= pack('n', $rangeShift); // rangeShift
  10675. $offset = ($numTables * 16);
  10676. foreach ($table as $tag => $data) {
  10677. $font .= $tag; // tag
  10678. $font .= pack('N', $data['checkSum']); // checkSum
  10679. $font .= pack('N', ($data['offset'] + $offset)); // offset
  10680. $font .= pack('N', $data['length']); // length
  10681. }
  10682. foreach ($table as $data) {
  10683. $font .= $data['data'];
  10684. }
  10685. // set checkSumAdjustment on head table
  10686. $checkSumAdjustment = 0xB1B0AFBA - $this->_getTTFtableChecksum($font, strlen($font));
  10687. $font = substr($font, 0, $table['head']['offset'] + 8).pack('N', $checkSumAdjustment).substr($font, $table['head']['offset'] + 12);
  10688. return $font;
  10689. }
  10690. /**
  10691. * Returs the checksum of a TTF table.
  10692. * @param $table (string) table to check
  10693. * @param $length (int) length of table in bytes
  10694. * @return int checksum
  10695. * @author Nicola Asuni
  10696. * @protected
  10697. * @since 5.2.000 (2010-06-02)
  10698. */
  10699. protected function _getTTFtableChecksum($table, $length) {
  10700. $sum = 0;
  10701. $tlen = ($length / 4);
  10702. $offset = 0;
  10703. for ($i = 0; $i < $tlen; ++$i) {
  10704. $v = unpack('Ni', substr($table, $offset, 4));
  10705. $sum += $v['i'];
  10706. $offset += 4;
  10707. }
  10708. $sum = unpack('Ni', pack('N', $sum));
  10709. return $sum['i'];
  10710. }
  10711. /**
  10712. * Outputs font widths
  10713. * @param $font (array) font data
  10714. * @param $cidoffset (int) offset for CID values
  10715. * @return PDF command string for font widths
  10716. * @author Nicola Asuni
  10717. * @protected
  10718. * @since 4.4.000 (2008-12-07)
  10719. */
  10720. protected function _putfontwidths($font, $cidoffset=0) {
  10721. ksort($font['cw']);
  10722. $rangeid = 0;
  10723. $range = array();
  10724. $prevcid = -2;
  10725. $prevwidth = -1;
  10726. $interval = false;
  10727. // for each character
  10728. foreach ($font['cw'] as $cid => $width) {
  10729. $cid -= $cidoffset;
  10730. if ($font['subset'] AND ($cid > 255) AND (!isset($font['subsetchars'][$cid]))) {
  10731. // ignore the unused characters (font subsetting)
  10732. continue;
  10733. }
  10734. if ($width != $font['dw']) {
  10735. if ($cid == ($prevcid + 1)) {
  10736. // consecutive CID
  10737. if ($width == $prevwidth) {
  10738. if ($width == $range[$rangeid][0]) {
  10739. $range[$rangeid][] = $width;
  10740. } else {
  10741. array_pop($range[$rangeid]);
  10742. // new range
  10743. $rangeid = $prevcid;
  10744. $range[$rangeid] = array();
  10745. $range[$rangeid][] = $prevwidth;
  10746. $range[$rangeid][] = $width;
  10747. }
  10748. $interval = true;
  10749. $range[$rangeid]['interval'] = true;
  10750. } else {
  10751. if ($interval) {
  10752. // new range
  10753. $rangeid = $cid;
  10754. $range[$rangeid] = array();
  10755. $range[$rangeid][] = $width;
  10756. } else {
  10757. $range[$rangeid][] = $width;
  10758. }
  10759. $interval = false;
  10760. }
  10761. } else {
  10762. // new range
  10763. $rangeid = $cid;
  10764. $range[$rangeid] = array();
  10765. $range[$rangeid][] = $width;
  10766. $interval = false;
  10767. }
  10768. $prevcid = $cid;
  10769. $prevwidth = $width;
  10770. }
  10771. }
  10772. // optimize ranges
  10773. $prevk = -1;
  10774. $nextk = -1;
  10775. $prevint = false;
  10776. foreach ($range as $k => $ws) {
  10777. $cws = count($ws);
  10778. if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
  10779. if (isset($range[$k]['interval'])) {
  10780. unset($range[$k]['interval']);
  10781. }
  10782. $range[$prevk] = array_merge($range[$prevk], $range[$k]);
  10783. unset($range[$k]);
  10784. } else {
  10785. $prevk = $k;
  10786. }
  10787. $nextk = $k + $cws;
  10788. if (isset($ws['interval'])) {
  10789. if ($cws > 3) {
  10790. $prevint = true;
  10791. } else {
  10792. $prevint = false;
  10793. }
  10794. unset($range[$k]['interval']);
  10795. --$nextk;
  10796. } else {
  10797. $prevint = false;
  10798. }
  10799. }
  10800. // output data
  10801. $w = '';
  10802. foreach ($range as $k => $ws) {
  10803. if (count(array_count_values($ws)) == 1) {
  10804. // interval mode is more compact
  10805. $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
  10806. } else {
  10807. // range mode
  10808. $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
  10809. }
  10810. }
  10811. return '/W ['.$w.' ]';
  10812. }
  10813. /**
  10814. * Output fonts.
  10815. * @author Nicola Asuni
  10816. * @protected
  10817. */
  10818. protected function _putfonts() {
  10819. $nf = $this->n;
  10820. foreach ($this->diffs as $diff) {
  10821. //Encodings
  10822. $this->_newobj();
  10823. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  10824. }
  10825. $mqr = $this->get_mqr();
  10826. $this->set_mqr(false);
  10827. foreach ($this->FontFiles as $file => $info) {
  10828. // search and get font file to embedd
  10829. $fontdir = $info['fontdir'];
  10830. $file = strtolower($file);
  10831. $fontfile = '';
  10832. // search files on various directories
  10833. if (($fontdir !== false) AND file_exists($fontdir.$file)) {
  10834. $fontfile = $fontdir.$file;
  10835. } elseif (file_exists($this->_getfontpath().$file)) {
  10836. $fontfile = $this->_getfontpath().$file;
  10837. } elseif (file_exists($file)) {
  10838. $fontfile = $file;
  10839. }
  10840. if (!$this->empty_string($fontfile)) {
  10841. $font = file_get_contents($fontfile);
  10842. $compressed = (substr($file, -2) == '.z');
  10843. if ((!$compressed) AND (isset($info['length2']))) {
  10844. $header = (ord($font{0}) == 128);
  10845. if ($header) {
  10846. // strip first binary header
  10847. $font = substr($font, 6);
  10848. }
  10849. if ($header AND (ord($font[$info['length1']]) == 128)) {
  10850. // strip second binary header
  10851. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  10852. }
  10853. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  10854. if ($compressed) {
  10855. // uncompress font
  10856. $font = gzuncompress($font);
  10857. }
  10858. // merge subset characters
  10859. $subsetchars = array(); // used chars
  10860. foreach ($info['fontkeys'] as $fontkey) {
  10861. $fontinfo = $this->getFontBuffer($fontkey);
  10862. $subsetchars += $fontinfo['subsetchars'];
  10863. }
  10864. // rebuild a font subset
  10865. $font = $this->_getTrueTypeFontSubset($font, $subsetchars);
  10866. // calculate new font length
  10867. $info['length1'] = strlen($font);
  10868. if ($compressed) {
  10869. // recompress font
  10870. $font = gzcompress($font);
  10871. }
  10872. }
  10873. $this->_newobj();
  10874. $this->FontFiles[$file]['n'] = $this->n;
  10875. $stream = $this->_getrawstream($font);
  10876. $out = '<< /Length '.strlen($stream);
  10877. if ($compressed) {
  10878. $out .= ' /Filter /FlateDecode';
  10879. }
  10880. $out .= ' /Length1 '.$info['length1'];
  10881. if (isset($info['length2'])) {
  10882. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  10883. }
  10884. $out .= ' >>';
  10885. $out .= ' stream'."\n".$stream."\n".'endstream';
  10886. $out .= "\n".'endobj';
  10887. $this->_out($out);
  10888. }
  10889. }
  10890. $this->set_mqr($mqr);
  10891. foreach ($this->fontkeys as $k) {
  10892. //Font objects
  10893. $font = $this->getFontBuffer($k);
  10894. $type = $font['type'];
  10895. $name = $font['name'];
  10896. if ($type == 'core') {
  10897. // standard core font
  10898. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  10899. $out .= '<</Type /Font';
  10900. $out .= ' /Subtype /Type1';
  10901. $out .= ' /BaseFont /'.$name;
  10902. $out .= ' /Name /F'.$font['i'];
  10903. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  10904. $out .= ' /Encoding /WinAnsiEncoding';
  10905. }
  10906. if ($k == 'helvetica') {
  10907. // add default font for annotations
  10908. $this->annotation_fonts[$k] = $font['i'];
  10909. }
  10910. $out .= ' >>';
  10911. $out .= "\n".'endobj';
  10912. $this->_out($out);
  10913. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  10914. // additional Type1 or TrueType font
  10915. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  10916. $out .= '<</Type /Font';
  10917. $out .= ' /Subtype /'.$type;
  10918. $out .= ' /BaseFont /'.$name;
  10919. $out .= ' /Name /F'.$font['i'];
  10920. $out .= ' /FirstChar 32 /LastChar 255';
  10921. $out .= ' /Widths '.($this->n + 1).' 0 R';
  10922. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  10923. if ($font['enc']) {
  10924. if (isset($font['diff'])) {
  10925. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  10926. } else {
  10927. $out .= ' /Encoding /WinAnsiEncoding';
  10928. }
  10929. }
  10930. $out .= ' >>';
  10931. $out .= "\n".'endobj';
  10932. $this->_out($out);
  10933. // Widths
  10934. $this->_newobj();
  10935. $s = '[';
  10936. for ($i = 32; $i < 256; ++$i) {
  10937. $s .= $font['cw'][$i].' ';
  10938. }
  10939. $s .= ']';
  10940. $s .= "\n".'endobj';
  10941. $this->_out($s);
  10942. //Descriptor
  10943. $this->_newobj();
  10944. $s = '<</Type /FontDescriptor /FontName /'.$name;
  10945. foreach ($font['desc'] as $fdk => $fdv) {
  10946. if (is_float($fdv)) {
  10947. $fdv = sprintf('%.3F', $fdv);
  10948. }
  10949. $s .= ' /'.$fdk.' '.$fdv.'';
  10950. }
  10951. if (!$this->empty_string($font['file'])) {
  10952. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  10953. }
  10954. $s .= '>>';
  10955. $s .= "\n".'endobj';
  10956. $this->_out($s);
  10957. } else {
  10958. // additional types
  10959. $mtd = '_put'.strtolower($type);
  10960. if (!method_exists($this, $mtd)) {
  10961. $this->Error('Unsupported font type: '.$type);
  10962. }
  10963. $this->$mtd($font);
  10964. }
  10965. }
  10966. }
  10967. /**
  10968. * Adds unicode fonts.<br>
  10969. * Based on PDF Reference 1.3 (section 5)
  10970. * @param $font (array) font data
  10971. * @protected
  10972. * @author Nicola Asuni
  10973. * @since 1.52.0.TC005 (2005-01-05)
  10974. */
  10975. protected function _puttruetypeunicode($font) {
  10976. $fontname = '';
  10977. if ($font['subset']) {
  10978. // change name for font subsetting
  10979. $subtag = sprintf('%06u', $font['i']);
  10980. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  10981. $fontname .= $subtag.'+';
  10982. }
  10983. $fontname .= $font['name'];
  10984. // Type0 Font
  10985. // A composite font composed of other fonts, organized hierarchically
  10986. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  10987. $out .= '<< /Type /Font';
  10988. $out .= ' /Subtype /Type0';
  10989. $out .= ' /BaseFont /'.$fontname;
  10990. $out .= ' /Name /F'.$font['i'];
  10991. $out .= ' /Encoding /'.$font['enc'];
  10992. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  10993. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  10994. $out .= ' >>';
  10995. $out .= "\n".'endobj';
  10996. $this->_out($out);
  10997. // ToUnicode map for Identity-H
  10998. $stream = "/CIDInit /ProcSet findresource begin\n";
  10999. $stream .= "12 dict begin\n";
  11000. $stream .= "begincmap\n";
  11001. $stream .= "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n";
  11002. $stream .= "/CMapName /Adobe-Identity-UCS def\n";
  11003. $stream .= "/CMapType 2 def\n";
  11004. $stream .= "/WMode 0 def\n";
  11005. $stream .= "1 begincodespacerange\n";
  11006. $stream .= "<0000> <FFFF>\n";
  11007. $stream .= "endcodespacerange\n";
  11008. $stream .= "100 beginbfrange\n";
  11009. $stream .= "<0000> <00ff> <0000>\n";
  11010. $stream .= "<0100> <01ff> <0100>\n";
  11011. $stream .= "<0200> <02ff> <0200>\n";
  11012. $stream .= "<0300> <03ff> <0300>\n";
  11013. $stream .= "<0400> <04ff> <0400>\n";
  11014. $stream .= "<0500> <05ff> <0500>\n";
  11015. $stream .= "<0600> <06ff> <0600>\n";
  11016. $stream .= "<0700> <07ff> <0700>\n";
  11017. $stream .= "<0800> <08ff> <0800>\n";
  11018. $stream .= "<0900> <09ff> <0900>\n";
  11019. $stream .= "<0a00> <0aff> <0a00>\n";
  11020. $stream .= "<0b00> <0bff> <0b00>\n";
  11021. $stream .= "<0c00> <0cff> <0c00>\n";
  11022. $stream .= "<0d00> <0dff> <0d00>\n";
  11023. $stream .= "<0e00> <0eff> <0e00>\n";
  11024. $stream .= "<0f00> <0fff> <0f00>\n";
  11025. $stream .= "<1000> <10ff> <1000>\n";
  11026. $stream .= "<1100> <11ff> <1100>\n";
  11027. $stream .= "<1200> <12ff> <1200>\n";
  11028. $stream .= "<1300> <13ff> <1300>\n";
  11029. $stream .= "<1400> <14ff> <1400>\n";
  11030. $stream .= "<1500> <15ff> <1500>\n";
  11031. $stream .= "<1600> <16ff> <1600>\n";
  11032. $stream .= "<1700> <17ff> <1700>\n";
  11033. $stream .= "<1800> <18ff> <1800>\n";
  11034. $stream .= "<1900> <19ff> <1900>\n";
  11035. $stream .= "<1a00> <1aff> <1a00>\n";
  11036. $stream .= "<1b00> <1bff> <1b00>\n";
  11037. $stream .= "<1c00> <1cff> <1c00>\n";
  11038. $stream .= "<1d00> <1dff> <1d00>\n";
  11039. $stream .= "<1e00> <1eff> <1e00>\n";
  11040. $stream .= "<1f00> <1fff> <1f00>\n";
  11041. $stream .= "<2000> <20ff> <2000>\n";
  11042. $stream .= "<2100> <21ff> <2100>\n";
  11043. $stream .= "<2200> <22ff> <2200>\n";
  11044. $stream .= "<2300> <23ff> <2300>\n";
  11045. $stream .= "<2400> <24ff> <2400>\n";
  11046. $stream .= "<2500> <25ff> <2500>\n";
  11047. $stream .= "<2600> <26ff> <2600>\n";
  11048. $stream .= "<2700> <27ff> <2700>\n";
  11049. $stream .= "<2800> <28ff> <2800>\n";
  11050. $stream .= "<2900> <29ff> <2900>\n";
  11051. $stream .= "<2a00> <2aff> <2a00>\n";
  11052. $stream .= "<2b00> <2bff> <2b00>\n";
  11053. $stream .= "<2c00> <2cff> <2c00>\n";
  11054. $stream .= "<2d00> <2dff> <2d00>\n";
  11055. $stream .= "<2e00> <2eff> <2e00>\n";
  11056. $stream .= "<2f00> <2fff> <2f00>\n";
  11057. $stream .= "<3000> <30ff> <3000>\n";
  11058. $stream .= "<3100> <31ff> <3100>\n";
  11059. $stream .= "<3200> <32ff> <3200>\n";
  11060. $stream .= "<3300> <33ff> <3300>\n";
  11061. $stream .= "<3400> <34ff> <3400>\n";
  11062. $stream .= "<3500> <35ff> <3500>\n";
  11063. $stream .= "<3600> <36ff> <3600>\n";
  11064. $stream .= "<3700> <37ff> <3700>\n";
  11065. $stream .= "<3800> <38ff> <3800>\n";
  11066. $stream .= "<3900> <39ff> <3900>\n";
  11067. $stream .= "<3a00> <3aff> <3a00>\n";
  11068. $stream .= "<3b00> <3bff> <3b00>\n";
  11069. $stream .= "<3c00> <3cff> <3c00>\n";
  11070. $stream .= "<3d00> <3dff> <3d00>\n";
  11071. $stream .= "<3e00> <3eff> <3e00>\n";
  11072. $stream .= "<3f00> <3fff> <3f00>\n";
  11073. $stream .= "<4000> <40ff> <4000>\n";
  11074. $stream .= "<4100> <41ff> <4100>\n";
  11075. $stream .= "<4200> <42ff> <4200>\n";
  11076. $stream .= "<4300> <43ff> <4300>\n";
  11077. $stream .= "<4400> <44ff> <4400>\n";
  11078. $stream .= "<4500> <45ff> <4500>\n";
  11079. $stream .= "<4600> <46ff> <4600>\n";
  11080. $stream .= "<4700> <47ff> <4700>\n";
  11081. $stream .= "<4800> <48ff> <4800>\n";
  11082. $stream .= "<4900> <49ff> <4900>\n";
  11083. $stream .= "<4a00> <4aff> <4a00>\n";
  11084. $stream .= "<4b00> <4bff> <4b00>\n";
  11085. $stream .= "<4c00> <4cff> <4c00>\n";
  11086. $stream .= "<4d00> <4dff> <4d00>\n";
  11087. $stream .= "<4e00> <4eff> <4e00>\n";
  11088. $stream .= "<4f00> <4fff> <4f00>\n";
  11089. $stream .= "<5000> <50ff> <5000>\n";
  11090. $stream .= "<5100> <51ff> <5100>\n";
  11091. $stream .= "<5200> <52ff> <5200>\n";
  11092. $stream .= "<5300> <53ff> <5300>\n";
  11093. $stream .= "<5400> <54ff> <5400>\n";
  11094. $stream .= "<5500> <55ff> <5500>\n";
  11095. $stream .= "<5600> <56ff> <5600>\n";
  11096. $stream .= "<5700> <57ff> <5700>\n";
  11097. $stream .= "<5800> <58ff> <5800>\n";
  11098. $stream .= "<5900> <59ff> <5900>\n";
  11099. $stream .= "<5a00> <5aff> <5a00>\n";
  11100. $stream .= "<5b00> <5bff> <5b00>\n";
  11101. $stream .= "<5c00> <5cff> <5c00>\n";
  11102. $stream .= "<5d00> <5dff> <5d00>\n";
  11103. $stream .= "<5e00> <5eff> <5e00>\n";
  11104. $stream .= "<5f00> <5fff> <5f00>\n";
  11105. $stream .= "<6000> <60ff> <6000>\n";
  11106. $stream .= "<6100> <61ff> <6100>\n";
  11107. $stream .= "<6200> <62ff> <6200>\n";
  11108. $stream .= "<6300> <63ff> <6300>\n";
  11109. $stream .= "endbfrange\n";
  11110. $stream .= "100 beginbfrange\n";
  11111. $stream .= "<6400> <64ff> <6400>\n";
  11112. $stream .= "<6500> <65ff> <6500>\n";
  11113. $stream .= "<6600> <66ff> <6600>\n";
  11114. $stream .= "<6700> <67ff> <6700>\n";
  11115. $stream .= "<6800> <68ff> <6800>\n";
  11116. $stream .= "<6900> <69ff> <6900>\n";
  11117. $stream .= "<6a00> <6aff> <6a00>\n";
  11118. $stream .= "<6b00> <6bff> <6b00>\n";
  11119. $stream .= "<6c00> <6cff> <6c00>\n";
  11120. $stream .= "<6d00> <6dff> <6d00>\n";
  11121. $stream .= "<6e00> <6eff> <6e00>\n";
  11122. $stream .= "<6f00> <6fff> <6f00>\n";
  11123. $stream .= "<7000> <70ff> <7000>\n";
  11124. $stream .= "<7100> <71ff> <7100>\n";
  11125. $stream .= "<7200> <72ff> <7200>\n";
  11126. $stream .= "<7300> <73ff> <7300>\n";
  11127. $stream .= "<7400> <74ff> <7400>\n";
  11128. $stream .= "<7500> <75ff> <7500>\n";
  11129. $stream .= "<7600> <76ff> <7600>\n";
  11130. $stream .= "<7700> <77ff> <7700>\n";
  11131. $stream .= "<7800> <78ff> <7800>\n";
  11132. $stream .= "<7900> <79ff> <7900>\n";
  11133. $stream .= "<7a00> <7aff> <7a00>\n";
  11134. $stream .= "<7b00> <7bff> <7b00>\n";
  11135. $stream .= "<7c00> <7cff> <7c00>\n";
  11136. $stream .= "<7d00> <7dff> <7d00>\n";
  11137. $stream .= "<7e00> <7eff> <7e00>\n";
  11138. $stream .= "<7f00> <7fff> <7f00>\n";
  11139. $stream .= "<8000> <80ff> <8000>\n";
  11140. $stream .= "<8100> <81ff> <8100>\n";
  11141. $stream .= "<8200> <82ff> <8200>\n";
  11142. $stream .= "<8300> <83ff> <8300>\n";
  11143. $stream .= "<8400> <84ff> <8400>\n";
  11144. $stream .= "<8500> <85ff> <8500>\n";
  11145. $stream .= "<8600> <86ff> <8600>\n";
  11146. $stream .= "<8700> <87ff> <8700>\n";
  11147. $stream .= "<8800> <88ff> <8800>\n";
  11148. $stream .= "<8900> <89ff> <8900>\n";
  11149. $stream .= "<8a00> <8aff> <8a00>\n";
  11150. $stream .= "<8b00> <8bff> <8b00>\n";
  11151. $stream .= "<8c00> <8cff> <8c00>\n";
  11152. $stream .= "<8d00> <8dff> <8d00>\n";
  11153. $stream .= "<8e00> <8eff> <8e00>\n";
  11154. $stream .= "<8f00> <8fff> <8f00>\n";
  11155. $stream .= "<9000> <90ff> <9000>\n";
  11156. $stream .= "<9100> <91ff> <9100>\n";
  11157. $stream .= "<9200> <92ff> <9200>\n";
  11158. $stream .= "<9300> <93ff> <9300>\n";
  11159. $stream .= "<9400> <94ff> <9400>\n";
  11160. $stream .= "<9500> <95ff> <9500>\n";
  11161. $stream .= "<9600> <96ff> <9600>\n";
  11162. $stream .= "<9700> <97ff> <9700>\n";
  11163. $stream .= "<9800> <98ff> <9800>\n";
  11164. $stream .= "<9900> <99ff> <9900>\n";
  11165. $stream .= "<9a00> <9aff> <9a00>\n";
  11166. $stream .= "<9b00> <9bff> <9b00>\n";
  11167. $stream .= "<9c00> <9cff> <9c00>\n";
  11168. $stream .= "<9d00> <9dff> <9d00>\n";
  11169. $stream .= "<9e00> <9eff> <9e00>\n";
  11170. $stream .= "<9f00> <9fff> <9f00>\n";
  11171. $stream .= "<a000> <a0ff> <a000>\n";
  11172. $stream .= "<a100> <a1ff> <a100>\n";
  11173. $stream .= "<a200> <a2ff> <a200>\n";
  11174. $stream .= "<a300> <a3ff> <a300>\n";
  11175. $stream .= "<a400> <a4ff> <a400>\n";
  11176. $stream .= "<a500> <a5ff> <a500>\n";
  11177. $stream .= "<a600> <a6ff> <a600>\n";
  11178. $stream .= "<a700> <a7ff> <a700>\n";
  11179. $stream .= "<a800> <a8ff> <a800>\n";
  11180. $stream .= "<a900> <a9ff> <a900>\n";
  11181. $stream .= "<aa00> <aaff> <aa00>\n";
  11182. $stream .= "<ab00> <abff> <ab00>\n";
  11183. $stream .= "<ac00> <acff> <ac00>\n";
  11184. $stream .= "<ad00> <adff> <ad00>\n";
  11185. $stream .= "<ae00> <aeff> <ae00>\n";
  11186. $stream .= "<af00> <afff> <af00>\n";
  11187. $stream .= "<b000> <b0ff> <b000>\n";
  11188. $stream .= "<b100> <b1ff> <b100>\n";
  11189. $stream .= "<b200> <b2ff> <b200>\n";
  11190. $stream .= "<b300> <b3ff> <b300>\n";
  11191. $stream .= "<b400> <b4ff> <b400>\n";
  11192. $stream .= "<b500> <b5ff> <b500>\n";
  11193. $stream .= "<b600> <b6ff> <b600>\n";
  11194. $stream .= "<b700> <b7ff> <b700>\n";
  11195. $stream .= "<b800> <b8ff> <b800>\n";
  11196. $stream .= "<b900> <b9ff> <b900>\n";
  11197. $stream .= "<ba00> <baff> <ba00>\n";
  11198. $stream .= "<bb00> <bbff> <bb00>\n";
  11199. $stream .= "<bc00> <bcff> <bc00>\n";
  11200. $stream .= "<bd00> <bdff> <bd00>\n";
  11201. $stream .= "<be00> <beff> <be00>\n";
  11202. $stream .= "<bf00> <bfff> <bf00>\n";
  11203. $stream .= "<c000> <c0ff> <c000>\n";
  11204. $stream .= "<c100> <c1ff> <c100>\n";
  11205. $stream .= "<c200> <c2ff> <c200>\n";
  11206. $stream .= "<c300> <c3ff> <c300>\n";
  11207. $stream .= "<c400> <c4ff> <c400>\n";
  11208. $stream .= "<c500> <c5ff> <c500>\n";
  11209. $stream .= "<c600> <c6ff> <c600>\n";
  11210. $stream .= "<c700> <c7ff> <c700>\n";
  11211. $stream .= "endbfrange\n";
  11212. $stream .= "56 beginbfrange\n";
  11213. $stream .= "<c800> <c8ff> <c800>\n";
  11214. $stream .= "<c900> <c9ff> <c900>\n";
  11215. $stream .= "<ca00> <caff> <ca00>\n";
  11216. $stream .= "<cb00> <cbff> <cb00>\n";
  11217. $stream .= "<cc00> <ccff> <cc00>\n";
  11218. $stream .= "<cd00> <cdff> <cd00>\n";
  11219. $stream .= "<ce00> <ceff> <ce00>\n";
  11220. $stream .= "<cf00> <cfff> <cf00>\n";
  11221. $stream .= "<d000> <d0ff> <d000>\n";
  11222. $stream .= "<d100> <d1ff> <d100>\n";
  11223. $stream .= "<d200> <d2ff> <d200>\n";
  11224. $stream .= "<d300> <d3ff> <d300>\n";
  11225. $stream .= "<d400> <d4ff> <d400>\n";
  11226. $stream .= "<d500> <d5ff> <d500>\n";
  11227. $stream .= "<d600> <d6ff> <d600>\n";
  11228. $stream .= "<d700> <d7ff> <d700>\n";
  11229. $stream .= "<d800> <d8ff> <d800>\n";
  11230. $stream .= "<d900> <d9ff> <d900>\n";
  11231. $stream .= "<da00> <daff> <da00>\n";
  11232. $stream .= "<db00> <dbff> <db00>\n";
  11233. $stream .= "<dc00> <dcff> <dc00>\n";
  11234. $stream .= "<dd00> <ddff> <dd00>\n";
  11235. $stream .= "<de00> <deff> <de00>\n";
  11236. $stream .= "<df00> <dfff> <df00>\n";
  11237. $stream .= "<e000> <e0ff> <e000>\n";
  11238. $stream .= "<e100> <e1ff> <e100>\n";
  11239. $stream .= "<e200> <e2ff> <e200>\n";
  11240. $stream .= "<e300> <e3ff> <e300>\n";
  11241. $stream .= "<e400> <e4ff> <e400>\n";
  11242. $stream .= "<e500> <e5ff> <e500>\n";
  11243. $stream .= "<e600> <e6ff> <e600>\n";
  11244. $stream .= "<e700> <e7ff> <e700>\n";
  11245. $stream .= "<e800> <e8ff> <e800>\n";
  11246. $stream .= "<e900> <e9ff> <e900>\n";
  11247. $stream .= "<ea00> <eaff> <ea00>\n";
  11248. $stream .= "<eb00> <ebff> <eb00>\n";
  11249. $stream .= "<ec00> <ecff> <ec00>\n";
  11250. $stream .= "<ed00> <edff> <ed00>\n";
  11251. $stream .= "<ee00> <eeff> <ee00>\n";
  11252. $stream .= "<ef00> <efff> <ef00>\n";
  11253. $stream .= "<f000> <f0ff> <f000>\n";
  11254. $stream .= "<f100> <f1ff> <f100>\n";
  11255. $stream .= "<f200> <f2ff> <f200>\n";
  11256. $stream .= "<f300> <f3ff> <f300>\n";
  11257. $stream .= "<f400> <f4ff> <f400>\n";
  11258. $stream .= "<f500> <f5ff> <f500>\n";
  11259. $stream .= "<f600> <f6ff> <f600>\n";
  11260. $stream .= "<f700> <f7ff> <f700>\n";
  11261. $stream .= "<f800> <f8ff> <f800>\n";
  11262. $stream .= "<f900> <f9ff> <f900>\n";
  11263. $stream .= "<fa00> <faff> <fa00>\n";
  11264. $stream .= "<fb00> <fbff> <fb00>\n";
  11265. $stream .= "<fc00> <fcff> <fc00>\n";
  11266. $stream .= "<fd00> <fdff> <fd00>\n";
  11267. $stream .= "<fe00> <feff> <fe00>\n";
  11268. $stream .= "<ff00> <ffff> <ff00>\n";
  11269. $stream .= "endbfrange\n";
  11270. $stream .= "endcmap\n";
  11271. $stream .= "CMapName currentdict /CMap defineresource pop\n";
  11272. $stream .= "end\n";
  11273. $stream .= "end";
  11274. // ToUnicode Object
  11275. $this->_newobj();
  11276. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  11277. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  11278. $stream = $this->_getrawstream($stream);
  11279. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  11280. // CIDFontType2
  11281. // A CIDFont whose glyph descriptions are based on TrueType font technology
  11282. $oid = $this->_newobj();
  11283. $out = '<< /Type /Font';
  11284. $out .= ' /Subtype /CIDFontType2';
  11285. $out .= ' /BaseFont /'.$fontname;
  11286. // A dictionary containing entries that define the character collection of the CIDFont.
  11287. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  11288. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  11289. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  11290. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  11291. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  11292. $out .= ' /DW '.$font['dw']; // default width
  11293. $out .= "\n".$this->_putfontwidths($font, 0);
  11294. if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
  11295. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  11296. }
  11297. $out .= ' >>';
  11298. $out .= "\n".'endobj';
  11299. $this->_out($out);
  11300. // Font descriptor
  11301. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  11302. $this->_newobj();
  11303. $out = '<< /Type /FontDescriptor';
  11304. $out .= ' /FontName /'.$fontname;
  11305. foreach ($font['desc'] as $key => $value) {
  11306. if (is_float($value)) {
  11307. $value = sprintf('%.3F', $value);
  11308. }
  11309. $out .= ' /'.$key.' '.$value;
  11310. }
  11311. $fontdir = false;
  11312. if (!$this->empty_string($font['file'])) {
  11313. // A stream containing a TrueType font
  11314. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  11315. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  11316. }
  11317. $out .= ' >>';
  11318. $out .= "\n".'endobj';
  11319. $this->_out($out);
  11320. if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
  11321. $this->_newobj();
  11322. // Embed CIDToGIDMap
  11323. // A specification of the mapping from CIDs to glyph indices
  11324. // search and get CTG font file to embedd
  11325. $ctgfile = strtolower($font['ctg']);
  11326. // search and get ctg font file to embedd
  11327. $fontfile = '';
  11328. // search files on various directories
  11329. if (($fontdir !== false) AND file_exists($fontdir.$ctgfile)) {
  11330. $fontfile = $fontdir.$ctgfile;
  11331. } elseif (file_exists($this->_getfontpath().$ctgfile)) {
  11332. $fontfile = $this->_getfontpath().$ctgfile;
  11333. } elseif (file_exists($ctgfile)) {
  11334. $fontfile = $ctgfile;
  11335. }
  11336. if ($this->empty_string($fontfile)) {
  11337. $this->Error('Font file not found: '.$ctgfile);
  11338. }
  11339. $stream = $this->_getrawstream(file_get_contents($fontfile));
  11340. $out = '<< /Length '.strlen($stream).'';
  11341. if (substr($fontfile, -2) == '.z') { // check file extension
  11342. // Decompresses data encoded using the public-domain
  11343. // zlib/deflate compression method, reproducing the
  11344. // original text or binary data
  11345. $out .= ' /Filter /FlateDecode';
  11346. }
  11347. $out .= ' >>';
  11348. $out .= ' stream'."\n".$stream."\n".'endstream';
  11349. $out .= "\n".'endobj';
  11350. $this->_out($out);
  11351. }
  11352. }
  11353. /**
  11354. * Output CID-0 fonts.
  11355. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  11356. * @param $font (array) font data
  11357. * @protected
  11358. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  11359. * @since 3.2.000 (2008-06-23)
  11360. */
  11361. protected function _putcidfont0($font) {
  11362. $cidoffset = 0;
  11363. if (!isset($font['cw'][1])) {
  11364. $cidoffset = 31;
  11365. }
  11366. if (isset($font['cidinfo']['uni2cid'])) {
  11367. // convert unicode to cid.
  11368. $uni2cid = $font['cidinfo']['uni2cid'];
  11369. $cw = array();
  11370. foreach ($font['cw'] as $uni => $width) {
  11371. if (isset($uni2cid[$uni])) {
  11372. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  11373. } elseif ($uni < 256) {
  11374. $cw[$uni] = $width;
  11375. } // else unknown character
  11376. }
  11377. $font = array_merge($font, array('cw' => $cw));
  11378. }
  11379. $name = $font['name'];
  11380. $enc = $font['enc'];
  11381. if ($enc) {
  11382. $longname = $name.'-'.$enc;
  11383. } else {
  11384. $longname = $name;
  11385. }
  11386. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  11387. $out .= '<</Type /Font';
  11388. $out .= ' /Subtype /Type0';
  11389. $out .= ' /BaseFont /'.$longname;
  11390. $out .= ' /Name /F'.$font['i'];
  11391. if ($enc) {
  11392. $out .= ' /Encoding /'.$enc;
  11393. }
  11394. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  11395. $out .= ' >>';
  11396. $out .= "\n".'endobj';
  11397. $this->_out($out);
  11398. $oid = $this->_newobj();
  11399. $out = '<</Type /Font';
  11400. $out .= ' /Subtype /CIDFontType0';
  11401. $out .= ' /BaseFont /'.$name;
  11402. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  11403. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  11404. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  11405. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  11406. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  11407. $out .= ' /DW '.$font['dw'];
  11408. $out .= "\n".$this->_putfontwidths($font, $cidoffset);
  11409. $out .= ' >>';
  11410. $out .= "\n".'endobj';
  11411. $this->_out($out);
  11412. $this->_newobj();
  11413. $s = '<</Type /FontDescriptor /FontName /'.$name;
  11414. foreach ($font['desc'] as $k => $v) {
  11415. if ($k != 'Style') {
  11416. if (is_float($v)) {
  11417. $v = sprintf('%.3F', $v);
  11418. }
  11419. $s .= ' /'.$k.' '.$v.'';
  11420. }
  11421. }
  11422. $s .= '>>';
  11423. $s .= "\n".'endobj';
  11424. $this->_out($s);
  11425. }
  11426. /**
  11427. * Output images.
  11428. * @protected
  11429. */
  11430. protected function _putimages() {
  11431. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  11432. foreach ($this->imagekeys as $file) {
  11433. $info = $this->getImageBuffer($file);
  11434. // set object for alternate images array
  11435. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  11436. $altoid = $this->_newobj();
  11437. $out = '[';
  11438. foreach ($info['altimgs'] as $altimage) {
  11439. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  11440. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  11441. $out .= ' /DefaultForPrinting';
  11442. if ($altimage[1] === true) {
  11443. $out .= ' true';
  11444. } else {
  11445. $out .= ' false';
  11446. }
  11447. $out .= ' >>';
  11448. }
  11449. }
  11450. $out .= ' ]';
  11451. $out .= "\n".'endobj';
  11452. $this->_out($out);
  11453. }
  11454. // set image object
  11455. $oid = $this->_newobj();
  11456. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  11457. $this->setImageSubBuffer($file, 'n', $this->n);
  11458. $out = '<</Type /XObject';
  11459. $out .= ' /Subtype /Image';
  11460. $out .= ' /Width '.$info['w'];
  11461. $out .= ' /Height '.$info['h'];
  11462. if (array_key_exists('masked', $info)) {
  11463. $out .= ' /SMask '.($this->n - 1).' 0 R';
  11464. }
  11465. // set color space
  11466. $icc = false;
  11467. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  11468. // ICC Colour Space
  11469. $icc = true;
  11470. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  11471. } elseif ($info['cs'] == 'Indexed') {
  11472. // Indexed Colour Space
  11473. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  11474. } else {
  11475. // Device Colour Space
  11476. $out .= ' /ColorSpace /'.$info['cs'];
  11477. }
  11478. if ($info['cs'] == 'DeviceCMYK') {
  11479. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  11480. }
  11481. $out .= ' /BitsPerComponent '.$info['bpc'];
  11482. if (isset($altoid) AND ($altoid > 0)) {
  11483. // reference to alternate images dictionary
  11484. $out .= ' /Alternates '.$altoid.' 0 R';
  11485. }
  11486. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  11487. // external stream
  11488. $out .= ' /Length 0';
  11489. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  11490. if (isset($info['f'])) {
  11491. $out .= ' /FFilter /'.$info['f'];
  11492. }
  11493. $out .= ' >>';
  11494. $out .= ' stream'."\n".'endstream';
  11495. } else {
  11496. if (isset($info['f'])) {
  11497. $out .= ' /Filter /'.$info['f'];
  11498. }
  11499. if (isset($info['parms'])) {
  11500. $out .= ' '.$info['parms'];
  11501. }
  11502. if (isset($info['trns']) AND is_array($info['trns'])) {
  11503. $trns = '';
  11504. $count_info = count($info['trns']);
  11505. for ($i=0; $i < $count_info; ++$i) {
  11506. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  11507. }
  11508. $out .= ' /Mask ['.$trns.']';
  11509. }
  11510. $stream = $this->_getrawstream($info['data']);
  11511. $out .= ' /Length '.strlen($stream).' >>';
  11512. $out .= ' stream'."\n".$stream."\n".'endstream';
  11513. }
  11514. $out .= "\n".'endobj';
  11515. $this->_out($out);
  11516. if ($icc) {
  11517. // ICC colour profile
  11518. $this->_newobj();
  11519. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  11520. $icc = $this->_getrawstream($icc);
  11521. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  11522. } elseif ($info['cs'] == 'Indexed') {
  11523. // colour palette
  11524. $this->_newobj();
  11525. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  11526. $pal = $this->_getrawstream($pal);
  11527. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  11528. }
  11529. }
  11530. }
  11531. /**
  11532. * Output Form XObjects Templates.
  11533. * @author Nicola Asuni
  11534. * @since 5.8.017 (2010-08-24)
  11535. * @protected
  11536. * @see startTemplate(), endTemplate(), printTemplate()
  11537. */
  11538. protected function _putxobjects() {
  11539. foreach ($this->xobjects as $key => $data) {
  11540. if (isset($data['outdata'])) {
  11541. $stream = trim($data['outdata']);
  11542. $out = $this->_getobj($data['n'])."\n";
  11543. $out .= '<<';
  11544. $out .= ' /Type /XObject';
  11545. $out .= ' /Subtype /Form';
  11546. $out .= ' /FormType 1';
  11547. if ($this->compress) {
  11548. $stream = gzcompress($stream);
  11549. $out .= ' /Filter /FlateDecode';
  11550. }
  11551. $out .= sprintf(' /BBox [%.2F %.2F %.2F %.2F]', ($data['x'] * $this->k), (-$data['y'] * $this->k), (($data['w'] + $data['x']) * $this->k), (($data['h'] - $data['y']) * $this->k));
  11552. $out .= ' /Matrix [1 0 0 1 0 0]';
  11553. $out .= ' /Resources <<';
  11554. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  11555. if (!$this->pdfa_mode) {
  11556. // transparency
  11557. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  11558. $out .= ' /ExtGState <<';
  11559. foreach ($data['extgstates'] as $k => $extgstate) {
  11560. if (isset($this->extgstates[$k]['name'])) {
  11561. $out .= ' /'.$this->extgstates[$k]['name'];
  11562. } else {
  11563. $out .= ' /GS'.$k;
  11564. }
  11565. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  11566. }
  11567. $out .= ' >>';
  11568. }
  11569. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  11570. $gp = '';
  11571. $gs = '';
  11572. foreach ($data['gradients'] as $id => $grad) {
  11573. // gradient patterns
  11574. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  11575. // gradient shadings
  11576. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  11577. }
  11578. $out .= ' /Pattern <<'.$gp.' >>';
  11579. $out .= ' /Shading <<'.$gs.' >>';
  11580. }
  11581. }
  11582. // spot colors
  11583. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  11584. $out .= ' /ColorSpace <<';
  11585. foreach ($data['spot_colors'] as $name => $color) {
  11586. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  11587. }
  11588. $out .= ' >>';
  11589. }
  11590. // fonts
  11591. if (!empty($data['fonts'])) {
  11592. $out .= ' /Font <<';
  11593. foreach ($data['fonts'] as $fontkey => $fontid) {
  11594. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  11595. }
  11596. $out .= ' >>';
  11597. }
  11598. // images or nested xobjects
  11599. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  11600. $out .= ' /XObject <<';
  11601. foreach ($data['images'] as $imgid) {
  11602. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  11603. }
  11604. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  11605. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  11606. }
  11607. $out .= ' >>';
  11608. }
  11609. $out .= ' >>'; //end resources
  11610. if (isset($data['group']) AND ($data['group'] !== false)) {
  11611. // set transparency group
  11612. $out .= ' /Group << /Type /Group /S /Transparency';
  11613. if (is_array($data['group'])) {
  11614. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  11615. $out .= ' /CS /'.$data['group']['CS'];
  11616. }
  11617. if (isset($data['group']['I'])) {
  11618. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  11619. }
  11620. if (isset($data['group']['K'])) {
  11621. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  11622. }
  11623. }
  11624. $out .= ' >>';
  11625. }
  11626. $stream = $this->_getrawstream($stream, $data['n']);
  11627. $out .= ' /Length '.strlen($stream);
  11628. $out .= ' >>';
  11629. $out .= ' stream'."\n".$stream."\n".'endstream';
  11630. $out .= "\n".'endobj';
  11631. $this->_out($out);
  11632. }
  11633. }
  11634. }
  11635. /**
  11636. * Output Spot Colors Resources.
  11637. * @protected
  11638. * @since 4.0.024 (2008-09-12)
  11639. */
  11640. protected function _putspotcolors() {
  11641. foreach ($this->spot_colors as $name => $color) {
  11642. $this->_newobj();
  11643. $this->spot_colors[$name]['n'] = $this->n;
  11644. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  11645. $out .= ' /DeviceCMYK <<';
  11646. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  11647. $out .= ' '.sprintf('/C1 [%.4F %.4F %.4F %.4F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  11648. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  11649. $out .= "\n".'endobj';
  11650. $this->_out($out);
  11651. }
  11652. }
  11653. /**
  11654. * Return XObjects Dictionary.
  11655. * @return string XObjects dictionary
  11656. * @protected
  11657. * @since 5.8.014 (2010-08-23)
  11658. */
  11659. protected function _getxobjectdict() {
  11660. $out = '';
  11661. foreach ($this->xobjects as $id => $objid) {
  11662. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  11663. }
  11664. return $out;
  11665. }
  11666. /**
  11667. * Output Resources Dictionary.
  11668. * @protected
  11669. */
  11670. protected function _putresourcedict() {
  11671. $out = $this->_getobj(2)."\n";
  11672. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  11673. $out .= ' /Font <<';
  11674. foreach ($this->fontkeys as $fontkey) {
  11675. $font = $this->getFontBuffer($fontkey);
  11676. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  11677. }
  11678. $out .= ' >>';
  11679. $out .= ' /XObject <<';
  11680. $out .= $this->_getxobjectdict();
  11681. $out .= ' >>';
  11682. // layers
  11683. if (!empty($this->pdflayers)) {
  11684. $out .= ' /Properties <<';
  11685. foreach ($this->pdflayers as $layer) {
  11686. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  11687. }
  11688. $out .= ' >>';
  11689. }
  11690. if (!$this->pdfa_mode) {
  11691. // transparency
  11692. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  11693. $out .= ' /ExtGState <<';
  11694. foreach ($this->extgstates as $k => $extgstate) {
  11695. if (isset($extgstate['name'])) {
  11696. $out .= ' /'.$extgstate['name'];
  11697. } else {
  11698. $out .= ' /GS'.$k;
  11699. }
  11700. $out .= ' '.$extgstate['n'].' 0 R';
  11701. }
  11702. $out .= ' >>';
  11703. }
  11704. if (isset($this->gradients) AND !empty($this->gradients)) {
  11705. $gp = '';
  11706. $gs = '';
  11707. foreach ($this->gradients as $id => $grad) {
  11708. // gradient patterns
  11709. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  11710. // gradient shadings
  11711. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  11712. }
  11713. $out .= ' /Pattern <<'.$gp.' >>';
  11714. $out .= ' /Shading <<'.$gs.' >>';
  11715. }
  11716. }
  11717. // spot colors
  11718. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  11719. $out .= ' /ColorSpace <<';
  11720. foreach ($this->spot_colors as $color) {
  11721. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  11722. }
  11723. $out .= ' >>';
  11724. }
  11725. $out .= ' >>';
  11726. $out .= "\n".'endobj';
  11727. $this->_out($out);
  11728. }
  11729. /**
  11730. * Output Resources.
  11731. * @protected
  11732. */
  11733. protected function _putresources() {
  11734. $this->_putextgstates();
  11735. $this->_putocg();
  11736. $this->_putfonts();
  11737. $this->_putimages();
  11738. $this->_putspotcolors();
  11739. $this->_putshaders();
  11740. $this->_putxobjects();
  11741. $this->_putresourcedict();
  11742. $this->_putdests();
  11743. $this->_putbookmarks();
  11744. $this->_putEmbeddedFiles();
  11745. $this->_putannotsobjs();
  11746. $this->_putjavascript();
  11747. $this->_putencryption();
  11748. }
  11749. /**
  11750. * Adds some Metadata information (Document Information Dictionary)
  11751. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  11752. * @return int object id
  11753. * @protected
  11754. */
  11755. protected function _putinfo() {
  11756. $oid = $this->_newobj();
  11757. $out = '<<';
  11758. // store current isunicode value
  11759. $prev_isunicode = $this->isunicode;
  11760. if ($this->docinfounicode) {
  11761. $this->isunicode = true;
  11762. }
  11763. if (!$this->empty_string($this->title)) {
  11764. // The document's title.
  11765. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  11766. }
  11767. if (!$this->empty_string($this->author)) {
  11768. // The name of the person who created the document.
  11769. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  11770. }
  11771. if (!$this->empty_string($this->subject)) {
  11772. // The subject of the document.
  11773. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  11774. }
  11775. if (!$this->empty_string($this->keywords)) {
  11776. // Keywords associated with the document.
  11777. $out .= ' /Keywords '.$this->_textstring($this->keywords.' TCPDF', $oid);
  11778. }
  11779. if (!$this->empty_string($this->creator)) {
  11780. // 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.
  11781. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  11782. }
  11783. // restore previous isunicode value
  11784. $this->isunicode = $prev_isunicode;
  11785. // default producer
  11786. $out .= ' /Producer '.$this->_textstring("\x54\x43\x50\x44\x46\x20".$this->tcpdf_version."\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29", $oid);
  11787. // The date and time the document was created, in human-readable form
  11788. $out .= ' /CreationDate '.$this->_datestring();
  11789. // The date and time the document was most recently modified, in human-readable form
  11790. $out .= ' /ModDate '.$this->_datestring();
  11791. // A name object indicating whether the document has been modified to include trapping information
  11792. $out .= ' /Trapped /False';
  11793. $out .= ' >>';
  11794. $out .= "\n".'endobj';
  11795. $this->_out($out);
  11796. return $oid;
  11797. }
  11798. /**
  11799. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  11800. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  11801. * @param $xmp (string) Custom XMP data.
  11802. * @since 5.9.128 (2011-10-06)
  11803. * @public
  11804. */
  11805. public function setExtraXMP($xmp) {
  11806. $this->custom_xmp = $xmp;
  11807. }
  11808. /**
  11809. * Put XMP data object and return ID.
  11810. * @return (int) The object ID.
  11811. * @since 5.9.121 (2011-09-28)
  11812. * @protected
  11813. */
  11814. protected function _putXMP() {
  11815. $oid = $this->_newobj();
  11816. // store current isunicode value
  11817. $prev_isunicode = $this->isunicode;
  11818. $this->isunicode = true;
  11819. $prev_encrypted = $this->encrypted;
  11820. $this->encrypted = false;
  11821. // set XMP data
  11822. $xmp = '<?xpacket begin="'.$this->unichr(0xfeff).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  11823. $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";
  11824. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  11825. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  11826. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  11827. $xmp .= "\t\t\t".'<dc:title>'."\n";
  11828. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  11829. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.$this->_escapeXML($this->title).'</rdf:li>'."\n";
  11830. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  11831. $xmp .= "\t\t\t".'</dc:title>'."\n";
  11832. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  11833. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  11834. $xmp .= "\t\t\t\t\t".'<rdf:li>'.$this->_escapeXML($this->author).'</rdf:li>'."\n";
  11835. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  11836. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  11837. $xmp .= "\t\t\t".'<dc:description>'."\n";
  11838. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  11839. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.$this->_escapeXML($this->subject).'</rdf:li>'."\n";
  11840. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  11841. $xmp .= "\t\t\t".'</dc:description>'."\n";
  11842. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  11843. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  11844. $xmp .= "\t\t\t\t\t".'<rdf:li>'.$this->_escapeXML($this->keywords).'</rdf:li>'."\n";
  11845. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  11846. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  11847. $xmp .= "\t\t".'</rdf:Description>'."\n";
  11848. // convert date format
  11849. $docdate = substr($this->doc_date, 0, 4).'-'.substr($this->doc_date, 4, 2).'-'.substr($this->doc_date, 6, 2);
  11850. $docdate .= 'T'.substr($this->doc_date, 8, 2).':'.substr($this->doc_date, 10, 2).':'.substr($this->doc_date, 12, 2);
  11851. $docdate .= '+'.substr($this->doc_date, 15, 2).':'.substr($this->doc_date, 18, 2);
  11852. $docdate = $this->_escapeXML($docdate);
  11853. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  11854. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$docdate.'</xmp:CreateDate>'."\n";
  11855. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  11856. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docdate.'</xmp:ModifyDate>'."\n";
  11857. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$docdate.'</xmp:MetadataDate>'."\n";
  11858. $xmp .= "\t\t".'</rdf:Description>'."\n";
  11859. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  11860. $xmp .= "\t\t\t".'<pdf:Keywords>'.$this->_escapeXML($this->keywords).' TCPDF</pdf:Keywords>'."\n";
  11861. $xmp .= "\t\t\t".'<pdf:Producer>'.$this->_escapeXML("\x54\x43\x50\x44\x46\x20".$this->tcpdf_version."\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29").'</pdf:Producer>'."\n";
  11862. $xmp .= "\t\t".'</rdf:Description>'."\n";
  11863. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  11864. $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);
  11865. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  11866. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  11867. $xmp .= "\t\t".'</rdf:Description>'."\n";
  11868. if ($this->pdfa_mode) {
  11869. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  11870. $xmp .= "\t\t\t".'<pdfaid:part>1</pdfaid:part>'."\n";
  11871. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  11872. $xmp .= "\t\t".'</rdf:Description>'."\n";
  11873. }
  11874. // XMP extension schemas
  11875. $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";
  11876. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  11877. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  11878. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11879. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  11880. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  11881. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  11882. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  11883. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11884. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  11885. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  11886. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  11887. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  11888. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  11889. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11890. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  11891. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  11892. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  11893. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  11894. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  11895. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  11896. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  11897. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  11898. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11899. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  11900. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  11901. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  11902. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  11903. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  11904. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11905. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  11906. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  11907. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  11908. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  11909. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  11910. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11911. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  11912. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  11913. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  11914. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  11915. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  11916. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  11917. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  11918. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  11919. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  11920. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  11921. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  11922. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  11923. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  11924. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  11925. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  11926. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  11927. $xmp .= "\t\t".'</rdf:Description>'."\n";
  11928. $xmp .= "\t".'</rdf:RDF>'."\n";
  11929. $xmp .= $this->custom_xmp;
  11930. $xmp .= '</x:xmpmeta>'."\n";
  11931. $xmp .= '<?xpacket end="w"?>';
  11932. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  11933. // restore previous isunicode value
  11934. $this->isunicode = $prev_isunicode;
  11935. $this->encrypted = $prev_encrypted;
  11936. $this->_out($out);
  11937. return $oid;
  11938. }
  11939. /**
  11940. * Output Catalog.
  11941. * @return int object id
  11942. * @protected
  11943. */
  11944. protected function _putcatalog() {
  11945. // put XMP
  11946. $xmpobj = $this->_putXMP();
  11947. // if required, add standard sRGB_IEC61966-2.1 blackscaled ICC colour profile
  11948. if ($this->pdfa_mode OR $this->force_srgb) {
  11949. $iccobj = $this->_newobj();
  11950. $icc = file_get_contents(dirname(__FILE__).'/sRGB.icc');
  11951. $filter = '';
  11952. if ($this->compress) {
  11953. $filter = ' /Filter /FlateDecode';
  11954. $icc = gzcompress($icc);
  11955. }
  11956. $icc = $this->_getrawstream($icc);
  11957. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  11958. }
  11959. // start catalog
  11960. $oid = $this->_newobj();
  11961. $out = '<< /Type /Catalog';
  11962. $out .= ' /Version /'.$this->PDFVersion;
  11963. //$out .= ' /Extensions <<>>';
  11964. $out .= ' /Pages 1 0 R';
  11965. //$out .= ' /PageLabels ' //...;
  11966. $out .= ' /Names <<';
  11967. if ((!$this->pdfa_mode) AND ((!empty($this->javascript)) OR (!empty($this->js_objects)))) {
  11968. $out .= ' /JavaScript '.($this->n_js).' 0 R';
  11969. }
  11970. $out .= ' >>';
  11971. if (!empty($this->dests)) {
  11972. $out .= ' /Dests '.$this->n_dests.' 0 R';
  11973. }
  11974. $out .= $this->_putviewerpreferences();
  11975. if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
  11976. $out .= ' /PageLayout /'.$this->LayoutMode;
  11977. }
  11978. if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
  11979. $out .= ' /PageMode /'.$this->PageMode;
  11980. }
  11981. if (count($this->outlines) > 0) {
  11982. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  11983. $out .= ' /PageMode /UseOutlines';
  11984. }
  11985. //$out .= ' /Threads []';
  11986. if ($this->ZoomMode == 'fullpage') {
  11987. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  11988. } elseif ($this->ZoomMode == 'fullwidth') {
  11989. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  11990. } elseif ($this->ZoomMode == 'real') {
  11991. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  11992. } elseif (!is_string($this->ZoomMode)) {
  11993. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %.2F]', ($this->ZoomMode / 100));
  11994. }
  11995. //$out .= ' /AA <<>>';
  11996. //$out .= ' /URI <<>>';
  11997. $out .= ' /Metadata '.$xmpobj.' 0 R';
  11998. //$out .= ' /StructTreeRoot <<>>';
  11999. //$out .= ' /MarkInfo <<>>';
  12000. if (isset($this->l['a_meta_language'])) {
  12001. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  12002. }
  12003. //$out .= ' /SpiderInfo <<>>';
  12004. // set OutputIntent to sRGB IEC61966-2.1 if required
  12005. if ($this->pdfa_mode OR $this->force_srgb) {
  12006. $out .= ' /OutputIntents [<<';
  12007. $out .= ' /Type /OutputIntent';
  12008. $out .= ' /S /GTS_PDFA1';
  12009. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  12010. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  12011. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  12012. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  12013. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  12014. $out .= ' >>]';
  12015. }
  12016. //$out .= ' /PieceInfo <<>>';
  12017. if (!empty($this->pdflayers)) {
  12018. $lyrobjs = '';
  12019. $lyrobjs_print = '';
  12020. $lyrobjs_view = '';
  12021. foreach ($this->pdflayers as $layer) {
  12022. $lyrobjs .= ' '.$layer['objid'].' 0 R';
  12023. if ($layer['print']) {
  12024. $lyrobjs_print .= ' '.$layer['objid'].' 0 R';
  12025. }
  12026. if ($layer['view']) {
  12027. $lyrobjs_view .= ' '.$layer['objid'].' 0 R';
  12028. }
  12029. }
  12030. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  12031. $out .= ' /D <<';
  12032. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  12033. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  12034. $out .= ' /BaseState /ON';
  12035. $out .= ' /ON ['.$lyrobjs_print.']';
  12036. $out .= ' /OFF ['.$lyrobjs_view.']';
  12037. $out .= ' /Intent /View';
  12038. $out .= ' /AS [';
  12039. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  12040. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  12041. $out .= ' ]';
  12042. $out .= ' /Order ['.$lyrobjs.']';
  12043. $out .= ' /ListMode /AllPages';
  12044. //$out .= ' /RBGroups ['..']';
  12045. //$out .= ' /Locked ['..']';
  12046. $out .= ' >>';
  12047. $out .= ' >>';
  12048. }
  12049. // AcroForm
  12050. if (!empty($this->form_obj_id) OR ($this->sign AND isset($this->signature_data['cert_type']))) {
  12051. $out .= ' /AcroForm <<';
  12052. $objrefs = '';
  12053. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12054. // set reference for signature object
  12055. $objrefs .= $this->sig_obj_id.' 0 R';
  12056. }
  12057. if (!empty($this->empty_signature_appearance)) {
  12058. foreach ($this->empty_signature_appearance as $esa) {
  12059. // set reference for empty signature objects
  12060. $objrefs .= ' '.$esa['objid'].' 0 R';
  12061. }
  12062. }
  12063. if (!empty($this->form_obj_id)) {
  12064. foreach($this->form_obj_id as $objid) {
  12065. $objrefs .= ' '.$objid.' 0 R';
  12066. }
  12067. }
  12068. $out .= ' /Fields ['.$objrefs.']';
  12069. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  12070. $out .= ' /NeedAppearances false';
  12071. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12072. if ($this->signature_data['cert_type'] > 0) {
  12073. $out .= ' /SigFlags 3';
  12074. } else {
  12075. $out .= ' /SigFlags 1';
  12076. }
  12077. }
  12078. //$out .= ' /CO ';
  12079. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  12080. $out .= ' /DR <<';
  12081. $out .= ' /Font <<';
  12082. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  12083. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  12084. }
  12085. $out .= ' >> >>';
  12086. }
  12087. $font = $this->getFontBuffer('helvetica');
  12088. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  12089. $out .= ' /Q '.(($this->rtl)?'2':'0');
  12090. //$out .= ' /XFA ';
  12091. $out .= ' >>';
  12092. // signatures
  12093. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12094. if ($this->signature_data['cert_type'] > 0) {
  12095. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  12096. } else {
  12097. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  12098. }
  12099. }
  12100. }
  12101. //$out .= ' /Legal <<>>';
  12102. //$out .= ' /Requirements []';
  12103. //$out .= ' /Collection <<>>';
  12104. //$out .= ' /NeedsRendering true';
  12105. $out .= ' >>';
  12106. $out .= "\n".'endobj';
  12107. $this->_out($out);
  12108. return $oid;
  12109. }
  12110. /**
  12111. * Output viewer preferences.
  12112. * @return string for viewer preferences
  12113. * @author Nicola asuni
  12114. * @since 3.1.000 (2008-06-09)
  12115. * @protected
  12116. */
  12117. protected function _putviewerpreferences() {
  12118. $out = ' /ViewerPreferences <<';
  12119. if ($this->rtl) {
  12120. $out .= ' /Direction /R2L';
  12121. } else {
  12122. $out .= ' /Direction /L2R';
  12123. }
  12124. if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
  12125. $out .= ' /HideToolbar true';
  12126. }
  12127. if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
  12128. $out .= ' /HideMenubar true';
  12129. }
  12130. if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
  12131. $out .= ' /HideWindowUI true';
  12132. }
  12133. if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
  12134. $out .= ' /FitWindow true';
  12135. }
  12136. if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
  12137. $out .= ' /CenterWindow true';
  12138. }
  12139. if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
  12140. $out .= ' /DisplayDocTitle true';
  12141. }
  12142. if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
  12143. $out .= ' /NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'];
  12144. }
  12145. if (isset($this->viewer_preferences['ViewArea'])) {
  12146. $out .= ' /ViewArea /'.$this->viewer_preferences['ViewArea'];
  12147. }
  12148. if (isset($this->viewer_preferences['ViewClip'])) {
  12149. $out .= ' /ViewClip /'.$this->viewer_preferences['ViewClip'];
  12150. }
  12151. if (isset($this->viewer_preferences['PrintArea'])) {
  12152. $out .= ' /PrintArea /'.$this->viewer_preferences['PrintArea'];
  12153. }
  12154. if (isset($this->viewer_preferences['PrintClip'])) {
  12155. $out .= ' /PrintClip /'.$this->viewer_preferences['PrintClip'];
  12156. }
  12157. if (isset($this->viewer_preferences['PrintScaling'])) {
  12158. $out .= ' /PrintScaling /'.$this->viewer_preferences['PrintScaling'];
  12159. }
  12160. if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
  12161. $out .= ' /Duplex /'.$this->viewer_preferences['Duplex'];
  12162. }
  12163. if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
  12164. if ($this->viewer_preferences['PickTrayByPDFSize']) {
  12165. $out .= ' /PickTrayByPDFSize true';
  12166. } else {
  12167. $out .= ' /PickTrayByPDFSize false';
  12168. }
  12169. }
  12170. if (isset($this->viewer_preferences['PrintPageRange'])) {
  12171. $PrintPageRangeNum = '';
  12172. foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
  12173. $PrintPageRangeNum .= ' '.($v - 1).'';
  12174. }
  12175. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  12176. }
  12177. if (isset($this->viewer_preferences['NumCopies'])) {
  12178. $out .= ' /NumCopies '.intval($this->viewer_preferences['NumCopies']);
  12179. }
  12180. $out .= ' >>';
  12181. return $out;
  12182. }
  12183. /**
  12184. * Output PDF File Header (7.5.2).
  12185. * @protected
  12186. */
  12187. protected function _putheader() {
  12188. $this->_out('%PDF-'.$this->PDFVersion);
  12189. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  12190. }
  12191. /**
  12192. * Output end of document (EOF).
  12193. * @protected
  12194. */
  12195. protected function _enddoc() {
  12196. $this->state = 1;
  12197. $this->_putheader();
  12198. $this->_putpages();
  12199. $this->_putresources();
  12200. // empty signature fields
  12201. if (!empty($this->empty_signature_appearance)) {
  12202. foreach ($this->empty_signature_appearance as $key => $esa) {
  12203. // widget annotation for empty signature
  12204. $out = $this->_getobj($esa['objid'])."\n";
  12205. $out .= '<< /Type /Annot';
  12206. $out .= ' /Subtype /Widget';
  12207. $out .= ' /Rect ['.$esa['rect'].']';
  12208. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  12209. $out .= ' /F 4';
  12210. $out .= ' /FT /Sig';
  12211. $signame = sprintf('Signature_%03d', ($key + 1));
  12212. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  12213. $out .= ' /Ff 0';
  12214. $out .= ' >>';
  12215. $out .= "\n".'endobj';
  12216. $this->_out($out);
  12217. }
  12218. }
  12219. // Signature
  12220. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12221. // widget annotation for signature
  12222. $out = $this->_getobj($this->sig_obj_id)."\n";
  12223. $out .= '<< /Type /Annot';
  12224. $out .= ' /Subtype /Widget';
  12225. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  12226. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  12227. $out .= ' /F 4';
  12228. $out .= ' /FT /Sig';
  12229. $out .= ' /T '.$this->_textstring('Signature_000', $this->sig_obj_id);
  12230. $out .= ' /Ff 0';
  12231. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  12232. $out .= ' >>';
  12233. $out .= "\n".'endobj';
  12234. $this->_out($out);
  12235. // signature
  12236. $this->_putsignature();
  12237. }
  12238. // Info
  12239. $objid_info = $this->_putinfo();
  12240. // Catalog
  12241. $objid_catalog = $this->_putcatalog();
  12242. // Cross-ref
  12243. $o = $this->bufferlen;
  12244. // XREF section
  12245. $this->_out('xref');
  12246. $this->_out('0 '.($this->n + 1));
  12247. $this->_out('0000000000 65535 f ');
  12248. for ($i=1; $i <= $this->n; ++$i) {
  12249. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  12250. $this->offsets[$i] = $this->offsets[($i - 1)];
  12251. }
  12252. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  12253. }
  12254. // TRAILER
  12255. $out = 'trailer'."\n";
  12256. $out .= '<<';
  12257. $out .= ' /Size '.($this->n + 1);
  12258. $out .= ' /Root '.$objid_catalog.' 0 R';
  12259. $out .= ' /Info '.$objid_info.' 0 R';
  12260. if ($this->encrypted) {
  12261. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  12262. }
  12263. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  12264. $out .= ' >>';
  12265. $this->_out($out);
  12266. $this->_out('startxref');
  12267. $this->_out($o);
  12268. $this->_out('%%EOF');
  12269. $this->state = 3; // end-of-doc
  12270. if ($this->diskcache) {
  12271. // remove temporary files used for images
  12272. foreach ($this->imagekeys as $key) {
  12273. // remove temporary files
  12274. unlink($this->images[$key]);
  12275. }
  12276. foreach ($this->fontkeys as $key) {
  12277. // remove temporary files
  12278. unlink($this->fonts[$key]);
  12279. }
  12280. }
  12281. }
  12282. /**
  12283. * Initialize a new page.
  12284. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  12285. * @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().
  12286. * @protected
  12287. * @see getPageSizeFromFormat(), setPageFormat()
  12288. */
  12289. protected function _beginpage($orientation='', $format='') {
  12290. ++$this->page;
  12291. $this->setPageBuffer($this->page, '');
  12292. // initialize array for graphics tranformation positions inside a page buffer
  12293. $this->transfmrk[$this->page] = array();
  12294. $this->state = 2;
  12295. if ($this->empty_string($orientation)) {
  12296. if (isset($this->CurOrientation)) {
  12297. $orientation = $this->CurOrientation;
  12298. } elseif ($this->fwPt > $this->fhPt) {
  12299. // landscape
  12300. $orientation = 'L';
  12301. } else {
  12302. // portrait
  12303. $orientation = 'P';
  12304. }
  12305. }
  12306. if ($this->empty_string($format)) {
  12307. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  12308. $this->setPageOrientation($orientation);
  12309. } else {
  12310. $this->setPageFormat($format, $orientation);
  12311. }
  12312. if ($this->rtl) {
  12313. $this->x = $this->w - $this->rMargin;
  12314. } else {
  12315. $this->x = $this->lMargin;
  12316. }
  12317. $this->y = $this->tMargin;
  12318. if (isset($this->newpagegroup[$this->page])) {
  12319. // start a new group
  12320. $this->currpagegroup = $this->newpagegroup[$this->page];
  12321. $this->pagegroups[$this->currpagegroup] = 1;
  12322. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  12323. ++$this->pagegroups[$this->currpagegroup];
  12324. }
  12325. }
  12326. /**
  12327. * Mark end of page.
  12328. * @protected
  12329. */
  12330. protected function _endpage() {
  12331. $this->setVisibility('all');
  12332. $this->state = 1;
  12333. }
  12334. /**
  12335. * Begin a new object and return the object number.
  12336. * @return int object number
  12337. * @protected
  12338. */
  12339. protected function _newobj() {
  12340. $this->_out($this->_getobj());
  12341. return $this->n;
  12342. }
  12343. /**
  12344. * Return the starting object string for the selected object ID.
  12345. * @param $objid (int) Object ID (leave empty to get a new ID).
  12346. * @return string the starting object string
  12347. * @protected
  12348. * @since 5.8.009 (2010-08-20)
  12349. */
  12350. protected function _getobj($objid='') {
  12351. if ($objid === '') {
  12352. ++$this->n;
  12353. $objid = $this->n;
  12354. }
  12355. $this->offsets[$objid] = $this->bufferlen;
  12356. return $objid.' 0 obj';
  12357. }
  12358. /**
  12359. * Underline text.
  12360. * @param $x (int) X coordinate
  12361. * @param $y (int) Y coordinate
  12362. * @param $txt (string) text to underline
  12363. * @protected
  12364. */
  12365. protected function _dounderline($x, $y, $txt) {
  12366. $w = $this->GetStringWidth($txt);
  12367. return $this->_dounderlinew($x, $y, $w);
  12368. }
  12369. /**
  12370. * Underline for rectangular text area.
  12371. * @param $x (int) X coordinate
  12372. * @param $y (int) Y coordinate
  12373. * @param $w (int) width to underline
  12374. * @protected
  12375. * @since 4.8.008 (2009-09-29)
  12376. */
  12377. protected function _dounderlinew($x, $y, $w) {
  12378. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  12379. return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  12380. }
  12381. /**
  12382. * Line through text.
  12383. * @param $x (int) X coordinate
  12384. * @param $y (int) Y coordinate
  12385. * @param $txt (string) text to linethrough
  12386. * @protected
  12387. */
  12388. protected function _dolinethrough($x, $y, $txt) {
  12389. $w = $this->GetStringWidth($txt);
  12390. return $this->_dolinethroughw($x, $y, $w);
  12391. }
  12392. /**
  12393. * Line through for rectangular text area.
  12394. * @param $x (int) X coordinate
  12395. * @param $y (int) Y coordinate
  12396. * @param $w (int) line length (width)
  12397. * @protected
  12398. * @since 4.9.008 (2009-09-29)
  12399. */
  12400. protected function _dolinethroughw($x, $y, $w) {
  12401. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  12402. return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  12403. }
  12404. /**
  12405. * Overline text.
  12406. * @param $x (int) X coordinate
  12407. * @param $y (int) Y coordinate
  12408. * @param $txt (string) text to overline
  12409. * @protected
  12410. * @since 4.9.015 (2010-04-19)
  12411. */
  12412. protected function _dooverline($x, $y, $txt) {
  12413. $w = $this->GetStringWidth($txt);
  12414. return $this->_dooverlinew($x, $y, $w);
  12415. }
  12416. /**
  12417. * Overline for rectangular text area.
  12418. * @param $x (int) X coordinate
  12419. * @param $y (int) Y coordinate
  12420. * @param $w (int) width to overline
  12421. * @protected
  12422. * @since 4.9.015 (2010-04-19)
  12423. */
  12424. protected function _dooverlinew($x, $y, $w) {
  12425. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  12426. return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  12427. }
  12428. /**
  12429. * Read a 4-byte (32 bit) integer from file.
  12430. * @param $f (string) file name.
  12431. * @return 4-byte integer
  12432. * @protected
  12433. */
  12434. protected function _freadint($f) {
  12435. $a = unpack('Ni', fread($f, 4));
  12436. return $a['i'];
  12437. }
  12438. /**
  12439. * Add "\" before "\", "(" and ")"
  12440. * @param $s (string) string to escape.
  12441. * @return string escaped string.
  12442. * @protected
  12443. */
  12444. protected function _escape($s) {
  12445. // the chr(13) substitution fixes the Bugs item #1421290.
  12446. return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
  12447. }
  12448. /**
  12449. * Format a data string for meta information
  12450. * @param $s (string) data string to escape.
  12451. * @param $n (int) object ID
  12452. * @return string escaped string.
  12453. * @protected
  12454. */
  12455. protected function _datastring($s, $n=0) {
  12456. if ($n == 0) {
  12457. $n = $this->n;
  12458. }
  12459. $s = $this->_encrypt_data($n, $s);
  12460. return '('. $this->_escape($s).')';
  12461. }
  12462. /**
  12463. * Returns a formatted date for meta information
  12464. * @param $n (int) object ID
  12465. * @return string escaped date string.
  12466. * @protected
  12467. * @since 4.6.028 (2009-08-25)
  12468. */
  12469. protected function _datestring($n=0) {
  12470. return $this->_datastring('D:'.$this->doc_date, $n);
  12471. }
  12472. /**
  12473. * Format a text string for meta information
  12474. * @param $s (string) string to escape.
  12475. * @param $n (int) object ID
  12476. * @return string escaped string.
  12477. * @protected
  12478. */
  12479. protected function _textstring($s, $n=0) {
  12480. if ($this->isunicode) {
  12481. //Convert string to UTF-16BE
  12482. $s = $this->UTF8ToUTF16BE($s, true);
  12483. }
  12484. return $this->_datastring($s, $n);
  12485. }
  12486. /**
  12487. * THIS METHOD IS DEPRECATED
  12488. * Format a text string
  12489. * @param $s (string) string to escape.
  12490. * @return string escaped string.
  12491. * @protected
  12492. * @deprecated
  12493. */
  12494. protected function _escapetext($s) {
  12495. if ($this->isunicode) {
  12496. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  12497. $s = $this->UTF8ToLatin1($s);
  12498. } else {
  12499. //Convert string to UTF-16BE and reverse RTL language
  12500. $s = $this->utf8StrRev($s, false, $this->tmprtl);
  12501. }
  12502. }
  12503. return $this->_escape($s);
  12504. }
  12505. /**
  12506. * Escape some special characters (&lt; &gt; &amp;) for XML output.
  12507. * @param $str (string) Input string to convert.
  12508. * @return converted string
  12509. * @since 5.9.121 (2011-09-28)
  12510. * @protected
  12511. */
  12512. protected function _escapeXML($str) {
  12513. $replaceTable = array("\0" => '', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;');
  12514. $str = strtr($str, $replaceTable);
  12515. return $str;
  12516. }
  12517. /**
  12518. * get raw output stream.
  12519. * @param $s (string) string to output.
  12520. * @param $n (int) object reference for encryption mode
  12521. * @protected
  12522. * @author Nicola Asuni
  12523. * @since 5.5.000 (2010-06-22)
  12524. */
  12525. protected function _getrawstream($s, $n=0) {
  12526. if ($n <= 0) {
  12527. // default to current object
  12528. $n = $this->n;
  12529. }
  12530. return $this->_encrypt_data($n, $s);
  12531. }
  12532. /**
  12533. * Format output stream (DEPRECATED).
  12534. * @param $s (string) string to output.
  12535. * @param $n (int) object reference for encryption mode
  12536. * @protected
  12537. * @deprecated
  12538. */
  12539. protected function _getstream($s, $n=0) {
  12540. return 'stream'."\n".$this->_getrawstream($s, $n)."\n".'endstream';
  12541. }
  12542. /**
  12543. * Output a stream (DEPRECATED).
  12544. * @param $s (string) string to output.
  12545. * @param $n (int) object reference for encryption mode
  12546. * @protected
  12547. * @deprecated
  12548. */
  12549. protected function _putstream($s, $n=0) {
  12550. $this->_out($this->_getstream($s, $n));
  12551. }
  12552. /**
  12553. * Output a string to the document.
  12554. * @param $s (string) string to output.
  12555. * @protected
  12556. */
  12557. protected function _out($s) {
  12558. if ($this->state == 2) {
  12559. if ($this->inxobj) {
  12560. // we are inside an XObject template
  12561. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  12562. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  12563. // puts data before page footer
  12564. $pagebuff = $this->getPageBuffer($this->page);
  12565. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  12566. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  12567. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  12568. // update footer position
  12569. $this->footerpos[$this->page] += strlen($s."\n");
  12570. } else {
  12571. $this->setPageBuffer($this->page, $s."\n", true);
  12572. }
  12573. } else {
  12574. $this->setBuffer($s."\n");
  12575. }
  12576. }
  12577. /**
  12578. * Converts UTF-8 strings to codepoints array.<br>
  12579. * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
  12580. * Based on: http://www.faqs.org/rfcs/rfc3629.html
  12581. * <pre>
  12582. * Char. number range | UTF-8 octet sequence
  12583. * (hexadecimal) | (binary)
  12584. * --------------------+-----------------------------------------------
  12585. * 0000 0000-0000 007F | 0xxxxxxx
  12586. * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
  12587. * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
  12588. * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  12589. * ---------------------------------------------------------------------
  12590. *
  12591. * ABFN notation:
  12592. * ---------------------------------------------------------------------
  12593. * UTF8-octets = *( UTF8-char )
  12594. * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
  12595. * UTF8-1 = %x00-7F
  12596. * UTF8-2 = %xC2-DF UTF8-tail
  12597. *
  12598. * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
  12599. * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
  12600. * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
  12601. * %xF4 %x80-8F 2( UTF8-tail )
  12602. * UTF8-tail = %x80-BF
  12603. * ---------------------------------------------------------------------
  12604. * </pre>
  12605. * @param $str (string) string to process.
  12606. * @return array containing codepoints (UTF-8 characters values)
  12607. * @protected
  12608. * @author Nicola Asuni
  12609. * @since 1.53.0.TC005 (2005-01-05)
  12610. */
  12611. protected function UTF8StringToArray($str) {
  12612. // build a unique string key
  12613. $strkey = md5($str);
  12614. if (isset($this->cache_UTF8StringToArray[$strkey])) {
  12615. // return cached value
  12616. $chrarray = $this->cache_UTF8StringToArray[$strkey]['s'];
  12617. if (!isset($this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']])) {
  12618. if ($this->isunicode) {
  12619. foreach ($chrarray as $chr) {
  12620. // store this char for font subsetting
  12621. $this->CurrentFont['subsetchars'][$chr] = true;
  12622. }
  12623. // update font subsetchars
  12624. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  12625. }
  12626. $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
  12627. }
  12628. return $chrarray;
  12629. }
  12630. // check cache size
  12631. if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
  12632. // remove first element
  12633. array_shift($this->cache_UTF8StringToArray);
  12634. }
  12635. // new cache array for selected string
  12636. $this->cache_UTF8StringToArray[$strkey] = array('s' => array(), 'f' => array());
  12637. ++$this->cache_size_UTF8StringToArray;
  12638. if (!$this->isunicode) {
  12639. // split string into array of equivalent codes
  12640. $strarr = array();
  12641. $strlen = strlen($str);
  12642. for ($i=0; $i < $strlen; ++$i) {
  12643. $strarr[] = ord($str[$i]);
  12644. }
  12645. // insert new value on cache
  12646. $this->cache_UTF8StringToArray[$strkey]['s'] = $strarr;
  12647. $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
  12648. return $strarr;
  12649. }
  12650. $unichar = -1; // last unicode char
  12651. $unicode = array(); // array containing unicode values
  12652. $bytes = array(); // array containing single character byte sequences
  12653. $numbytes = 1; // number of octetc needed to represent the UTF-8 character
  12654. $str .= ''; // force $str to be a string
  12655. $length = strlen($str);
  12656. for ($i = 0; $i < $length; ++$i) {
  12657. $char = ord($str[$i]); // get one string character at time
  12658. if (count($bytes) == 0) { // get starting octect
  12659. if ($char <= 0x7F) {
  12660. $unichar = $char; // use the character "as is" because is ASCII
  12661. $numbytes = 1;
  12662. } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
  12663. $bytes[] = ($char - 0xC0) << 0x06;
  12664. $numbytes = 2;
  12665. } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
  12666. $bytes[] = ($char - 0xE0) << 0x0C;
  12667. $numbytes = 3;
  12668. } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
  12669. $bytes[] = ($char - 0xF0) << 0x12;
  12670. $numbytes = 4;
  12671. } else {
  12672. // use replacement character for other invalid sequences
  12673. $unichar = 0xFFFD;
  12674. $bytes = array();
  12675. $numbytes = 1;
  12676. }
  12677. } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  12678. $bytes[] = $char - 0x80;
  12679. if (count($bytes) == $numbytes) {
  12680. // compose UTF-8 bytes to a single unicode value
  12681. $char = $bytes[0];
  12682. for ($j = 1; $j < $numbytes; ++$j) {
  12683. $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
  12684. }
  12685. if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
  12686. /* The definition of UTF-8 prohibits encoding character numbers between
  12687. U+D800 and U+DFFF, which are reserved for use with the UTF-16
  12688. encoding form (as surrogate pairs) and do not directly represent
  12689. characters. */
  12690. $unichar = 0xFFFD; // use replacement character
  12691. } else {
  12692. $unichar = $char; // add char to array
  12693. }
  12694. // reset data for next char
  12695. $bytes = array();
  12696. $numbytes = 1;
  12697. }
  12698. } else {
  12699. // use replacement character for other invalid sequences
  12700. $unichar = 0xFFFD;
  12701. $bytes = array();
  12702. $numbytes = 1;
  12703. }
  12704. if ($unichar >= 0) {
  12705. // insert unicode value into array
  12706. $unicode[] = $unichar;
  12707. // store this char for font subsetting
  12708. $this->CurrentFont['subsetchars'][$unichar] = true;
  12709. $unichar = -1;
  12710. }
  12711. }
  12712. // update font subsetchars
  12713. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  12714. // insert new value on cache
  12715. $this->cache_UTF8StringToArray[$strkey]['s'] = $unicode;
  12716. $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
  12717. return $unicode;
  12718. }
  12719. /**
  12720. * Converts UTF-8 strings to UTF16-BE.<br>
  12721. * @param $str (string) string to process.
  12722. * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
  12723. * @return string
  12724. * @author Nicola Asuni
  12725. * @since 1.53.0.TC005 (2005-01-05)
  12726. * @see UTF8StringToArray(), arrUTF8ToUTF16BE()
  12727. * @protected
  12728. */
  12729. protected function UTF8ToUTF16BE($str, $setbom=false) {
  12730. if (!$this->isunicode) {
  12731. return $str; // string is not in unicode
  12732. }
  12733. $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
  12734. return $this->arrUTF8ToUTF16BE($unicode, $setbom);
  12735. }
  12736. /**
  12737. * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
  12738. * @param $str (string) string to process.
  12739. * @return string
  12740. * @author Andrew Whitehead, Nicola Asuni
  12741. * @protected
  12742. * @since 3.2.000 (2008-06-23)
  12743. */
  12744. protected function UTF8ToLatin1($str) {
  12745. if (!$this->isunicode) {
  12746. return $str; // string is not in unicode
  12747. }
  12748. $outstr = ''; // string to be returned
  12749. $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
  12750. foreach ($unicode as $char) {
  12751. if ($char < 256) {
  12752. $outstr .= chr($char);
  12753. } elseif (array_key_exists($char, $this->unicode->uni_utf8tolatin)) {
  12754. // map from UTF-8
  12755. $outstr .= chr($this->unicode->uni_utf8tolatin[$char]);
  12756. } elseif ($char == 0xFFFD) {
  12757. // skip
  12758. } else {
  12759. $outstr .= '?';
  12760. }
  12761. }
  12762. return $outstr;
  12763. }
  12764. /**
  12765. * Converts UTF-8 characters array to array of Latin1 characters<br>
  12766. * @param $unicode (array) array containing UTF-8 unicode values
  12767. * @return array
  12768. * @author Nicola Asuni
  12769. * @protected
  12770. * @since 4.8.023 (2010-01-15)
  12771. */
  12772. protected function UTF8ArrToLatin1($unicode) {
  12773. if ((!$this->isunicode) OR $this->isUnicodeFont()) {
  12774. return $unicode;
  12775. }
  12776. $outarr = array(); // array to be returned
  12777. foreach ($unicode as $char) {
  12778. if ($char < 256) {
  12779. $outarr[] = $char;
  12780. } elseif (array_key_exists($char, $this->unicode->uni_utf8tolatin)) {
  12781. // map from UTF-8
  12782. $outarr[] = $this->unicode->uni_utf8tolatin[$char];
  12783. } elseif ($char == 0xFFFD) {
  12784. // skip
  12785. } else {
  12786. $outarr[] = 63; // '?' character
  12787. }
  12788. }
  12789. return $outarr;
  12790. }
  12791. /**
  12792. * Converts array of UTF-8 characters to UTF16-BE string.<br>
  12793. * Based on: http://www.faqs.org/rfcs/rfc2781.html
  12794. * <pre>
  12795. * Encoding UTF-16:
  12796. *
  12797. * Encoding of a single character from an ISO 10646 character value to
  12798. * UTF-16 proceeds as follows. Let U be the character number, no greater
  12799. * than 0x10FFFF.
  12800. *
  12801. * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
  12802. * terminate.
  12803. *
  12804. * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
  12805. * U' must be less than or equal to 0xFFFFF. That is, U' can be
  12806. * represented in 20 bits.
  12807. *
  12808. * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
  12809. * 0xDC00, respectively. These integers each have 10 bits free to
  12810. * encode the character value, for a total of 20 bits.
  12811. *
  12812. * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
  12813. * bits of W1 and the 10 low-order bits of U' to the 10 low-order
  12814. * bits of W2. Terminate.
  12815. *
  12816. * Graphically, steps 2 through 4 look like:
  12817. * U' = yyyyyyyyyyxxxxxxxxxx
  12818. * W1 = 110110yyyyyyyyyy
  12819. * W2 = 110111xxxxxxxxxx
  12820. * </pre>
  12821. * @param $unicode (array) array containing UTF-8 unicode values
  12822. * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
  12823. * @return string
  12824. * @protected
  12825. * @author Nicola Asuni
  12826. * @since 2.1.000 (2008-01-08)
  12827. * @see UTF8ToUTF16BE()
  12828. */
  12829. protected function arrUTF8ToUTF16BE($unicode, $setbom=false) {
  12830. $outstr = ''; // string to be returned
  12831. if ($setbom) {
  12832. $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
  12833. }
  12834. foreach ($unicode as $char) {
  12835. if ($char == 0x200b) {
  12836. // skip Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)
  12837. } elseif ($char == 0xFFFD) {
  12838. $outstr .= "\xFF\xFD"; // replacement character
  12839. } elseif ($char < 0x10000) {
  12840. $outstr .= chr($char >> 0x08);
  12841. $outstr .= chr($char & 0xFF);
  12842. } else {
  12843. $char -= 0x10000;
  12844. $w1 = 0xD800 | ($char >> 0x0a);
  12845. $w2 = 0xDC00 | ($char & 0x3FF);
  12846. $outstr .= chr($w1 >> 0x08);
  12847. $outstr .= chr($w1 & 0xFF);
  12848. $outstr .= chr($w2 >> 0x08);
  12849. $outstr .= chr($w2 & 0xFF);
  12850. }
  12851. }
  12852. return $outstr;
  12853. }
  12854. // ====================================================
  12855. /**
  12856. * Set header font.
  12857. * @param $font (array) font
  12858. * @public
  12859. * @since 1.1
  12860. */
  12861. public function setHeaderFont($font) {
  12862. $this->header_font = $font;
  12863. }
  12864. /**
  12865. * Get header font.
  12866. * @return array()
  12867. * @public
  12868. * @since 4.0.012 (2008-07-24)
  12869. */
  12870. public function getHeaderFont() {
  12871. return $this->header_font;
  12872. }
  12873. /**
  12874. * Set footer font.
  12875. * @param $font (array) font
  12876. * @public
  12877. * @since 1.1
  12878. */
  12879. public function setFooterFont($font) {
  12880. $this->footer_font = $font;
  12881. }
  12882. /**
  12883. * Get Footer font.
  12884. * @return array()
  12885. * @public
  12886. * @since 4.0.012 (2008-07-24)
  12887. */
  12888. public function getFooterFont() {
  12889. return $this->footer_font;
  12890. }
  12891. /**
  12892. * Set language array.
  12893. * @param $language (array)
  12894. * @public
  12895. * @since 1.1
  12896. */
  12897. public function setLanguageArray($language) {
  12898. $this->l = $language;
  12899. if (isset($this->l['a_meta_dir'])) {
  12900. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  12901. } else {
  12902. $this->rtl = false;
  12903. }
  12904. }
  12905. /**
  12906. * Returns the PDF data.
  12907. * @public
  12908. */
  12909. public function getPDFData() {
  12910. if ($this->state < 3) {
  12911. $this->Close();
  12912. }
  12913. return $this->buffer;
  12914. }
  12915. /**
  12916. * Output anchor link.
  12917. * @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;)
  12918. * @param $name (string) link name
  12919. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  12920. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  12921. * @param $color (array) array of RGB text color
  12922. * @param $style (string) font style (U, D, B, I)
  12923. * @param $firstblock (boolean) if true the string is the starting of a line.
  12924. * @return the number of cells used or the remaining text if $firstline = true;
  12925. * @public
  12926. */
  12927. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  12928. if (!$this->empty_string($url) AND ($url{0} == '#')) {
  12929. // convert url to internal link
  12930. $lnkdata = explode(',', $url);
  12931. if (isset($lnkdata[0])) {
  12932. $page = intval(substr($lnkdata[0], 1));
  12933. if (empty($page) OR ($page <= 0)) {
  12934. $page = $this->page;
  12935. }
  12936. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  12937. $lnky = floatval($lnkdata[1]);
  12938. } else {
  12939. $lnky = 0;
  12940. }
  12941. $url = $this->AddLink();
  12942. $this->SetLink($url, $lnky, $page);
  12943. }
  12944. }
  12945. // store current settings
  12946. $prevcolor = $this->fgcolor;
  12947. $prevstyle = $this->FontStyle;
  12948. if (empty($color)) {
  12949. $this->SetTextColorArray($this->htmlLinkColorArray);
  12950. } else {
  12951. $this->SetTextColorArray($color);
  12952. }
  12953. if ($style == -1) {
  12954. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  12955. } else {
  12956. $this->SetFont('', $this->FontStyle.$style);
  12957. }
  12958. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  12959. // restore settings
  12960. $this->SetFont('', $prevstyle);
  12961. $this->SetTextColorArray($prevcolor);
  12962. return $ret;
  12963. }
  12964. /**
  12965. * Returns an array (RGB or CMYK) from an html color name, or a six-digit (i.e. #3FE5AA), or three-digit (i.e. #7FF) hexadecimal color, or a javascript color array, or javascript color name.
  12966. * @param $hcolor (string) HTML color.
  12967. * @param $defcol (array) Color to return in case of error.
  12968. * @return array RGB or CMYK color, or false in case of error.
  12969. * @public
  12970. */
  12971. public function convertHTMLColorToDec($hcolor='#FFFFFF', $defcol=array('R'=>128,'G'=>128,'B'=>128)) {
  12972. $color = preg_replace('/[\s]*/', '', $hcolor); // remove extra spaces
  12973. $color = strtolower($color);
  12974. // check for javascript color array syntax
  12975. if (strpos($color, '[') !== false) {
  12976. if (preg_match('/[\[][\"\'](t|g|rgb|cmyk)[\"\'][\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\]]/', $color, $m) > 0) {
  12977. $returncolor = array();
  12978. switch ($m[1]) {
  12979. case 'cmyk': {
  12980. // RGB
  12981. $returncolor['C'] = max(0, min(100, (floatval($m[2]) * 100)));
  12982. $returncolor['M'] = max(0, min(100, (floatval($m[3]) * 100)));
  12983. $returncolor['Y'] = max(0, min(100, (floatval($m[4]) * 100)));
  12984. $returncolor['K'] = max(0, min(100, (floatval($m[5]) * 100)));
  12985. break;
  12986. }
  12987. case 'rgb': {
  12988. // RGB
  12989. $returncolor['R'] = max(0, min(255, (floatval($m[2]) * 255)));
  12990. $returncolor['G'] = max(0, min(255, (floatval($m[3]) * 255)));
  12991. $returncolor['B'] = max(0, min(255, (floatval($m[4]) * 255)));
  12992. break;
  12993. }
  12994. case 'g': {
  12995. // grayscale
  12996. $returncolor['G'] = max(0, min(255, (floatval($m[2]) * 255)));
  12997. break;
  12998. }
  12999. case 't':
  13000. default: {
  13001. // transparent (empty array)
  13002. break;
  13003. }
  13004. }
  13005. return $returncolor;
  13006. }
  13007. } elseif (($dotpos = strpos($color, '.')) !== false) {
  13008. // remove class parent (i.e.: color.red)
  13009. $color = substr($color, ($dotpos + 1));
  13010. if ($color == 'transparent') {
  13011. // transparent (empty array)
  13012. return array();
  13013. }
  13014. }
  13015. if (strlen($color) == 0) {
  13016. return $defcol;
  13017. }
  13018. // RGB ARRAY
  13019. if (substr($color, 0, 3) == 'rgb') {
  13020. $codes = substr($color, 4);
  13021. $codes = str_replace(')', '', $codes);
  13022. $returncolor = explode(',', $codes);
  13023. foreach ($returncolor as $key => $val) {
  13024. if (strpos($val, '%') > 0) {
  13025. // percentage
  13026. $returncolor[$key] = (255 * intval($val) / 100);
  13027. } else {
  13028. $returncolor[$key] = intval($val);
  13029. }
  13030. // normalize value
  13031. $returncolor[$key] = max(0, min(255, $returncolor[$key]));
  13032. }
  13033. return $returncolor;
  13034. }
  13035. // CMYK ARRAY
  13036. if (substr($color, 0, 4) == 'cmyk') {
  13037. $codes = substr($color, 5);
  13038. $codes = str_replace(')', '', $codes);
  13039. $returncolor = explode(',', $codes);
  13040. foreach ($returncolor as $key => $val) {
  13041. if (strpos($val, '%') !== false) {
  13042. // percentage
  13043. $returncolor[$key] = (100 * intval($val) / 100);
  13044. } else {
  13045. $returncolor[$key] = intval($val);
  13046. }
  13047. // normalize value
  13048. $returncolor[$key] = max(0, min(100, $returncolor[$key]));
  13049. }
  13050. return $returncolor;
  13051. }
  13052. if ($color{0} != '#') {
  13053. // COLOR NAME
  13054. if (isset($this->webcolor[$color])) {
  13055. // web color
  13056. $color_code = $this->webcolor[$color];
  13057. } else {
  13058. // spot color
  13059. $returncolor = $this->getSpotColor($color);
  13060. if ($returncolor === false) {
  13061. $returncolor = $defcol;
  13062. }
  13063. return $returncolor;
  13064. }
  13065. } else {
  13066. $color_code = substr($color, 1);
  13067. }
  13068. // HEXADECIMAL REPRESENTATION
  13069. switch (strlen($color_code)) {
  13070. case 3: {
  13071. // 3-digit RGB hexadecimal representation
  13072. $r = substr($color_code, 0, 1);
  13073. $g = substr($color_code, 1, 1);
  13074. $b = substr($color_code, 2, 1);
  13075. $returncolor = array();
  13076. $returncolor['R'] = max(0, min(255, hexdec($r.$r)));
  13077. $returncolor['G'] = max(0, min(255, hexdec($g.$g)));
  13078. $returncolor['B'] = max(0, min(255, hexdec($b.$b)));
  13079. break;
  13080. }
  13081. case 6: {
  13082. // 6-digit RGB hexadecimal representation
  13083. $returncolor = array();
  13084. $returncolor['R'] = max(0, min(255, hexdec(substr($color_code, 0, 2))));
  13085. $returncolor['G'] = max(0, min(255, hexdec(substr($color_code, 2, 2))));
  13086. $returncolor['B'] = max(0, min(255, hexdec(substr($color_code, 4, 2))));
  13087. break;
  13088. }
  13089. case 8: {
  13090. // 8-digit CMYK hexadecimal representation
  13091. $returncolor = array();
  13092. $returncolor['C'] = max(0, min(100, round(hexdec(substr($color_code, 0, 2)) / 2.55)));
  13093. $returncolor['M'] = max(0, min(100, round(hexdec(substr($color_code, 2, 2)) / 2.55)));
  13094. $returncolor['Y'] = max(0, min(100, round(hexdec(substr($color_code, 4, 2)) / 2.55)));
  13095. $returncolor['K'] = max(0, min(100, round(hexdec(substr($color_code, 6, 2)) / 2.55)));
  13096. break;
  13097. }
  13098. default: {
  13099. $returncolor = $defcol;
  13100. break;
  13101. }
  13102. }
  13103. return $returncolor;
  13104. }
  13105. /**
  13106. * Converts pixels to User's Units.
  13107. * @param $px (int) pixels
  13108. * @return float value in user's unit
  13109. * @public
  13110. * @see setImageScale(), getImageScale()
  13111. */
  13112. public function pixelsToUnits($px) {
  13113. return ($px / ($this->imgscale * $this->k));
  13114. }
  13115. /**
  13116. * Reverse function for htmlentities.
  13117. * Convert entities in UTF-8.
  13118. * @param $text_to_convert (string) Text to convert.
  13119. * @return string converted text string
  13120. * @public
  13121. */
  13122. public function unhtmlentities($text_to_convert) {
  13123. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  13124. }
  13125. // ENCRYPTION METHODS ----------------------------------
  13126. /**
  13127. * Returns a string containing random data to be used as a seed for encryption methods.
  13128. * @param $seed (string) starting seed value
  13129. * @return string containing random data
  13130. * @author Nicola Asuni
  13131. * @since 5.9.006 (2010-10-19)
  13132. * @protected
  13133. */
  13134. protected function getRandomSeed($seed='') {
  13135. $seed .= microtime();
  13136. if (function_exists('openssl_random_pseudo_bytes') AND (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) {
  13137. // this is not used on windows systems because it is very slow for a know bug
  13138. $seed .= openssl_random_pseudo_bytes(512);
  13139. } else {
  13140. for ($i = 0; $i < 23; ++$i) {
  13141. $seed .= uniqid('', true);
  13142. }
  13143. }
  13144. $seed .= uniqid('', true);
  13145. $seed .= rand();
  13146. $seed .= getmypid();
  13147. $seed .= __FILE__;
  13148. $seed .= $this->bufferlen;
  13149. if (isset($_SERVER['REMOTE_ADDR'])) {
  13150. $seed .= $_SERVER['REMOTE_ADDR'];
  13151. }
  13152. if (isset($_SERVER['HTTP_USER_AGENT'])) {
  13153. $seed .= $_SERVER['HTTP_USER_AGENT'];
  13154. }
  13155. if (isset($_SERVER['HTTP_ACCEPT'])) {
  13156. $seed .= $_SERVER['HTTP_ACCEPT'];
  13157. }
  13158. if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
  13159. $seed .= $_SERVER['HTTP_ACCEPT_ENCODING'];
  13160. }
  13161. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  13162. $seed .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  13163. }
  13164. if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
  13165. $seed .= $_SERVER['HTTP_ACCEPT_CHARSET'];
  13166. }
  13167. $seed .= rand();
  13168. $seed .= uniqid('', true);
  13169. $seed .= microtime();
  13170. return $seed;
  13171. }
  13172. /**
  13173. * Compute encryption key depending on object number where the encrypted data is stored.
  13174. * This is used for all strings and streams without crypt filter specifier.
  13175. * @param $n (int) object number
  13176. * @return int object key
  13177. * @protected
  13178. * @author Nicola Asuni
  13179. * @since 2.0.000 (2008-01-02)
  13180. */
  13181. protected function _objectkey($n) {
  13182. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  13183. if ($this->encryptdata['mode'] == 2) { // AES-128
  13184. // AES padding
  13185. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  13186. }
  13187. $objkey = substr($this->_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  13188. $objkey = substr($objkey, 0, 16);
  13189. return $objkey;
  13190. }
  13191. /**
  13192. * Encrypt the input string.
  13193. * @param $n (int) object number
  13194. * @param $s (string) data string to encrypt
  13195. * @return encrypted string
  13196. * @protected
  13197. * @author Nicola Asuni
  13198. * @since 5.0.005 (2010-05-11)
  13199. */
  13200. protected function _encrypt_data($n, $s) {
  13201. if (!$this->encrypted) {
  13202. return $s;
  13203. }
  13204. switch ($this->encryptdata['mode']) {
  13205. case 0: // RC4-40
  13206. case 1: { // RC4-128
  13207. $s = $this->_RC4($this->_objectkey($n), $s);
  13208. break;
  13209. }
  13210. case 2: { // AES-128
  13211. $s = $this->_AES($this->_objectkey($n), $s);
  13212. break;
  13213. }
  13214. case 3: { // AES-256
  13215. $s = $this->_AES($this->encryptdata['key'], $s);
  13216. break;
  13217. }
  13218. }
  13219. return $s;
  13220. }
  13221. /**
  13222. * Put encryption on PDF document.
  13223. * @protected
  13224. * @author Nicola Asuni
  13225. * @since 2.0.000 (2008-01-02)
  13226. */
  13227. protected function _putencryption() {
  13228. if (!$this->encrypted) {
  13229. return;
  13230. }
  13231. $this->encryptdata['objid'] = $this->_newobj();
  13232. $out = '<<';
  13233. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  13234. $this->encryptdata['Filter'] = 'Standard';
  13235. }
  13236. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  13237. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  13238. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  13239. }
  13240. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  13241. $this->encryptdata['V'] = 1;
  13242. }
  13243. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  13244. $out .= ' /V '.$this->encryptdata['V'];
  13245. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  13246. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  13247. $out .= ' /Length '.$this->encryptdata['Length'];
  13248. } else {
  13249. $out .= ' /Length 40';
  13250. }
  13251. if ($this->encryptdata['V'] >= 4) {
  13252. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  13253. $this->encryptdata['StmF'] = 'Identity';
  13254. }
  13255. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  13256. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  13257. $this->encryptdata['StrF'] = 'Identity';
  13258. }
  13259. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  13260. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  13261. $out .= ' /CF <<';
  13262. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  13263. $out .= ' /Type /CryptFilter';
  13264. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  13265. // The method used
  13266. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  13267. if ($this->encryptdata['pubkey']) {
  13268. $out .= ' /Recipients [';
  13269. foreach ($this->encryptdata['Recipients'] as $rec) {
  13270. $out .= ' <'.$rec.'>';
  13271. }
  13272. $out .= ' ]';
  13273. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  13274. $out .= ' /EncryptMetadata false';
  13275. } else {
  13276. $out .= ' /EncryptMetadata true';
  13277. }
  13278. }
  13279. } else {
  13280. $out .= ' /CFM /None';
  13281. }
  13282. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  13283. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  13284. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  13285. } else {
  13286. $out .= ' /AuthEvent /DocOpen';
  13287. }
  13288. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  13289. // The bit length of the encryption key.
  13290. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  13291. }
  13292. $out .= ' >> >>';
  13293. }
  13294. // The name of the crypt filter that shall be used by default when decrypting streams.
  13295. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  13296. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  13297. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  13298. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  13299. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  13300. $out .= ' /EFF /'.$this->encryptdata[''];
  13301. }
  13302. }
  13303. // Additional encryption dictionary entries for the standard security handler
  13304. if ($this->encryptdata['pubkey']) {
  13305. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  13306. $out .= ' /Recipients [';
  13307. foreach ($this->encryptdata['Recipients'] as $rec) {
  13308. $out .= ' <'.$rec.'>';
  13309. }
  13310. $out .= ' ]';
  13311. }
  13312. } else {
  13313. $out .= ' /R';
  13314. if ($this->encryptdata['V'] == 5) { // AES-256
  13315. $out .= ' 5';
  13316. $out .= ' /OE ('.$this->_escape($this->encryptdata['OE']).')';
  13317. $out .= ' /UE ('.$this->_escape($this->encryptdata['UE']).')';
  13318. $out .= ' /Perms ('.$this->_escape($this->encryptdata['perms']).')';
  13319. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  13320. $out .= ' 4';
  13321. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  13322. $out .= ' 2';
  13323. } else { // RC-128
  13324. $out .= ' 3';
  13325. }
  13326. $out .= ' /O ('.$this->_escape($this->encryptdata['O']).')';
  13327. $out .= ' /U ('.$this->_escape($this->encryptdata['U']).')';
  13328. $out .= ' /P '.$this->encryptdata['P'];
  13329. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  13330. $out .= ' /EncryptMetadata false';
  13331. } else {
  13332. $out .= ' /EncryptMetadata true';
  13333. }
  13334. }
  13335. $out .= ' >>';
  13336. $out .= "\n".'endobj';
  13337. $this->_out($out);
  13338. }
  13339. /**
  13340. * Returns the input text encrypted using RC4 algorithm and the specified key.
  13341. * RC4 is the standard encryption algorithm used in PDF format
  13342. * @param $key (string) encryption key
  13343. * @param $text (String) input text to be encrypted
  13344. * @return String encrypted text
  13345. * @protected
  13346. * @since 2.0.000 (2008-01-02)
  13347. * @author Klemen Vodopivec, Nicola Asuni
  13348. */
  13349. protected function _RC4($key, $text) {
  13350. if (function_exists('mcrypt_decrypt') AND ($out = @mcrypt_decrypt(MCRYPT_ARCFOUR, $key, $text, MCRYPT_MODE_STREAM, ''))) {
  13351. // try to use mcrypt function if exist
  13352. return $out;
  13353. }
  13354. if ($this->last_enc_key != $key) {
  13355. $k = str_repeat($key, ((256 / strlen($key)) + 1));
  13356. $rc4 = range(0, 255);
  13357. $j = 0;
  13358. for ($i = 0; $i < 256; ++$i) {
  13359. $t = $rc4[$i];
  13360. $j = ($j + $t + ord($k[$i])) % 256;
  13361. $rc4[$i] = $rc4[$j];
  13362. $rc4[$j] = $t;
  13363. }
  13364. $this->last_enc_key = $key;
  13365. $this->last_enc_key_c = $rc4;
  13366. } else {
  13367. $rc4 = $this->last_enc_key_c;
  13368. }
  13369. $len = strlen($text);
  13370. $a = 0;
  13371. $b = 0;
  13372. $out = '';
  13373. for ($i = 0; $i < $len; ++$i) {
  13374. $a = ($a + 1) % 256;
  13375. $t = $rc4[$a];
  13376. $b = ($b + $t) % 256;
  13377. $rc4[$a] = $rc4[$b];
  13378. $rc4[$b] = $t;
  13379. $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
  13380. $out .= chr(ord($text[$i]) ^ $k);
  13381. }
  13382. return $out;
  13383. }
  13384. /**
  13385. * Returns the input text exrypted using AES algorithm and the specified key.
  13386. * This method requires mcrypt.
  13387. * @param $key (string) encryption key
  13388. * @param $text (String) input text to be encrypted
  13389. * @return String encrypted text
  13390. * @protected
  13391. * @author Nicola Asuni
  13392. * @since 5.0.005 (2010-05-11)
  13393. */
  13394. protected function _AES($key, $text) {
  13395. // padding (RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0)
  13396. $padding = 16 - (strlen($text) % 16);
  13397. $text .= str_repeat(chr($padding), $padding);
  13398. $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
  13399. $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
  13400. $text = $iv.$text;
  13401. return $text;
  13402. }
  13403. /**
  13404. * Encrypts a string using MD5 and returns it's value as a binary string.
  13405. * @param $str (string) input string
  13406. * @return String MD5 encrypted binary string
  13407. * @protected
  13408. * @since 2.0.000 (2008-01-02)
  13409. * @author Klemen Vodopivec
  13410. */
  13411. protected function _md5_16($str) {
  13412. return pack('H*', md5($str));
  13413. }
  13414. /**
  13415. * Compute U value (used for encryption)
  13416. * @return string U value
  13417. * @protected
  13418. * @since 2.0.000 (2008-01-02)
  13419. * @author Nicola Asuni
  13420. */
  13421. protected function _Uvalue() {
  13422. if ($this->encryptdata['mode'] == 0) { // RC4-40
  13423. return $this->_RC4($this->encryptdata['key'], $this->enc_padding);
  13424. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  13425. $tmp = $this->_md5_16($this->enc_padding.$this->encryptdata['fileid']);
  13426. $enc = $this->_RC4($this->encryptdata['key'], $tmp);
  13427. $len = strlen($tmp);
  13428. for ($i = 1; $i <= 19; ++$i) {
  13429. $ek = '';
  13430. for ($j = 0; $j < $len; ++$j) {
  13431. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  13432. }
  13433. $enc = $this->_RC4($ek, $enc);
  13434. }
  13435. $enc .= str_repeat("\x00", 16);
  13436. return substr($enc, 0, 32);
  13437. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  13438. $seed = $this->_md5_16($this->getRandomSeed());
  13439. // User Validation Salt
  13440. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  13441. // User Key Salt
  13442. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  13443. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  13444. }
  13445. }
  13446. /**
  13447. * Compute UE value (used for encryption)
  13448. * @return string UE value
  13449. * @protected
  13450. * @since 5.9.006 (2010-10-19)
  13451. * @author Nicola Asuni
  13452. */
  13453. protected function _UEvalue() {
  13454. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  13455. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
  13456. return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashkey, $this->encryptdata['key'], MCRYPT_MODE_CBC, $iv);
  13457. }
  13458. /**
  13459. * Compute O value (used for encryption)
  13460. * @return string O value
  13461. * @protected
  13462. * @since 2.0.000 (2008-01-02)
  13463. * @author Nicola Asuni
  13464. */
  13465. protected function _Ovalue() {
  13466. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  13467. $tmp = $this->_md5_16($this->encryptdata['owner_password']);
  13468. if ($this->encryptdata['mode'] > 0) {
  13469. for ($i = 0; $i < 50; ++$i) {
  13470. $tmp = $this->_md5_16($tmp);
  13471. }
  13472. }
  13473. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  13474. $enc = $this->_RC4($owner_key, $this->encryptdata['user_password']);
  13475. if ($this->encryptdata['mode'] > 0) {
  13476. $len = strlen($owner_key);
  13477. for ($i = 1; $i <= 19; ++$i) {
  13478. $ek = '';
  13479. for ($j = 0; $j < $len; ++$j) {
  13480. $ek .= chr(ord($owner_key[$j]) ^ $i);
  13481. }
  13482. $enc = $this->_RC4($ek, $enc);
  13483. }
  13484. }
  13485. return $enc;
  13486. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  13487. $seed = $this->_md5_16($this->getRandomSeed());
  13488. // Owner Validation Salt
  13489. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  13490. // Owner Key Salt
  13491. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  13492. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  13493. }
  13494. }
  13495. /**
  13496. * Compute OE value (used for encryption)
  13497. * @return string OE value
  13498. * @protected
  13499. * @since 5.9.006 (2010-10-19)
  13500. * @author Nicola Asuni
  13501. */
  13502. protected function _OEvalue() {
  13503. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  13504. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
  13505. return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashkey, $this->encryptdata['key'], MCRYPT_MODE_CBC, $iv);
  13506. }
  13507. /**
  13508. * Convert password for AES-256 encryption mode
  13509. * @param $password (string) password
  13510. * @return string password
  13511. * @protected
  13512. * @since 5.9.006 (2010-10-19)
  13513. * @author Nicola Asuni
  13514. */
  13515. protected function _fixAES256Password($password) {
  13516. $psw = ''; // password to be returned
  13517. $psw_array = $this->utf8Bidi($this->UTF8StringToArray($password), $password, $this->rtl);
  13518. foreach ($psw_array as $c) {
  13519. $psw .= $this->unichr($c);
  13520. }
  13521. return substr($psw, 0, 127);
  13522. }
  13523. /**
  13524. * Compute encryption key
  13525. * @protected
  13526. * @since 2.0.000 (2008-01-02)
  13527. * @author Nicola Asuni
  13528. */
  13529. protected function _generateencryptionkey() {
  13530. $keybytelen = ($this->encryptdata['Length'] / 8);
  13531. if (!$this->encryptdata['pubkey']) { // standard mode
  13532. if ($this->encryptdata['mode'] == 3) { // AES-256
  13533. // generate 256 bit random key
  13534. $this->encryptdata['key'] = substr(hash('sha256', $this->getRandomSeed(), true), 0, $keybytelen);
  13535. // truncate passwords
  13536. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  13537. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  13538. // Compute U value
  13539. $this->encryptdata['U'] = $this->_Uvalue();
  13540. // Compute UE value
  13541. $this->encryptdata['UE'] = $this->_UEvalue();
  13542. // Compute O value
  13543. $this->encryptdata['O'] = $this->_Ovalue();
  13544. // Compute OE value
  13545. $this->encryptdata['OE'] = $this->_OEvalue();
  13546. // Compute P value
  13547. $this->encryptdata['P'] = $this->encryptdata['protection'];
  13548. // Computing the encryption dictionary's Perms (permissions) value
  13549. $perms = $this->getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  13550. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  13551. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  13552. $perms .= 'F';
  13553. } else {
  13554. $perms .= 'T';
  13555. }
  13556. $perms .= 'adb'; // bytes 9-11
  13557. $perms .= 'nick'; // bytes 12-15
  13558. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
  13559. $this->encryptdata['perms'] = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->encryptdata['key'], $perms, MCRYPT_MODE_ECB, $iv);
  13560. } else { // RC4-40, RC4-128, AES-128
  13561. // Pad passwords
  13562. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].$this->enc_padding, 0, 32);
  13563. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].$this->enc_padding, 0, 32);
  13564. // Compute O value
  13565. $this->encryptdata['O'] = $this->_Ovalue();
  13566. // get default permissions (reverse byte order)
  13567. $permissions = $this->getEncPermissionsString($this->encryptdata['protection']);
  13568. // Compute encryption key
  13569. $tmp = $this->_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  13570. if ($this->encryptdata['mode'] > 0) {
  13571. for ($i = 0; $i < 50; ++$i) {
  13572. $tmp = $this->_md5_16(substr($tmp, 0, $keybytelen));
  13573. }
  13574. }
  13575. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  13576. // Compute U value
  13577. $this->encryptdata['U'] = $this->_Uvalue();
  13578. // Compute P value
  13579. $this->encryptdata['P'] = $this->encryptdata['protection'];
  13580. }
  13581. } else { // Public-Key mode
  13582. // random 20-byte seed
  13583. $seed = sha1($this->getRandomSeed(), true);
  13584. $recipient_bytes = '';
  13585. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  13586. // for each public certificate
  13587. if (isset($pubkey['p'])) {
  13588. $pkprotection = $this->getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  13589. } else {
  13590. $pkprotection = $this->encryptdata['protection'];
  13591. }
  13592. // get default permissions (reverse byte order)
  13593. $pkpermissions = $this->getEncPermissionsString($pkprotection);
  13594. // envelope data
  13595. $envelope = $seed.$pkpermissions;
  13596. // write the envelope data to a temporary file
  13597. $tempkeyfile = tempnam(K_PATH_CACHE, 'tmpkey_');
  13598. $f = fopen($tempkeyfile, 'wb');
  13599. if (!$f) {
  13600. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  13601. }
  13602. $envelope_length = strlen($envelope);
  13603. fwrite($f, $envelope, $envelope_length);
  13604. fclose($f);
  13605. $tempencfile = tempnam(K_PATH_CACHE, 'tmpenc_');
  13606. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  13607. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  13608. }
  13609. unlink($tempkeyfile);
  13610. // read encryption signature
  13611. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  13612. unlink($tempencfile);
  13613. // extract signature
  13614. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  13615. $tmparr = explode("\n\n", $signature);
  13616. $signature = trim($tmparr[1]);
  13617. unset($tmparr);
  13618. // decode signature
  13619. $signature = base64_decode($signature);
  13620. // convert signature to hex
  13621. $hexsignature = current(unpack('H*', $signature));
  13622. // store signature on recipients array
  13623. $this->encryptdata['Recipients'][] = $hexsignature;
  13624. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  13625. $recipient_bytes .= $signature;
  13626. }
  13627. // calculate encryption key
  13628. if ($this->encryptdata['mode'] == 3) { // AES-256
  13629. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  13630. } else { // RC4-40, RC4-128, AES-128
  13631. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  13632. }
  13633. }
  13634. }
  13635. /**
  13636. * Return the premission code used on encryption (P value).
  13637. * @param $permissions (Array) the set of permissions (specify the ones you want to block).
  13638. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  13639. * @protected
  13640. * @since 5.0.005 (2010-05-12)
  13641. * @author Nicola Asuni
  13642. */
  13643. protected function getUserPermissionCode($permissions, $mode=0) {
  13644. $options = array(
  13645. 'owner' => 2, // bit 2 -- inverted logic: cleared by default
  13646. 'print' => 4, // bit 3
  13647. 'modify' => 8, // bit 4
  13648. 'copy' => 16, // bit 5
  13649. 'annot-forms' => 32, // bit 6
  13650. 'fill-forms' => 256, // bit 9
  13651. 'extract' => 512, // bit 10
  13652. 'assemble' => 1024,// bit 11
  13653. 'print-high' => 2048 // bit 12
  13654. );
  13655. $protection = 2147422012; // 32 bit: (01111111 11111111 00001111 00111100)
  13656. foreach ($permissions as $permission) {
  13657. if (!isset($options[$permission])) {
  13658. $this->Error('Incorrect permission: '.$permission);
  13659. }
  13660. if (($mode > 0) OR ($options[$permission] <= 32)) {
  13661. // set only valid permissions
  13662. if ($options[$permission] == 2) {
  13663. // the logic for bit 2 is inverted (cleared by default)
  13664. $protection += $options[$permission];
  13665. } else {
  13666. $protection -= $options[$permission];
  13667. }
  13668. }
  13669. }
  13670. return $protection;
  13671. }
  13672. /**
  13673. * Set document protection
  13674. * Remark: the protection against modification is for people who have the full Acrobat product.
  13675. * 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.
  13676. * 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.
  13677. * @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>
  13678. * @param $user_pass (String) user password. Empty by default.
  13679. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  13680. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  13681. * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../tcpdf.crt', 'p' => array('print')))
  13682. * @public
  13683. * @since 2.0.000 (2008-01-02)
  13684. * @author Nicola Asuni
  13685. */
  13686. 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) {
  13687. if ($this->pdfa_mode) {
  13688. // encryption is not allowed in PDF/A mode
  13689. return;
  13690. }
  13691. $this->encryptdata['protection'] = $this->getUserPermissionCode($permissions, $mode);
  13692. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  13693. // public-key mode
  13694. $this->encryptdata['pubkeys'] = $pubkeys;
  13695. if ($mode == 0) {
  13696. // public-Key Security requires at least 128 bit
  13697. $mode = 1;
  13698. }
  13699. if (!function_exists('openssl_pkcs7_encrypt')) {
  13700. $this->Error('Public-Key Security requires openssl library.');
  13701. }
  13702. // Set Public-Key filter (availabe are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  13703. $this->encryptdata['pubkey'] = true;
  13704. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  13705. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  13706. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  13707. } else {
  13708. // standard mode (password mode)
  13709. $this->encryptdata['pubkey'] = false;
  13710. $this->encryptdata['Filter'] = 'Standard';
  13711. $this->encryptdata['StmF'] = 'StdCF';
  13712. $this->encryptdata['StrF'] = 'StdCF';
  13713. }
  13714. if ($mode > 1) { // AES
  13715. if (!extension_loaded('mcrypt')) {
  13716. $this->Error('AES encryption requires mcrypt library (http://www.php.net/manual/en/mcrypt.requirements.php).');
  13717. }
  13718. if (mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  13719. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  13720. }
  13721. if (($mode == 3) AND !function_exists('hash')) {
  13722. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  13723. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  13724. }
  13725. }
  13726. if ($owner_pass === null) {
  13727. $owner_pass = md5($this->getRandomSeed());
  13728. }
  13729. $this->encryptdata['user_password'] = $user_pass;
  13730. $this->encryptdata['owner_password'] = $owner_pass;
  13731. $this->encryptdata['mode'] = $mode;
  13732. switch ($mode) {
  13733. case 0: { // RC4 40 bit
  13734. $this->encryptdata['V'] = 1;
  13735. $this->encryptdata['Length'] = 40;
  13736. $this->encryptdata['CF']['CFM'] = 'V2';
  13737. break;
  13738. }
  13739. case 1: { // RC4 128 bit
  13740. $this->encryptdata['V'] = 2;
  13741. $this->encryptdata['Length'] = 128;
  13742. $this->encryptdata['CF']['CFM'] = 'V2';
  13743. if ($this->encryptdata['pubkey']) {
  13744. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  13745. $this->encryptdata['Recipients'] = array();
  13746. }
  13747. break;
  13748. }
  13749. case 2: { // AES 128 bit
  13750. $this->encryptdata['V'] = 4;
  13751. $this->encryptdata['Length'] = 128;
  13752. $this->encryptdata['CF']['CFM'] = 'AESV2';
  13753. $this->encryptdata['CF']['Length'] = 128;
  13754. if ($this->encryptdata['pubkey']) {
  13755. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  13756. $this->encryptdata['Recipients'] = array();
  13757. }
  13758. break;
  13759. }
  13760. case 3: { // AES 256 bit
  13761. $this->encryptdata['V'] = 5;
  13762. $this->encryptdata['Length'] = 256;
  13763. $this->encryptdata['CF']['CFM'] = 'AESV3';
  13764. $this->encryptdata['CF']['Length'] = 256;
  13765. if ($this->encryptdata['pubkey']) {
  13766. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  13767. $this->encryptdata['Recipients'] = array();
  13768. }
  13769. break;
  13770. }
  13771. }
  13772. $this->encrypted = true;
  13773. $this->encryptdata['fileid'] = $this->convertHexStringToString($this->file_id);
  13774. $this->_generateencryptionkey();
  13775. }
  13776. /**
  13777. * Convert hexadecimal string to string
  13778. * @param $bs (string) byte-string to convert
  13779. * @return String
  13780. * @protected
  13781. * @since 5.0.005 (2010-05-12)
  13782. * @author Nicola Asuni
  13783. */
  13784. protected function convertHexStringToString($bs) {
  13785. $string = ''; // string to be returned
  13786. $bslength = strlen($bs);
  13787. if (($bslength % 2) != 0) {
  13788. // padding
  13789. $bs .= '0';
  13790. ++$bslength;
  13791. }
  13792. for ($i = 0; $i < $bslength; $i += 2) {
  13793. $string .= chr(hexdec($bs[$i].$bs[($i + 1)]));
  13794. }
  13795. return $string;
  13796. }
  13797. /**
  13798. * Convert string to hexadecimal string (byte string)
  13799. * @param $s (string) string to convert
  13800. * @return byte string
  13801. * @protected
  13802. * @since 5.0.010 (2010-05-17)
  13803. * @author Nicola Asuni
  13804. */
  13805. protected function convertStringToHexString($s) {
  13806. $bs = '';
  13807. $chars = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
  13808. foreach ($chars as $c) {
  13809. $bs .= sprintf('%02s', dechex(ord($c)));
  13810. }
  13811. return $bs;
  13812. }
  13813. /**
  13814. * Convert encryption P value to a string of bytes, low-order byte first.
  13815. * @param $protection (string) 32bit encryption permission value (P value)
  13816. * @return String
  13817. * @protected
  13818. * @since 5.0.005 (2010-05-12)
  13819. * @author Nicola Asuni
  13820. */
  13821. protected function getEncPermissionsString($protection) {
  13822. $binprot = sprintf('%032b', $protection);
  13823. $str = chr(bindec(substr($binprot, 24, 8)));
  13824. $str .= chr(bindec(substr($binprot, 16, 8)));
  13825. $str .= chr(bindec(substr($binprot, 8, 8)));
  13826. $str .= chr(bindec(substr($binprot, 0, 8)));
  13827. return $str;
  13828. }
  13829. // END OF ENCRYPTION FUNCTIONS -------------------------
  13830. // START TRANSFORMATIONS SECTION -----------------------
  13831. /**
  13832. * Starts a 2D tranformation saving current graphic state.
  13833. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  13834. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  13835. * @public
  13836. * @since 2.1.000 (2008-01-07)
  13837. * @see StartTransform(), StopTransform()
  13838. */
  13839. public function StartTransform() {
  13840. $this->_out('q');
  13841. if ($this->inxobj) {
  13842. // we are inside an XObject template
  13843. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  13844. } else {
  13845. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  13846. }
  13847. ++$this->transfmatrix_key;
  13848. $this->transfmatrix[$this->transfmatrix_key] = array();
  13849. }
  13850. /**
  13851. * Stops a 2D tranformation restoring previous graphic state.
  13852. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  13853. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  13854. * @public
  13855. * @since 2.1.000 (2008-01-07)
  13856. * @see StartTransform(), StopTransform()
  13857. */
  13858. public function StopTransform() {
  13859. $this->_out('Q');
  13860. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  13861. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  13862. --$this->transfmatrix_key;
  13863. }
  13864. if ($this->inxobj) {
  13865. // we are inside an XObject template
  13866. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  13867. } else {
  13868. array_pop($this->transfmrk[$this->page]);
  13869. }
  13870. }
  13871. /**
  13872. * Horizontal Scaling.
  13873. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  13874. * @param $x (int) abscissa of the scaling center. Default is current x position
  13875. * @param $y (int) ordinate of the scaling center. Default is current y position
  13876. * @public
  13877. * @since 2.1.000 (2008-01-07)
  13878. * @see StartTransform(), StopTransform()
  13879. */
  13880. public function ScaleX($s_x, $x='', $y='') {
  13881. $this->Scale($s_x, 100, $x, $y);
  13882. }
  13883. /**
  13884. * Vertical Scaling.
  13885. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  13886. * @param $x (int) abscissa of the scaling center. Default is current x position
  13887. * @param $y (int) ordinate of the scaling center. Default is current y position
  13888. * @public
  13889. * @since 2.1.000 (2008-01-07)
  13890. * @see StartTransform(), StopTransform()
  13891. */
  13892. public function ScaleY($s_y, $x='', $y='') {
  13893. $this->Scale(100, $s_y, $x, $y);
  13894. }
  13895. /**
  13896. * Vertical and horizontal proportional Scaling.
  13897. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  13898. * @param $x (int) abscissa of the scaling center. Default is current x position
  13899. * @param $y (int) ordinate of the scaling center. Default is current y position
  13900. * @public
  13901. * @since 2.1.000 (2008-01-07)
  13902. * @see StartTransform(), StopTransform()
  13903. */
  13904. public function ScaleXY($s, $x='', $y='') {
  13905. $this->Scale($s, $s, $x, $y);
  13906. }
  13907. /**
  13908. * Vertical and horizontal non-proportional Scaling.
  13909. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  13910. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  13911. * @param $x (int) abscissa of the scaling center. Default is current x position
  13912. * @param $y (int) ordinate of the scaling center. Default is current y position
  13913. * @public
  13914. * @since 2.1.000 (2008-01-07)
  13915. * @see StartTransform(), StopTransform()
  13916. */
  13917. public function Scale($s_x, $s_y, $x='', $y='') {
  13918. if ($x === '') {
  13919. $x = $this->x;
  13920. }
  13921. if ($y === '') {
  13922. $y = $this->y;
  13923. }
  13924. if (($s_x == 0) OR ($s_y == 0)) {
  13925. $this->Error('Please do not use values equal to zero for scaling');
  13926. }
  13927. $y = ($this->h - $y) * $this->k;
  13928. $x *= $this->k;
  13929. //calculate elements of transformation matrix
  13930. $s_x /= 100;
  13931. $s_y /= 100;
  13932. $tm = array();
  13933. $tm[0] = $s_x;
  13934. $tm[1] = 0;
  13935. $tm[2] = 0;
  13936. $tm[3] = $s_y;
  13937. $tm[4] = $x * (1 - $s_x);
  13938. $tm[5] = $y * (1 - $s_y);
  13939. //scale the coordinate system
  13940. $this->Transform($tm);
  13941. }
  13942. /**
  13943. * Horizontal Mirroring.
  13944. * @param $x (int) abscissa of the point. Default is current x position
  13945. * @public
  13946. * @since 2.1.000 (2008-01-07)
  13947. * @see StartTransform(), StopTransform()
  13948. */
  13949. public function MirrorH($x='') {
  13950. $this->Scale(-100, 100, $x);
  13951. }
  13952. /**
  13953. * Verical Mirroring.
  13954. * @param $y (int) ordinate of the point. Default is current y position
  13955. * @public
  13956. * @since 2.1.000 (2008-01-07)
  13957. * @see StartTransform(), StopTransform()
  13958. */
  13959. public function MirrorV($y='') {
  13960. $this->Scale(100, -100, '', $y);
  13961. }
  13962. /**
  13963. * Point reflection mirroring.
  13964. * @param $x (int) abscissa of the point. Default is current x position
  13965. * @param $y (int) ordinate of the point. Default is current y position
  13966. * @public
  13967. * @since 2.1.000 (2008-01-07)
  13968. * @see StartTransform(), StopTransform()
  13969. */
  13970. public function MirrorP($x='',$y='') {
  13971. $this->Scale(-100, -100, $x, $y);
  13972. }
  13973. /**
  13974. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  13975. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  13976. * @param $x (int) abscissa of the point. Default is current x position
  13977. * @param $y (int) ordinate of the point. Default is current y position
  13978. * @public
  13979. * @since 2.1.000 (2008-01-07)
  13980. * @see StartTransform(), StopTransform()
  13981. */
  13982. public function MirrorL($angle=0, $x='',$y='') {
  13983. $this->Scale(-100, 100, $x, $y);
  13984. $this->Rotate(-2*($angle-90), $x, $y);
  13985. }
  13986. /**
  13987. * Translate graphic object horizontally.
  13988. * @param $t_x (int) movement to the right (or left for RTL)
  13989. * @public
  13990. * @since 2.1.000 (2008-01-07)
  13991. * @see StartTransform(), StopTransform()
  13992. */
  13993. public function TranslateX($t_x) {
  13994. $this->Translate($t_x, 0);
  13995. }
  13996. /**
  13997. * Translate graphic object vertically.
  13998. * @param $t_y (int) movement to the bottom
  13999. * @public
  14000. * @since 2.1.000 (2008-01-07)
  14001. * @see StartTransform(), StopTransform()
  14002. */
  14003. public function TranslateY($t_y) {
  14004. $this->Translate(0, $t_y);
  14005. }
  14006. /**
  14007. * Translate graphic object horizontally and vertically.
  14008. * @param $t_x (int) movement to the right
  14009. * @param $t_y (int) movement to the bottom
  14010. * @public
  14011. * @since 2.1.000 (2008-01-07)
  14012. * @see StartTransform(), StopTransform()
  14013. */
  14014. public function Translate($t_x, $t_y) {
  14015. //calculate elements of transformation matrix
  14016. $tm = array();
  14017. $tm[0] = 1;
  14018. $tm[1] = 0;
  14019. $tm[2] = 0;
  14020. $tm[3] = 1;
  14021. $tm[4] = $t_x * $this->k;
  14022. $tm[5] = -$t_y * $this->k;
  14023. //translate the coordinate system
  14024. $this->Transform($tm);
  14025. }
  14026. /**
  14027. * Rotate object.
  14028. * @param $angle (float) angle in degrees for counter-clockwise rotation
  14029. * @param $x (int) abscissa of the rotation center. Default is current x position
  14030. * @param $y (int) ordinate of the rotation center. Default is current y position
  14031. * @public
  14032. * @since 2.1.000 (2008-01-07)
  14033. * @see StartTransform(), StopTransform()
  14034. */
  14035. public function Rotate($angle, $x='', $y='') {
  14036. if ($x === '') {
  14037. $x = $this->x;
  14038. }
  14039. if ($y === '') {
  14040. $y = $this->y;
  14041. }
  14042. $y = ($this->h - $y) * $this->k;
  14043. $x *= $this->k;
  14044. //calculate elements of transformation matrix
  14045. $tm = array();
  14046. $tm[0] = cos(deg2rad($angle));
  14047. $tm[1] = sin(deg2rad($angle));
  14048. $tm[2] = -$tm[1];
  14049. $tm[3] = $tm[0];
  14050. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  14051. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  14052. //rotate the coordinate system around ($x,$y)
  14053. $this->Transform($tm);
  14054. }
  14055. /**
  14056. * Skew horizontally.
  14057. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  14058. * @param $x (int) abscissa of the skewing center. default is current x position
  14059. * @param $y (int) ordinate of the skewing center. default is current y position
  14060. * @public
  14061. * @since 2.1.000 (2008-01-07)
  14062. * @see StartTransform(), StopTransform()
  14063. */
  14064. public function SkewX($angle_x, $x='', $y='') {
  14065. $this->Skew($angle_x, 0, $x, $y);
  14066. }
  14067. /**
  14068. * Skew vertically.
  14069. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  14070. * @param $x (int) abscissa of the skewing center. default is current x position
  14071. * @param $y (int) ordinate of the skewing center. default is current y position
  14072. * @public
  14073. * @since 2.1.000 (2008-01-07)
  14074. * @see StartTransform(), StopTransform()
  14075. */
  14076. public function SkewY($angle_y, $x='', $y='') {
  14077. $this->Skew(0, $angle_y, $x, $y);
  14078. }
  14079. /**
  14080. * Skew.
  14081. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  14082. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  14083. * @param $x (int) abscissa of the skewing center. default is current x position
  14084. * @param $y (int) ordinate of the skewing center. default is current y position
  14085. * @public
  14086. * @since 2.1.000 (2008-01-07)
  14087. * @see StartTransform(), StopTransform()
  14088. */
  14089. public function Skew($angle_x, $angle_y, $x='', $y='') {
  14090. if ($x === '') {
  14091. $x = $this->x;
  14092. }
  14093. if ($y === '') {
  14094. $y = $this->y;
  14095. }
  14096. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  14097. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  14098. }
  14099. $x *= $this->k;
  14100. $y = ($this->h - $y) * $this->k;
  14101. //calculate elements of transformation matrix
  14102. $tm = array();
  14103. $tm[0] = 1;
  14104. $tm[1] = tan(deg2rad($angle_y));
  14105. $tm[2] = tan(deg2rad($angle_x));
  14106. $tm[3] = 1;
  14107. $tm[4] = -$tm[2] * $y;
  14108. $tm[5] = -$tm[1] * $x;
  14109. //skew the coordinate system
  14110. $this->Transform($tm);
  14111. }
  14112. /**
  14113. * Apply graphic transformations.
  14114. * @param $tm (array) transformation matrix
  14115. * @protected
  14116. * @since 2.1.000 (2008-01-07)
  14117. * @see StartTransform(), StopTransform()
  14118. */
  14119. protected function Transform($tm) {
  14120. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  14121. // add tranformation matrix
  14122. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  14123. // update transformation mark
  14124. if ($this->inxobj) {
  14125. // we are inside an XObject template
  14126. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  14127. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  14128. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  14129. }
  14130. } elseif (end($this->transfmrk[$this->page]) !== false) {
  14131. $key = key($this->transfmrk[$this->page]);
  14132. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  14133. }
  14134. }
  14135. // END TRANSFORMATIONS SECTION -------------------------
  14136. // START GRAPHIC FUNCTIONS SECTION ---------------------
  14137. // The following section is based on the code provided by David Hernandez Sanz
  14138. /**
  14139. * 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.
  14140. * @param $width (float) The width.
  14141. * @public
  14142. * @since 1.0
  14143. * @see Line(), Rect(), Cell(), MultiCell()
  14144. */
  14145. public function SetLineWidth($width) {
  14146. //Set line width
  14147. $this->LineWidth = $width;
  14148. $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
  14149. if ($this->page > 0) {
  14150. $this->_out($this->linestyleWidth);
  14151. }
  14152. }
  14153. /**
  14154. * Returns the current the line width.
  14155. * @return int Line width
  14156. * @public
  14157. * @since 2.1.000 (2008-01-07)
  14158. * @see Line(), SetLineWidth()
  14159. */
  14160. public function GetLineWidth() {
  14161. return $this->LineWidth;
  14162. }
  14163. /**
  14164. * Set line style.
  14165. * @param $style (array) Line style. Array with keys among the following:
  14166. * <ul>
  14167. * <li>width (float): Width of the line in user units.</li>
  14168. * <li>cap (string): Type of cap to put on the line. Possible values are:
  14169. * butt, round, square. The difference between "square" and "butt" is that
  14170. * "square" projects a flat end past the end of the line.</li>
  14171. * <li>join (string): Type of join. Possible values are: miter, round,
  14172. * bevel.</li>
  14173. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  14174. * series of length values, which are the lengths of the on and off dashes.
  14175. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  14176. * 1 off, 2 on, 1 off, ...</li>
  14177. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  14178. * the point at which the pattern starts.</li>
  14179. * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
  14180. * </ul>
  14181. * @param $ret (boolean) if true do not send the command.
  14182. * @return string the PDF command
  14183. * @public
  14184. * @since 2.1.000 (2008-01-08)
  14185. */
  14186. public function SetLineStyle($style, $ret=false) {
  14187. $s = ''; // string to be returned
  14188. if (!is_array($style)) {
  14189. return;
  14190. }
  14191. if (isset($style['width'])) {
  14192. $this->LineWidth = $style['width'];
  14193. $this->linestyleWidth = sprintf('%.2F w', ($style['width'] * $this->k));
  14194. $s .= $this->linestyleWidth.' ';
  14195. }
  14196. if (isset($style['cap'])) {
  14197. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  14198. if (isset($ca[$style['cap']])) {
  14199. $this->linestyleCap = $ca[$style['cap']].' J';
  14200. $s .= $this->linestyleCap.' ';
  14201. }
  14202. }
  14203. if (isset($style['join'])) {
  14204. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  14205. if (isset($ja[$style['join']])) {
  14206. $this->linestyleJoin = $ja[$style['join']].' j';
  14207. $s .= $this->linestyleJoin.' ';
  14208. }
  14209. }
  14210. if (isset($style['dash'])) {
  14211. $dash_string = '';
  14212. if ($style['dash']) {
  14213. if (preg_match('/^.+,/', $style['dash']) > 0) {
  14214. $tab = explode(',', $style['dash']);
  14215. } else {
  14216. $tab = array($style['dash']);
  14217. }
  14218. $dash_string = '';
  14219. foreach ($tab as $i => $v) {
  14220. if ($i) {
  14221. $dash_string .= ' ';
  14222. }
  14223. $dash_string .= sprintf('%.2F', $v);
  14224. }
  14225. }
  14226. if (!isset($style['phase']) OR !$style['dash']) {
  14227. $style['phase'] = 0;
  14228. }
  14229. $this->linestyleDash = sprintf('[%s] %.2F d', $dash_string, $style['phase']);
  14230. $s .= $this->linestyleDash.' ';
  14231. }
  14232. if (isset($style['color'])) {
  14233. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  14234. }
  14235. if (!$ret) {
  14236. $this->_out($s);
  14237. }
  14238. return $s;
  14239. }
  14240. /**
  14241. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  14242. * @param $x (float) Abscissa of point.
  14243. * @param $y (float) Ordinate of point.
  14244. * @protected
  14245. * @since 2.1.000 (2008-01-08)
  14246. */
  14247. protected function _outPoint($x, $y) {
  14248. $this->_out(sprintf('%.2F %.2F m', $x * $this->k, ($this->h - $y) * $this->k));
  14249. }
  14250. /**
  14251. * Append a straight line segment from the current point to the point (x, y).
  14252. * The new current point shall be (x, y).
  14253. * @param $x (float) Abscissa of end point.
  14254. * @param $y (float) Ordinate of end point.
  14255. * @protected
  14256. * @since 2.1.000 (2008-01-08)
  14257. */
  14258. protected function _outLine($x, $y) {
  14259. $this->_out(sprintf('%.2F %.2F l', $x * $this->k, ($this->h - $y) * $this->k));
  14260. }
  14261. /**
  14262. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  14263. * @param $x (float) Abscissa of upper-left corner.
  14264. * @param $y (float) Ordinate of upper-left corner.
  14265. * @param $w (float) Width.
  14266. * @param $h (float) Height.
  14267. * @param $op (string) options
  14268. * @protected
  14269. * @since 2.1.000 (2008-01-08)
  14270. */
  14271. protected function _outRect($x, $y, $w, $h, $op) {
  14272. $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x * $this->k, ($this->h - $y) * $this->k, $w * $this->k, -$h * $this->k, $op));
  14273. }
  14274. /**
  14275. * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x2, y2) as the Bézier control points.
  14276. * The new current point shall be (x3, y3).
  14277. * @param $x1 (float) Abscissa of control point 1.
  14278. * @param $y1 (float) Ordinate of control point 1.
  14279. * @param $x2 (float) Abscissa of control point 2.
  14280. * @param $y2 (float) Ordinate of control point 2.
  14281. * @param $x3 (float) Abscissa of end point.
  14282. * @param $y3 (float) Ordinate of end point.
  14283. * @protected
  14284. * @since 2.1.000 (2008-01-08)
  14285. */
  14286. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  14287. $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  14288. }
  14289. /**
  14290. * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using the current point and (x2, y2) as the Bézier control points.
  14291. * The new current point shall be (x3, y3).
  14292. * @param $x2 (float) Abscissa of control point 2.
  14293. * @param $y2 (float) Ordinate of control point 2.
  14294. * @param $x3 (float) Abscissa of end point.
  14295. * @param $y3 (float) Ordinate of end point.
  14296. * @protected
  14297. * @since 4.9.019 (2010-04-26)
  14298. */
  14299. protected function _outCurveV($x2, $y2, $x3, $y3) {
  14300. $this->_out(sprintf('%.2F %.2F %.2F %.2F v', $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  14301. }
  14302. /**
  14303. * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x3, y3) as the Bézier control points.
  14304. * The new current point shall be (x3, y3).
  14305. * @param $x1 (float) Abscissa of control point 1.
  14306. * @param $y1 (float) Ordinate of control point 1.
  14307. * @param $x3 (float) Abscissa of end point.
  14308. * @param $y3 (float) Ordinate of end point.
  14309. * @protected
  14310. * @since 2.1.000 (2008-01-08)
  14311. */
  14312. protected function _outCurveY($x1, $y1, $x3, $y3) {
  14313. $this->_out(sprintf('%.2F %.2F %.2F %.2F y', $x1 * $this->k, ($this->h - $y1) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  14314. }
  14315. /**
  14316. * Draws a line between two points.
  14317. * @param $x1 (float) Abscissa of first point.
  14318. * @param $y1 (float) Ordinate of first point.
  14319. * @param $x2 (float) Abscissa of second point.
  14320. * @param $y2 (float) Ordinate of second point.
  14321. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  14322. * @public
  14323. * @since 1.0
  14324. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  14325. */
  14326. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  14327. if (is_array($style)) {
  14328. $this->SetLineStyle($style);
  14329. }
  14330. $this->_outPoint($x1, $y1);
  14331. $this->_outLine($x2, $y2);
  14332. $this->_out('S');
  14333. }
  14334. /**
  14335. * Draws a rectangle.
  14336. * @param $x (float) Abscissa of upper-left corner.
  14337. * @param $y (float) Ordinate of upper-left corner.
  14338. * @param $w (float) Width.
  14339. * @param $h (float) Height.
  14340. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14341. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  14342. * <ul>
  14343. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  14344. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  14345. * </ul>
  14346. * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
  14347. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  14348. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14349. * @public
  14350. * @since 1.0
  14351. * @see SetLineStyle()
  14352. */
  14353. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  14354. if (!(false === strpos($style, 'F')) AND !empty($fill_color)) {
  14355. $this->SetFillColorArray($fill_color);
  14356. }
  14357. $op = $this->getPathPaintOperator($style);
  14358. if ((!$border_style) OR (isset($border_style['all']))) {
  14359. if (isset($border_style['all']) AND $border_style['all']) {
  14360. $this->SetLineStyle($border_style['all']);
  14361. $border_style = array();
  14362. }
  14363. }
  14364. $this->_outRect($x, $y, $w, $h, $op);
  14365. if ($border_style) {
  14366. $border_style2 = array();
  14367. foreach ($border_style as $line => $value) {
  14368. $length = strlen($line);
  14369. for ($i = 0; $i < $length; ++$i) {
  14370. $border_style2[$line[$i]] = $value;
  14371. }
  14372. }
  14373. $border_style = $border_style2;
  14374. if (isset($border_style['L']) AND $border_style['L']) {
  14375. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  14376. }
  14377. if (isset($border_style['T']) AND $border_style['T']) {
  14378. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  14379. }
  14380. if (isset($border_style['R']) AND $border_style['R']) {
  14381. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  14382. }
  14383. if (isset($border_style['B']) AND $border_style['B']) {
  14384. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  14385. }
  14386. }
  14387. }
  14388. /**
  14389. * Draws a Bezier curve.
  14390. * The Bezier curve is a tangent to the line between the control points at
  14391. * either end of the curve.
  14392. * @param $x0 (float) Abscissa of start point.
  14393. * @param $y0 (float) Ordinate of start point.
  14394. * @param $x1 (float) Abscissa of control point 1.
  14395. * @param $y1 (float) Ordinate of control point 1.
  14396. * @param $x2 (float) Abscissa of control point 2.
  14397. * @param $y2 (float) Ordinate of control point 2.
  14398. * @param $x3 (float) Abscissa of end point.
  14399. * @param $y3 (float) Ordinate of end point.
  14400. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14401. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  14402. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14403. * @public
  14404. * @see SetLineStyle()
  14405. * @since 2.1.000 (2008-01-08)
  14406. */
  14407. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  14408. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14409. $this->SetFillColorArray($fill_color);
  14410. }
  14411. $op = $this->getPathPaintOperator($style);
  14412. if ($line_style) {
  14413. $this->SetLineStyle($line_style);
  14414. }
  14415. $this->_outPoint($x0, $y0);
  14416. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  14417. $this->_out($op);
  14418. }
  14419. /**
  14420. * Draws a poly-Bezier curve.
  14421. * Each Bezier curve segment is a tangent to the line between the control points at
  14422. * either end of the curve.
  14423. * @param $x0 (float) Abscissa of start point.
  14424. * @param $y0 (float) Ordinate of start point.
  14425. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  14426. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14427. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  14428. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14429. * @public
  14430. * @see SetLineStyle()
  14431. * @since 3.0008 (2008-05-12)
  14432. */
  14433. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  14434. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14435. $this->SetFillColorArray($fill_color);
  14436. }
  14437. $op = $this->getPathPaintOperator($style);
  14438. if ($op == 'f') {
  14439. $line_style = array();
  14440. }
  14441. if ($line_style) {
  14442. $this->SetLineStyle($line_style);
  14443. }
  14444. $this->_outPoint($x0, $y0);
  14445. foreach ($segments as $segment) {
  14446. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  14447. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  14448. }
  14449. $this->_out($op);
  14450. }
  14451. /**
  14452. * Draws an ellipse.
  14453. * An ellipse is formed from n Bezier curves.
  14454. * @param $x0 (float) Abscissa of center point.
  14455. * @param $y0 (float) Ordinate of center point.
  14456. * @param $rx (float) Horizontal radius.
  14457. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  14458. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  14459. * @param $astart: (float) Angle start of draw line. Default value: 0.
  14460. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  14461. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14462. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  14463. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14464. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  14465. * @author Nicola Asuni
  14466. * @public
  14467. * @since 2.1.000 (2008-01-08)
  14468. */
  14469. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  14470. if ($this->empty_string($ry) OR ($ry == 0)) {
  14471. $ry = $rx;
  14472. }
  14473. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14474. $this->SetFillColorArray($fill_color);
  14475. }
  14476. $op = $this->getPathPaintOperator($style);
  14477. if ($op == 'f') {
  14478. $line_style = array();
  14479. }
  14480. if ($line_style) {
  14481. $this->SetLineStyle($line_style);
  14482. }
  14483. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  14484. $this->_out($op);
  14485. }
  14486. /**
  14487. * Append an elliptical arc to the current path.
  14488. * An ellipse is formed from n Bezier curves.
  14489. * @param $xc (float) Abscissa of center point.
  14490. * @param $yc (float) Ordinate of center point.
  14491. * @param $rx (float) Horizontal radius.
  14492. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  14493. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  14494. * @param $angs: (float) Angle start of draw line. Default value: 0.
  14495. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  14496. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  14497. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  14498. * @param $startpoint (boolean) if true output a starting point.
  14499. * @param $ccw (boolean) if true draws in counter-clockwise.
  14500. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  14501. * @return array bounding box coordinates (x min, y min, x max, y max)
  14502. * @author Nicola Asuni
  14503. * @protected
  14504. * @since 4.9.019 (2010-04-26)
  14505. */
  14506. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  14507. $k = $this->k;
  14508. if ($nc < 2) {
  14509. $nc = 2;
  14510. }
  14511. $xmin = 2147483647;
  14512. $ymin = 2147483647;
  14513. $xmax = 0;
  14514. $ymax = 0;
  14515. if ($pie) {
  14516. // center of the arc
  14517. $this->_outPoint($xc, $yc);
  14518. }
  14519. $xang = deg2rad((float) $xang);
  14520. $angs = deg2rad((float) $angs);
  14521. $angf = deg2rad((float) $angf);
  14522. if ($svg) {
  14523. $as = $angs;
  14524. $af = $angf;
  14525. } else {
  14526. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  14527. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  14528. }
  14529. if ($as < 0) {
  14530. $as += (2 * M_PI);
  14531. }
  14532. if ($af < 0) {
  14533. $af += (2 * M_PI);
  14534. }
  14535. if ($ccw AND ($as > $af)) {
  14536. // reverse rotation
  14537. $as -= (2 * M_PI);
  14538. } elseif (!$ccw AND ($as < $af)) {
  14539. // reverse rotation
  14540. $af -= (2 * M_PI);
  14541. }
  14542. $total_angle = ($af - $as);
  14543. if ($nc < 2) {
  14544. $nc = 2;
  14545. }
  14546. // total arcs to draw
  14547. $nc *= (2 * abs($total_angle) / M_PI);
  14548. $nc = round($nc) + 1;
  14549. // angle of each arc
  14550. $arcang = ($total_angle / $nc);
  14551. // center point in PDF coordinates
  14552. $x0 = $xc;
  14553. $y0 = ($this->h - $yc);
  14554. // starting angle
  14555. $ang = $as;
  14556. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  14557. $cos_xang = cos($xang);
  14558. $sin_xang = sin($xang);
  14559. $cos_ang = cos($ang);
  14560. $sin_ang = sin($ang);
  14561. // first arc point
  14562. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  14563. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  14564. // first Bezier control point
  14565. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  14566. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  14567. if ($pie) {
  14568. // line from center to arc starting point
  14569. $this->_outLine($px1, $this->h - $py1);
  14570. } elseif ($startpoint) {
  14571. // arc starting point
  14572. $this->_outPoint($px1, $this->h - $py1);
  14573. }
  14574. // draw arcs
  14575. for ($i = 1; $i <= $nc; ++$i) {
  14576. // starting angle
  14577. $ang = $as + ($i * $arcang);
  14578. if ($i == $nc) {
  14579. $ang = $af;
  14580. }
  14581. $cos_ang = cos($ang);
  14582. $sin_ang = sin($ang);
  14583. // second arc point
  14584. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  14585. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  14586. // second Bezier control point
  14587. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  14588. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  14589. // draw arc
  14590. $cx1 = ($px1 + $qx1);
  14591. $cy1 = ($this->h - ($py1 + $qy1));
  14592. $cx2 = ($px2 - $qx2);
  14593. $cy2 = ($this->h - ($py2 - $qy2));
  14594. $cx3 = $px2;
  14595. $cy3 = ($this->h - $py2);
  14596. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  14597. // get bounding box coordinates
  14598. $xmin = min($xmin, $cx1, $cx2, $cx3);
  14599. $ymin = min($ymin, $cy1, $cy2, $cy3);
  14600. $xmax = max($xmax, $cx1, $cx2, $cx3);
  14601. $ymax = max($ymax, $cy1, $cy2, $cy3);
  14602. // move to next point
  14603. $px1 = $px2;
  14604. $py1 = $py2;
  14605. $qx1 = $qx2;
  14606. $qy1 = $qy2;
  14607. }
  14608. if ($pie) {
  14609. $this->_outLine($xc, $yc);
  14610. // get bounding box coordinates
  14611. $xmin = min($xmin, $xc);
  14612. $ymin = min($ymin, $yc);
  14613. $xmax = max($xmax, $xc);
  14614. $ymax = max($ymax, $yc);
  14615. }
  14616. return array($xmin, $ymin, $xmax, $ymax);
  14617. }
  14618. /**
  14619. * Draws a circle.
  14620. * A circle is formed from n Bezier curves.
  14621. * @param $x0 (float) Abscissa of center point.
  14622. * @param $y0 (float) Ordinate of center point.
  14623. * @param $r (float) Radius.
  14624. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  14625. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  14626. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14627. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  14628. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  14629. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  14630. * @public
  14631. * @since 2.1.000 (2008-01-08)
  14632. */
  14633. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  14634. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  14635. }
  14636. /**
  14637. * Draws a polygonal line
  14638. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  14639. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14640. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  14641. * <ul>
  14642. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  14643. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  14644. * </ul>
  14645. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  14646. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14647. * @since 4.8.003 (2009-09-15)
  14648. * @public
  14649. */
  14650. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  14651. $this->Polygon($p, $style, $line_style, $fill_color, false);
  14652. }
  14653. /**
  14654. * Draws a polygon.
  14655. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  14656. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14657. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  14658. * <ul>
  14659. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  14660. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  14661. * </ul>
  14662. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  14663. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14664. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  14665. * @public
  14666. * @since 2.1.000 (2008-01-08)
  14667. */
  14668. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  14669. $nc = count($p); // number of coordinates
  14670. $np = $nc / 2; // number of points
  14671. if ($closed) {
  14672. // close polygon by adding the first 2 points at the end (one line)
  14673. for ($i = 0; $i < 4; ++$i) {
  14674. $p[$nc + $i] = $p[$i];
  14675. }
  14676. // copy style for the last added line
  14677. if (isset($line_style[0])) {
  14678. $line_style[$np] = $line_style[0];
  14679. }
  14680. $nc += 4;
  14681. }
  14682. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14683. $this->SetFillColorArray($fill_color);
  14684. }
  14685. $op = $this->getPathPaintOperator($style);
  14686. if ($op == 'f') {
  14687. $line_style = array();
  14688. }
  14689. $draw = true;
  14690. if ($line_style) {
  14691. if (isset($line_style['all'])) {
  14692. $this->SetLineStyle($line_style['all']);
  14693. } else {
  14694. $draw = false;
  14695. if ($op == 'B') {
  14696. // draw fill
  14697. $op = 'f';
  14698. $this->_outPoint($p[0], $p[1]);
  14699. for ($i = 2; $i < $nc; $i = $i + 2) {
  14700. $this->_outLine($p[$i], $p[$i + 1]);
  14701. }
  14702. $this->_out($op);
  14703. }
  14704. // draw outline
  14705. $this->_outPoint($p[0], $p[1]);
  14706. for ($i = 2; $i < $nc; $i = $i + 2) {
  14707. $line_num = ($i / 2) - 1;
  14708. if (isset($line_style[$line_num])) {
  14709. if ($line_style[$line_num] != 0) {
  14710. if (is_array($line_style[$line_num])) {
  14711. $this->_out('S');
  14712. $this->SetLineStyle($line_style[$line_num]);
  14713. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  14714. $this->_outLine($p[$i], $p[$i + 1]);
  14715. $this->_out('S');
  14716. $this->_outPoint($p[$i], $p[$i + 1]);
  14717. } else {
  14718. $this->_outLine($p[$i], $p[$i + 1]);
  14719. }
  14720. }
  14721. } else {
  14722. $this->_outLine($p[$i], $p[$i + 1]);
  14723. }
  14724. }
  14725. $this->_out($op);
  14726. }
  14727. }
  14728. if ($draw) {
  14729. $this->_outPoint($p[0], $p[1]);
  14730. for ($i = 2; $i < $nc; $i = $i + 2) {
  14731. $this->_outLine($p[$i], $p[$i + 1]);
  14732. }
  14733. $this->_out($op);
  14734. }
  14735. }
  14736. /**
  14737. * Draws a regular polygon.
  14738. * @param $x0 (float) Abscissa of center point.
  14739. * @param $y0 (float) Ordinate of center point.
  14740. * @param $r: (float) Radius of inscribed circle.
  14741. * @param $ns (integer) Number of sides.
  14742. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  14743. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  14744. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14745. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  14746. * <ul>
  14747. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  14748. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  14749. * </ul>
  14750. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  14751. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  14752. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  14753. * <ul>
  14754. * <li>D or empty string: Draw (default).</li>
  14755. * <li>F: Fill.</li>
  14756. * <li>DF or FD: Draw and fill.</li>
  14757. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  14758. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  14759. * </ul>
  14760. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  14761. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  14762. * @public
  14763. * @since 2.1.000 (2008-01-08)
  14764. */
  14765. 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()) {
  14766. if (3 > $ns) {
  14767. $ns = 3;
  14768. }
  14769. if ($draw_circle) {
  14770. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  14771. }
  14772. $p = array();
  14773. for ($i = 0; $i < $ns; ++$i) {
  14774. $a = $angle + ($i * 360 / $ns);
  14775. $a_rad = deg2rad((float) $a);
  14776. $p[] = $x0 + ($r * sin($a_rad));
  14777. $p[] = $y0 + ($r * cos($a_rad));
  14778. }
  14779. $this->Polygon($p, $style, $line_style, $fill_color);
  14780. }
  14781. /**
  14782. * Draws a star polygon
  14783. * @param $x0 (float) Abscissa of center point.
  14784. * @param $y0 (float) Ordinate of center point.
  14785. * @param $r (float) Radius of inscribed circle.
  14786. * @param $nv (integer) Number of vertices.
  14787. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  14788. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  14789. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  14790. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14791. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  14792. * <ul>
  14793. * <li>all: Line style of all sides. Array like for
  14794. * SetLineStyle().</li>
  14795. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  14796. * </ul>
  14797. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  14798. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  14799. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  14800. * <ul>
  14801. * <li>D or empty string: Draw (default).</li>
  14802. * <li>F: Fill.</li>
  14803. * <li>DF or FD: Draw and fill.</li>
  14804. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  14805. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  14806. * </ul>
  14807. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  14808. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  14809. * @public
  14810. * @since 2.1.000 (2008-01-08)
  14811. */
  14812. 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()) {
  14813. if ($nv < 2) {
  14814. $nv = 2;
  14815. }
  14816. if ($draw_circle) {
  14817. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  14818. }
  14819. $p2 = array();
  14820. $visited = array();
  14821. for ($i = 0; $i < $nv; ++$i) {
  14822. $a = $angle + ($i * 360 / $nv);
  14823. $a_rad = deg2rad((float) $a);
  14824. $p2[] = $x0 + ($r * sin($a_rad));
  14825. $p2[] = $y0 + ($r * cos($a_rad));
  14826. $visited[] = false;
  14827. }
  14828. $p = array();
  14829. $i = 0;
  14830. do {
  14831. $p[] = $p2[$i * 2];
  14832. $p[] = $p2[($i * 2) + 1];
  14833. $visited[$i] = true;
  14834. $i += $ng;
  14835. $i %= $nv;
  14836. } while (!$visited[$i]);
  14837. $this->Polygon($p, $style, $line_style, $fill_color);
  14838. }
  14839. /**
  14840. * Draws a rounded rectangle.
  14841. * @param $x (float) Abscissa of upper-left corner.
  14842. * @param $y (float) Ordinate of upper-left corner.
  14843. * @param $w (float) Width.
  14844. * @param $h (float) Height.
  14845. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  14846. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
  14847. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14848. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  14849. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14850. * @public
  14851. * @since 2.1.000 (2008-01-08)
  14852. */
  14853. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  14854. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  14855. }
  14856. /**
  14857. * Draws a rounded rectangle.
  14858. * @param $x (float) Abscissa of upper-left corner.
  14859. * @param $y (float) Ordinate of upper-left corner.
  14860. * @param $w (float) Width.
  14861. * @param $h (float) Height.
  14862. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  14863. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  14864. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
  14865. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14866. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  14867. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  14868. * @public
  14869. * @since 4.9.019 (2010-04-22)
  14870. */
  14871. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  14872. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  14873. // Not rounded
  14874. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  14875. return;
  14876. }
  14877. // Rounded
  14878. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14879. $this->SetFillColorArray($fill_color);
  14880. }
  14881. $op = $this->getPathPaintOperator($style);
  14882. if ($op == 'f') {
  14883. $border_style = array();
  14884. }
  14885. if ($border_style) {
  14886. $this->SetLineStyle($border_style);
  14887. }
  14888. $MyArc = 4 / 3 * (sqrt(2) - 1);
  14889. $this->_outPoint($x + $rx, $y);
  14890. $xc = $x + $w - $rx;
  14891. $yc = $y + $ry;
  14892. $this->_outLine($xc, $y);
  14893. if ($round_corner[0]) {
  14894. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  14895. } else {
  14896. $this->_outLine($x + $w, $y);
  14897. }
  14898. $xc = $x + $w - $rx;
  14899. $yc = $y + $h - $ry;
  14900. $this->_outLine($x + $w, $yc);
  14901. if ($round_corner[1]) {
  14902. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  14903. } else {
  14904. $this->_outLine($x + $w, $y + $h);
  14905. }
  14906. $xc = $x + $rx;
  14907. $yc = $y + $h - $ry;
  14908. $this->_outLine($xc, $y + $h);
  14909. if ($round_corner[2]) {
  14910. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  14911. } else {
  14912. $this->_outLine($x, $y + $h);
  14913. }
  14914. $xc = $x + $rx;
  14915. $yc = $y + $ry;
  14916. $this->_outLine($x, $yc);
  14917. if ($round_corner[3]) {
  14918. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  14919. } else {
  14920. $this->_outLine($x, $y);
  14921. $this->_outLine($x + $rx, $y);
  14922. }
  14923. $this->_out($op);
  14924. }
  14925. /**
  14926. * Draws a grahic arrow.
  14927. * @param $x0 (float) Abscissa of first point.
  14928. * @param $y0 (float) Ordinate of first point.
  14929. * @param $x1 (float) Abscissa of second point.
  14930. * @param $y1 (float) Ordinate of second point.
  14931. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  14932. * @param $arm_size (float) length of arrowhead arms
  14933. * @param $arm_angle (int) angle between an arm and the shaft
  14934. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  14935. * @since 4.6.018 (2009-07-10)
  14936. */
  14937. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  14938. // getting arrow direction angle
  14939. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  14940. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  14941. if ($dir_angle < 0) {
  14942. $dir_angle += (2 * M_PI);
  14943. }
  14944. $arm_angle = deg2rad($arm_angle);
  14945. $sx1 = $x1;
  14946. $sy1 = $y1;
  14947. if ($head_style > 0) {
  14948. // calculate the stopping point for the arrow shaft
  14949. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  14950. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  14951. }
  14952. // main arrow line / shaft
  14953. $this->Line($x0, $y0, $sx1, $sy1);
  14954. // left arrowhead arm tip
  14955. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  14956. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  14957. // right arrowhead arm tip
  14958. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  14959. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  14960. $mode = 'D';
  14961. $style = array();
  14962. switch ($head_style) {
  14963. case 0: {
  14964. // draw only arrowhead arms
  14965. $mode = 'D';
  14966. $style = array(1, 1, 0);
  14967. break;
  14968. }
  14969. case 1: {
  14970. // draw closed arrowhead, but no fill
  14971. $mode = 'D';
  14972. break;
  14973. }
  14974. case 2: {
  14975. // closed and filled arrowhead
  14976. $mode = 'DF';
  14977. break;
  14978. }
  14979. case 3: {
  14980. // filled arrowhead
  14981. $mode = 'F';
  14982. break;
  14983. }
  14984. }
  14985. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  14986. }
  14987. // END GRAPHIC FUNCTIONS SECTION -----------------------
  14988. // BIDIRECTIONAL TEXT SECTION --------------------------
  14989. /**
  14990. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  14991. * @param $str (string) string to manipulate.
  14992. * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
  14993. * @param $forcertl (bool) if true forces RTL text direction
  14994. * @return string
  14995. * @protected
  14996. * @author Nicola Asuni
  14997. * @since 2.1.000 (2008-01-08)
  14998. */
  14999. protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
  15000. return $this->utf8StrArrRev($this->UTF8StringToArray($str), $str, $setbom, $forcertl);
  15001. }
  15002. /**
  15003. * Reverse the RLT substrings array using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  15004. * @param $arr (array) array of unicode values.
  15005. * @param $str (string) string to manipulate (or empty value).
  15006. * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
  15007. * @param $forcertl (bool) if true forces RTL text direction
  15008. * @return string
  15009. * @protected
  15010. * @author Nicola Asuni
  15011. * @since 4.9.000 (2010-03-27)
  15012. */
  15013. protected function utf8StrArrRev($arr, $str='', $setbom=false, $forcertl=false) {
  15014. return $this->arrUTF8ToUTF16BE($this->utf8Bidi($arr, $str, $forcertl), $setbom);
  15015. }
  15016. /**
  15017. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  15018. * @param $ta (array) array of characters composing the string.
  15019. * @param $str (string) string to process
  15020. * @param $forcertl (bool) if 'R' forces RTL, if 'L' forces LTR
  15021. * @return array of unicode chars
  15022. * @author Nicola Asuni
  15023. * @protected
  15024. * @since 2.4.000 (2008-03-06)
  15025. */
  15026. protected function utf8Bidi($ta, $str='', $forcertl=false) {
  15027. // paragraph embedding level
  15028. $pel = 0;
  15029. // max level
  15030. $maxlevel = 0;
  15031. if ($this->empty_string($str)) {
  15032. // create string from array
  15033. $str = $this->UTF8ArrSubString($ta);
  15034. }
  15035. // check if string contains arabic text
  15036. if (preg_match($this->unicode->uni_RE_PATTERN_ARABIC, $str)) {
  15037. $arabic = true;
  15038. } else {
  15039. $arabic = false;
  15040. }
  15041. // check if string contains RTL text
  15042. if (!($forcertl OR $arabic OR preg_match($this->unicode->uni_RE_PATTERN_RTL, $str))) {
  15043. return $ta;
  15044. }
  15045. // get number of chars
  15046. $numchars = count($ta);
  15047. if ($forcertl == 'R') {
  15048. $pel = 1;
  15049. } elseif ($forcertl == 'L') {
  15050. $pel = 0;
  15051. } else {
  15052. // P2. In each paragraph, find the first character of type L, AL, or R.
  15053. // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
  15054. for ($i=0; $i < $numchars; ++$i) {
  15055. $type = $this->unicode->uni_type[$ta[$i]];
  15056. if ($type == 'L') {
  15057. $pel = 0;
  15058. break;
  15059. } elseif (($type == 'AL') OR ($type == 'R')) {
  15060. $pel = 1;
  15061. break;
  15062. }
  15063. }
  15064. }
  15065. // Current Embedding Level
  15066. $cel = $pel;
  15067. // directional override status
  15068. $dos = 'N';
  15069. $remember = array();
  15070. // start-of-level-run
  15071. $sor = $pel % 2 ? 'R' : 'L';
  15072. $eor = $sor;
  15073. // Array of characters data
  15074. $chardata = Array();
  15075. // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
  15076. // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
  15077. for ($i=0; $i < $numchars; ++$i) {
  15078. if ($ta[$i] == $this->unicode->uni_RLE) {
  15079. // X2. With each RLE, compute the least greater odd embedding level.
  15080. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
  15081. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15082. $next_level = $cel + ($cel % 2) + 1;
  15083. if ($next_level < 62) {
  15084. $remember[] = array('num' => $this->unicode->uni_RLE, 'cel' => $cel, 'dos' => $dos);
  15085. $cel = $next_level;
  15086. $dos = 'N';
  15087. $sor = $eor;
  15088. $eor = $cel % 2 ? 'R' : 'L';
  15089. }
  15090. } elseif ($ta[$i] == $this->unicode->uni_LRE) {
  15091. // X3. With each LRE, compute the least greater even embedding level.
  15092. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
  15093. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15094. $next_level = $cel + 2 - ($cel % 2);
  15095. if ( $next_level < 62 ) {
  15096. $remember[] = array('num' => $this->unicode->uni_LRE, 'cel' => $cel, 'dos' => $dos);
  15097. $cel = $next_level;
  15098. $dos = 'N';
  15099. $sor = $eor;
  15100. $eor = $cel % 2 ? 'R' : 'L';
  15101. }
  15102. } elseif ($ta[$i] == $this->unicode->uni_RLO) {
  15103. // X4. With each RLO, compute the least greater odd embedding level.
  15104. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
  15105. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15106. $next_level = $cel + ($cel % 2) + 1;
  15107. if ($next_level < 62) {
  15108. $remember[] = array('num' => $this->unicode->uni_RLO, 'cel' => $cel, 'dos' => $dos);
  15109. $cel = $next_level;
  15110. $dos = 'R';
  15111. $sor = $eor;
  15112. $eor = $cel % 2 ? 'R' : 'L';
  15113. }
  15114. } elseif ($ta[$i] == $this->unicode->uni_LRO) {
  15115. // X5. With each LRO, compute the least greater even embedding level.
  15116. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
  15117. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15118. $next_level = $cel + 2 - ($cel % 2);
  15119. if ( $next_level < 62 ) {
  15120. $remember[] = array('num' => $this->unicode->uni_LRO, 'cel' => $cel, 'dos' => $dos);
  15121. $cel = $next_level;
  15122. $dos = 'L';
  15123. $sor = $eor;
  15124. $eor = $cel % 2 ? 'R' : 'L';
  15125. }
  15126. } elseif ($ta[$i] == $this->unicode->uni_PDF) {
  15127. // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
  15128. if (count($remember)) {
  15129. $last = count($remember ) - 1;
  15130. if (($remember[$last]['num'] == $this->unicode->uni_RLE) OR
  15131. ($remember[$last]['num'] == $this->unicode->uni_LRE) OR
  15132. ($remember[$last]['num'] == $this->unicode->uni_RLO) OR
  15133. ($remember[$last]['num'] == $this->unicode->uni_LRO)) {
  15134. $match = array_pop($remember);
  15135. $cel = $match['cel'];
  15136. $dos = $match['dos'];
  15137. $sor = $eor;
  15138. $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
  15139. }
  15140. }
  15141. } elseif (($ta[$i] != $this->unicode->uni_RLE) AND
  15142. ($ta[$i] != $this->unicode->uni_LRE) AND
  15143. ($ta[$i] != $this->unicode->uni_RLO) AND
  15144. ($ta[$i] != $this->unicode->uni_LRO) AND
  15145. ($ta[$i] != $this->unicode->uni_PDF)) {
  15146. // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
  15147. // a. Set the level of the current character to the current embedding level.
  15148. // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
  15149. if ($dos != 'N') {
  15150. $chardir = $dos;
  15151. } else {
  15152. if (isset($this->unicode->uni_type[$ta[$i]])) {
  15153. $chardir = $this->unicode->uni_type[$ta[$i]];
  15154. } else {
  15155. $chardir = 'L';
  15156. }
  15157. }
  15158. // stores string characters and other information
  15159. $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
  15160. }
  15161. } // end for each char
  15162. // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
  15163. // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
  15164. // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
  15165. // 3.3.3 Resolving Weak Types
  15166. // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
  15167. // Nonspacing marks are now resolved based on the previous characters.
  15168. $numchars = count($chardata);
  15169. // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
  15170. $prevlevel = -1; // track level changes
  15171. $levcount = 0; // counts consecutive chars at the same level
  15172. for ($i=0; $i < $numchars; ++$i) {
  15173. if ($chardata[$i]['type'] == 'NSM') {
  15174. if ($levcount) {
  15175. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15176. } elseif ($i > 0) {
  15177. $chardata[$i]['type'] = $chardata[($i-1)]['type'];
  15178. }
  15179. }
  15180. if ($chardata[$i]['level'] != $prevlevel) {
  15181. $levcount = 0;
  15182. } else {
  15183. ++$levcount;
  15184. }
  15185. $prevlevel = $chardata[$i]['level'];
  15186. }
  15187. // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
  15188. $prevlevel = -1;
  15189. $levcount = 0;
  15190. for ($i=0; $i < $numchars; ++$i) {
  15191. if ($chardata[$i]['char'] == 'EN') {
  15192. for ($j=$levcount; $j >= 0; $j--) {
  15193. if ($chardata[$j]['type'] == 'AL') {
  15194. $chardata[$i]['type'] = 'AN';
  15195. } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
  15196. break;
  15197. }
  15198. }
  15199. }
  15200. if ($chardata[$i]['level'] != $prevlevel) {
  15201. $levcount = 0;
  15202. } else {
  15203. ++$levcount;
  15204. }
  15205. $prevlevel = $chardata[$i]['level'];
  15206. }
  15207. // W3. Change all ALs to R.
  15208. for ($i=0; $i < $numchars; ++$i) {
  15209. if ($chardata[$i]['type'] == 'AL') {
  15210. $chardata[$i]['type'] = 'R';
  15211. }
  15212. }
  15213. // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
  15214. $prevlevel = -1;
  15215. $levcount = 0;
  15216. for ($i=0; $i < $numchars; ++$i) {
  15217. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  15218. if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  15219. $chardata[$i]['type'] = 'EN';
  15220. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  15221. $chardata[$i]['type'] = 'EN';
  15222. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
  15223. $chardata[$i]['type'] = 'AN';
  15224. }
  15225. }
  15226. if ($chardata[$i]['level'] != $prevlevel) {
  15227. $levcount = 0;
  15228. } else {
  15229. ++$levcount;
  15230. }
  15231. $prevlevel = $chardata[$i]['level'];
  15232. }
  15233. // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
  15234. $prevlevel = -1;
  15235. $levcount = 0;
  15236. for ($i=0; $i < $numchars; ++$i) {
  15237. if ($chardata[$i]['type'] == 'ET') {
  15238. if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
  15239. $chardata[$i]['type'] = 'EN';
  15240. } else {
  15241. $j = $i+1;
  15242. while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
  15243. if ($chardata[$j]['type'] == 'EN') {
  15244. $chardata[$i]['type'] = 'EN';
  15245. break;
  15246. } elseif ($chardata[$j]['type'] != 'ET') {
  15247. break;
  15248. }
  15249. ++$j;
  15250. }
  15251. }
  15252. }
  15253. if ($chardata[$i]['level'] != $prevlevel) {
  15254. $levcount = 0;
  15255. } else {
  15256. ++$levcount;
  15257. }
  15258. $prevlevel = $chardata[$i]['level'];
  15259. }
  15260. // W6. Otherwise, separators and terminators change to Other Neutral.
  15261. $prevlevel = -1;
  15262. $levcount = 0;
  15263. for ($i=0; $i < $numchars; ++$i) {
  15264. if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
  15265. $chardata[$i]['type'] = 'ON';
  15266. }
  15267. if ($chardata[$i]['level'] != $prevlevel) {
  15268. $levcount = 0;
  15269. } else {
  15270. ++$levcount;
  15271. }
  15272. $prevlevel = $chardata[$i]['level'];
  15273. }
  15274. //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
  15275. $prevlevel = -1;
  15276. $levcount = 0;
  15277. for ($i=0; $i < $numchars; ++$i) {
  15278. if ($chardata[$i]['char'] == 'EN') {
  15279. for ($j=$levcount; $j >= 0; $j--) {
  15280. if ($chardata[$j]['type'] == 'L') {
  15281. $chardata[$i]['type'] = 'L';
  15282. } elseif ($chardata[$j]['type'] == 'R') {
  15283. break;
  15284. }
  15285. }
  15286. }
  15287. if ($chardata[$i]['level'] != $prevlevel) {
  15288. $levcount = 0;
  15289. } else {
  15290. ++$levcount;
  15291. }
  15292. $prevlevel = $chardata[$i]['level'];
  15293. }
  15294. // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
  15295. $prevlevel = -1;
  15296. $levcount = 0;
  15297. for ($i=0; $i < $numchars; ++$i) {
  15298. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  15299. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  15300. $chardata[$i]['type'] = 'L';
  15301. } elseif (($chardata[$i]['type'] == 'N') AND
  15302. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  15303. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  15304. $chardata[$i]['type'] = 'R';
  15305. } elseif ($chardata[$i]['type'] == 'N') {
  15306. // N2. Any remaining neutrals take the embedding direction
  15307. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15308. }
  15309. } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  15310. // first char
  15311. if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  15312. $chardata[$i]['type'] = 'L';
  15313. } elseif (($chardata[$i]['type'] == 'N') AND
  15314. (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
  15315. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  15316. $chardata[$i]['type'] = 'R';
  15317. } elseif ($chardata[$i]['type'] == 'N') {
  15318. // N2. Any remaining neutrals take the embedding direction
  15319. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15320. }
  15321. } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
  15322. //last char
  15323. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
  15324. $chardata[$i]['type'] = 'L';
  15325. } elseif (($chardata[$i]['type'] == 'N') AND
  15326. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  15327. (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
  15328. $chardata[$i]['type'] = 'R';
  15329. } elseif ($chardata[$i]['type'] == 'N') {
  15330. // N2. Any remaining neutrals take the embedding direction
  15331. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15332. }
  15333. } elseif ($chardata[$i]['type'] == 'N') {
  15334. // N2. Any remaining neutrals take the embedding direction
  15335. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15336. }
  15337. if ($chardata[$i]['level'] != $prevlevel) {
  15338. $levcount = 0;
  15339. } else {
  15340. ++$levcount;
  15341. }
  15342. $prevlevel = $chardata[$i]['level'];
  15343. }
  15344. // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
  15345. // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
  15346. for ($i=0; $i < $numchars; ++$i) {
  15347. $odd = $chardata[$i]['level'] % 2;
  15348. if ($odd) {
  15349. if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  15350. $chardata[$i]['level'] += 1;
  15351. }
  15352. } else {
  15353. if ($chardata[$i]['type'] == 'R') {
  15354. $chardata[$i]['level'] += 1;
  15355. } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  15356. $chardata[$i]['level'] += 2;
  15357. }
  15358. }
  15359. $maxlevel = max($chardata[$i]['level'],$maxlevel);
  15360. }
  15361. // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
  15362. // 1. Segment separators,
  15363. // 2. Paragraph separators,
  15364. // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
  15365. // 4. Any sequence of white space characters at the end of the line.
  15366. for ($i=0; $i < $numchars; ++$i) {
  15367. if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
  15368. $chardata[$i]['level'] = $pel;
  15369. } elseif ($chardata[$i]['type'] == 'WS') {
  15370. $j = $i+1;
  15371. while ($j < $numchars) {
  15372. if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
  15373. (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
  15374. $chardata[$i]['level'] = $pel;
  15375. break;
  15376. } elseif ($chardata[$j]['type'] != 'WS') {
  15377. break;
  15378. }
  15379. ++$j;
  15380. }
  15381. }
  15382. }
  15383. // Arabic Shaping
  15384. // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
  15385. if ($arabic) {
  15386. $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
  15387. $alfletter = array(1570,1571,1573,1575);
  15388. $chardata2 = $chardata;
  15389. $laaletter = false;
  15390. $charAL = array();
  15391. $x = 0;
  15392. for ($i=0; $i < $numchars; ++$i) {
  15393. if (($this->unicode->uni_type[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
  15394. $charAL[$x] = $chardata[$i];
  15395. $charAL[$x]['i'] = $i;
  15396. $chardata[$i]['x'] = $x;
  15397. ++$x;
  15398. }
  15399. }
  15400. $numAL = $x;
  15401. for ($i=0; $i < $numchars; ++$i) {
  15402. $thischar = $chardata[$i];
  15403. if ($i > 0) {
  15404. $prevchar = $chardata[($i-1)];
  15405. } else {
  15406. $prevchar = false;
  15407. }
  15408. if (($i+1) < $numchars) {
  15409. $nextchar = $chardata[($i+1)];
  15410. } else {
  15411. $nextchar = false;
  15412. }
  15413. if ($this->unicode->uni_type[$thischar['char']] == 'AL') {
  15414. $x = $thischar['x'];
  15415. if ($x > 0) {
  15416. $prevchar = $charAL[($x-1)];
  15417. } else {
  15418. $prevchar = false;
  15419. }
  15420. if (($x+1) < $numAL) {
  15421. $nextchar = $charAL[($x+1)];
  15422. } else {
  15423. $nextchar = false;
  15424. }
  15425. // if laa letter
  15426. if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
  15427. $arabicarr = $this->unicode->uni_laa_array;
  15428. $laaletter = true;
  15429. if ($x > 1) {
  15430. $prevchar = $charAL[($x-2)];
  15431. } else {
  15432. $prevchar = false;
  15433. }
  15434. } else {
  15435. $arabicarr = $this->unicode->uni_arabicsubst;
  15436. $laaletter = false;
  15437. }
  15438. if (($prevchar !== false) AND ($nextchar !== false) AND
  15439. (($this->unicode->uni_type[$prevchar['char']] == 'AL') OR ($this->unicode->uni_type[$prevchar['char']] == 'NSM')) AND
  15440. (($this->unicode->uni_type[$nextchar['char']] == 'AL') OR ($this->unicode->uni_type[$nextchar['char']] == 'NSM')) AND
  15441. ($prevchar['type'] == $thischar['type']) AND
  15442. ($nextchar['type'] == $thischar['type']) AND
  15443. ($nextchar['char'] != 1567)) {
  15444. if (in_array($prevchar['char'], $endedletter)) {
  15445. if (isset($arabicarr[$thischar['char']][2])) {
  15446. // initial
  15447. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  15448. }
  15449. } else {
  15450. if (isset($arabicarr[$thischar['char']][3])) {
  15451. // medial
  15452. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
  15453. }
  15454. }
  15455. } elseif (($nextchar !== false) AND
  15456. (($this->unicode->uni_type[$nextchar['char']] == 'AL') OR ($this->unicode->uni_type[$nextchar['char']] == 'NSM')) AND
  15457. ($nextchar['type'] == $thischar['type']) AND
  15458. ($nextchar['char'] != 1567)) {
  15459. if (isset($arabicarr[$chardata[$i]['char']][2])) {
  15460. // initial
  15461. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  15462. }
  15463. } elseif ((($prevchar !== false) AND
  15464. (($this->unicode->uni_type[$prevchar['char']] == 'AL') OR ($this->unicode->uni_type[$prevchar['char']] == 'NSM')) AND
  15465. ($prevchar['type'] == $thischar['type'])) OR
  15466. (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
  15467. // final
  15468. if (($i > 1) AND ($thischar['char'] == 1607) AND
  15469. ($chardata[$i-1]['char'] == 1604) AND
  15470. ($chardata[$i-2]['char'] == 1604)) {
  15471. //Allah Word
  15472. // mark characters to delete with false
  15473. $chardata2[$i-2]['char'] = false;
  15474. $chardata2[$i-1]['char'] = false;
  15475. $chardata2[$i]['char'] = 65010;
  15476. } else {
  15477. if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
  15478. if (isset($arabicarr[$thischar['char']][0])) {
  15479. // isolated
  15480. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  15481. }
  15482. } else {
  15483. if (isset($arabicarr[$thischar['char']][1])) {
  15484. // final
  15485. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
  15486. }
  15487. }
  15488. }
  15489. } elseif (isset($arabicarr[$thischar['char']][0])) {
  15490. // isolated
  15491. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  15492. }
  15493. // if laa letter
  15494. if ($laaletter) {
  15495. // mark characters to delete with false
  15496. $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
  15497. }
  15498. } // end if AL (Arabic Letter)
  15499. } // end for each char
  15500. /*
  15501. * Combining characters that can occur with Arabic Shadda (0651 HEX, 1617 DEC) are replaced.
  15502. * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
  15503. */
  15504. for ($i = 0; $i < ($numchars-1); ++$i) {
  15505. if (($chardata2[$i]['char'] == 1617) AND (isset($this->unicode->uni_diacritics[($chardata2[$i+1]['char'])]))) {
  15506. // check if the subtitution font is defined on current font
  15507. if (isset($this->CurrentFont['cw'][($this->unicode->uni_diacritics[($chardata2[$i+1]['char'])])])) {
  15508. $chardata2[$i]['char'] = false;
  15509. $chardata2[$i+1]['char'] = $this->unicode->uni_diacritics[($chardata2[$i+1]['char'])];
  15510. }
  15511. }
  15512. }
  15513. // remove marked characters
  15514. foreach ($chardata2 as $key => $value) {
  15515. if ($value['char'] === false) {
  15516. unset($chardata2[$key]);
  15517. }
  15518. }
  15519. $chardata = array_values($chardata2);
  15520. $numchars = count($chardata);
  15521. unset($chardata2);
  15522. unset($arabicarr);
  15523. unset($laaletter);
  15524. unset($charAL);
  15525. }
  15526. // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
  15527. for ($j=$maxlevel; $j > 0; $j--) {
  15528. $ordarray = Array();
  15529. $revarr = Array();
  15530. $onlevel = false;
  15531. for ($i=0; $i < $numchars; ++$i) {
  15532. if ($chardata[$i]['level'] >= $j) {
  15533. $onlevel = true;
  15534. if (isset($this->unicode->uni_mirror[$chardata[$i]['char']])) {
  15535. // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
  15536. $chardata[$i]['char'] = $this->unicode->uni_mirror[$chardata[$i]['char']];
  15537. }
  15538. $revarr[] = $chardata[$i];
  15539. } else {
  15540. if ($onlevel) {
  15541. $revarr = array_reverse($revarr);
  15542. $ordarray = array_merge($ordarray, $revarr);
  15543. $revarr = Array();
  15544. $onlevel = false;
  15545. }
  15546. $ordarray[] = $chardata[$i];
  15547. }
  15548. }
  15549. if ($onlevel) {
  15550. $revarr = array_reverse($revarr);
  15551. $ordarray = array_merge($ordarray, $revarr);
  15552. }
  15553. $chardata = $ordarray;
  15554. }
  15555. $ordarray = array();
  15556. for ($i=0; $i < $numchars; ++$i) {
  15557. $ordarray[] = $chardata[$i]['char'];
  15558. // store char values for subsetting
  15559. $this->CurrentFont['subsetchars'][$chardata[$i]['char']] = true;
  15560. }
  15561. // update font subsetchars
  15562. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  15563. return $ordarray;
  15564. }
  15565. // END OF BIDIRECTIONAL TEXT SECTION -------------------
  15566. /**
  15567. * Encode a name object.
  15568. * @param $name (string) Name object to encode.
  15569. * @return (string) Encoded name object.
  15570. * @protected
  15571. * @author Nicola Asuni
  15572. * @since 5.9.097 (2011-06-23)
  15573. */
  15574. protected function encodeNameObject($name) {
  15575. $escname = '';
  15576. $length = strlen($name);
  15577. for ($i = 0; $i < $length; ++$i) {
  15578. $chr = $name[$i];
  15579. if (preg_match('/[0-9a-zA-Z]/', $chr) == 1) {
  15580. $escname .= $chr;
  15581. } else {
  15582. $escname .= sprintf('#%02X', ord($chr));
  15583. }
  15584. }
  15585. return $escname;
  15586. }
  15587. /**
  15588. * Add a Named Destination.
  15589. * NOTE: destination names are unique, so only last entry will be saved.
  15590. * @param $name (string) Destination name.
  15591. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  15592. * @param $page (int) Target page number (leave empty for current page).
  15593. * @return (string) Stripped named destination identifier or false in case of error.
  15594. * @public
  15595. * @author Christian Deligant, Nicola Asuni
  15596. * @since 5.9.097 (2011-06-23)
  15597. */
  15598. public function setDestination($name, $y=-1, $page='') {
  15599. // remove unsupported characters
  15600. $name = $this->encodeNameObject($name);
  15601. if ($this->empty_string($name)) {
  15602. return false;
  15603. }
  15604. if ($y == -1) {
  15605. $y = $this->GetY();
  15606. }
  15607. if (empty($page)) {
  15608. $page = $this->PageNo();
  15609. if (empty($page)) {
  15610. return;
  15611. }
  15612. }
  15613. $this->dests[$name] = array('y' => $y, 'p' => $page);
  15614. return $name;
  15615. }
  15616. /**
  15617. * Return the Named Destination array.
  15618. * @return (array) Named Destination array.
  15619. * @public
  15620. * @author Nicola Asuni
  15621. * @since 5.9.097 (2011-06-23)
  15622. */
  15623. public function getDestination() {
  15624. return $this->dests;
  15625. }
  15626. /**
  15627. * Create a javascript PDF string.
  15628. * @protected
  15629. * @author Johannes Güntert, Nicola Asuni
  15630. * @since 5.9.098 (2011-06-23)
  15631. */
  15632. protected function _putdests() {
  15633. if (empty($this->dests)) {
  15634. return;
  15635. }
  15636. $this->n_dests = $this->_newobj();
  15637. $out = ' <<';
  15638. foreach($this->dests as $name => $o) {
  15639. $out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($o['p'])], ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  15640. }
  15641. $out .= ' >>';
  15642. $out .= "\n".'endobj';
  15643. $this->_out($out);
  15644. }
  15645. /**
  15646. * Adds a bookmark - alias for Bookmark().
  15647. * @param $txt (string) Bookmark description.
  15648. * @param $level (int) Bookmark level (minimum value is 0).
  15649. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  15650. * @param $page (int) Target page number (leave empty for current page).
  15651. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  15652. * @param $color (array) RGB color array (values from 0 to 255).
  15653. * @public
  15654. */
  15655. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0)) {
  15656. $this->Bookmark($txt, $level, $y, $page, $style, $color);
  15657. }
  15658. /**
  15659. * Adds a bookmark.
  15660. * @param $txt (string) Bookmark description.
  15661. * @param $level (int) Bookmark level (minimum value is 0).
  15662. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  15663. * @param $page (int) Target page number (leave empty for current page).
  15664. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  15665. * @param $color (array) RGB color array (values from 0 to 255).
  15666. * @public
  15667. * @author Olivier Plathey, Nicola Asuni
  15668. * @since 2.1.002 (2008-02-12)
  15669. */
  15670. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0)) {
  15671. if ($level < 0) {
  15672. $level = 0;
  15673. }
  15674. if (isset($this->outlines[0])) {
  15675. $lastoutline = end($this->outlines);
  15676. $maxlevel = $lastoutline['l'] + 1;
  15677. } else {
  15678. $maxlevel = 0;
  15679. }
  15680. if ($level > $maxlevel) {
  15681. $level = $maxlevel;
  15682. }
  15683. if ($y == -1) {
  15684. $y = $this->GetY();
  15685. }
  15686. if (empty($page)) {
  15687. $page = $this->PageNo();
  15688. if (empty($page)) {
  15689. return;
  15690. }
  15691. }
  15692. $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page, 's' => strtoupper($style), 'c' => $color);
  15693. }
  15694. /**
  15695. * Sort bookmarks for page and key.
  15696. * @protected
  15697. * @since 5.9.119 (2011-09-19)
  15698. */
  15699. protected function sortBookmarks() {
  15700. // get sorting columns
  15701. $outline_p = array();
  15702. $outline_y = array();
  15703. foreach ($this->outlines as $key => $row) {
  15704. $outline_p[$key] = $row['p'];
  15705. $outline_k[$key] = $key;
  15706. }
  15707. // sort outlines by page and original position
  15708. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  15709. }
  15710. /**
  15711. * Create a bookmark PDF string.
  15712. * @protected
  15713. * @author Olivier Plathey, Nicola Asuni
  15714. * @since 2.1.002 (2008-02-12)
  15715. */
  15716. protected function _putbookmarks() {
  15717. $nb = count($this->outlines);
  15718. if ($nb == 0) {
  15719. return;
  15720. }
  15721. // sort bookmarks
  15722. $this->sortBookmarks();
  15723. $lru = array();
  15724. $level = 0;
  15725. foreach ($this->outlines as $i => $o) {
  15726. if ($o['l'] > 0) {
  15727. $parent = $lru[($o['l'] - 1)];
  15728. //Set parent and last pointers
  15729. $this->outlines[$i]['parent'] = $parent;
  15730. $this->outlines[$parent]['last'] = $i;
  15731. if ($o['l'] > $level) {
  15732. //Level increasing: set first pointer
  15733. $this->outlines[$parent]['first'] = $i;
  15734. }
  15735. } else {
  15736. $this->outlines[$i]['parent'] = $nb;
  15737. }
  15738. if (($o['l'] <= $level) AND ($i > 0)) {
  15739. //Set prev and next pointers
  15740. $prev = $lru[$o['l']];
  15741. $this->outlines[$prev]['next'] = $i;
  15742. $this->outlines[$i]['prev'] = $prev;
  15743. }
  15744. $lru[$o['l']] = $i;
  15745. $level = $o['l'];
  15746. }
  15747. //Outline items
  15748. $n = $this->n + 1;
  15749. $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';
  15750. foreach ($this->outlines as $i => $o) {
  15751. $oid = $this->_newobj();
  15752. // covert HTML title to string
  15753. $title = preg_replace($nltags, "\n", $o['t']);
  15754. $title = preg_replace("/[\r]+/si", '', $title);
  15755. $title = preg_replace("/[\n]+/si", "\n", $title);
  15756. $title = strip_tags($title);
  15757. $title = $this->stringTrim($title);
  15758. $out = '<</Title '.$this->_textstring($title, $oid);
  15759. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  15760. if (isset($o['prev'])) {
  15761. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  15762. }
  15763. if (isset($o['next'])) {
  15764. $out .= ' /Next '.($n + $o['next']).' 0 R';
  15765. }
  15766. if (isset($o['first'])) {
  15767. $out .= ' /First '.($n + $o['first']).' 0 R';
  15768. }
  15769. if (isset($o['last'])) {
  15770. $out .= ' /Last '.($n + $o['last']).' 0 R';
  15771. }
  15772. if (isset($this->page_obj_id[($o['p'])])) {
  15773. $out .= ' '.sprintf('/Dest [%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($o['p'])], ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  15774. }
  15775. // set font style
  15776. $style = 0;
  15777. if (!empty($o['s'])) {
  15778. // bold
  15779. if (strpos($o['s'], 'B') !== false) {
  15780. $style |= 2;
  15781. }
  15782. // oblique
  15783. if (strpos($o['s'], 'I') !== false) {
  15784. $style |= 1;
  15785. }
  15786. }
  15787. $out .= sprintf(' /F %d', $style);
  15788. // set bookmark color
  15789. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  15790. $color = array_values($o['c']);
  15791. $out .= sprintf(' /C [%.3F %.3F %.3F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  15792. } else {
  15793. // black
  15794. $out .= ' /C [0.0 0.0 0.0]';
  15795. }
  15796. $out .= ' /Count 0'; // normally closed item
  15797. $out .= ' >>';
  15798. $out .= "\n".'endobj';
  15799. $this->_out($out);
  15800. }
  15801. //Outline root
  15802. $this->OutlineRoot = $this->_newobj();
  15803. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  15804. }
  15805. // --- JAVASCRIPT ------------------------------------------------------
  15806. /**
  15807. * Adds a javascript
  15808. * @param $script (string) Javascript code
  15809. * @public
  15810. * @author Johannes Güntert, Nicola Asuni
  15811. * @since 2.1.002 (2008-02-12)
  15812. */
  15813. public function IncludeJS($script) {
  15814. $this->javascript .= $script;
  15815. }
  15816. /**
  15817. * Adds a javascript object and return object ID
  15818. * @param $script (string) Javascript code
  15819. * @param $onload (boolean) if true executes this object when opening the document
  15820. * @return int internal object ID
  15821. * @public
  15822. * @author Nicola Asuni
  15823. * @since 4.8.000 (2009-09-07)
  15824. */
  15825. public function addJavascriptObject($script, $onload=false) {
  15826. if ($this->pdfa_mode) {
  15827. // javascript is not allowed in PDF/A mode
  15828. return false;
  15829. }
  15830. ++$this->n;
  15831. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  15832. return $this->n;
  15833. }
  15834. /**
  15835. * Create a javascript PDF string.
  15836. * @protected
  15837. * @author Johannes Güntert, Nicola Asuni
  15838. * @since 2.1.002 (2008-02-12)
  15839. */
  15840. protected function _putjavascript() {
  15841. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  15842. return;
  15843. }
  15844. if (strpos($this->javascript, 'this.addField') > 0) {
  15845. if (!$this->ur['enabled']) {
  15846. //$this->setUserRights();
  15847. }
  15848. // the following two lines are used to avoid form fields duplication after saving
  15849. // The addField method only works when releasing user rights (UR3)
  15850. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  15851. $jsb = "getField('tcpdfdocsaved').value='saved';";
  15852. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  15853. }
  15854. $this->n_js = $this->_newobj();
  15855. $out = ' << /Names [';
  15856. if (!empty($this->javascript)) {
  15857. $out .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  15858. }
  15859. if (!empty($this->js_objects)) {
  15860. foreach ($this->js_objects as $key => $val) {
  15861. if ($val['onload']) {
  15862. $out .= ' (JS'.$key.') '.$key.' 0 R';
  15863. }
  15864. }
  15865. }
  15866. $out .= ' ] >>';
  15867. $out .= "\n".'endobj';
  15868. $this->_out($out);
  15869. // default Javascript object
  15870. if (!empty($this->javascript)) {
  15871. $obj_id = $this->_newobj();
  15872. $out = '<< /S /JavaScript';
  15873. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  15874. $out .= ' >>';
  15875. $out .= "\n".'endobj';
  15876. $this->_out($out);
  15877. }
  15878. // additional Javascript objects
  15879. if (!empty($this->js_objects)) {
  15880. foreach ($this->js_objects as $key => $val) {
  15881. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  15882. $this->_out($out);
  15883. }
  15884. }
  15885. }
  15886. /**
  15887. * Convert color to javascript color.
  15888. * @param $color (string) color name or "#RRGGBB"
  15889. * @protected
  15890. * @author Denis Van Nuffelen, Nicola Asuni
  15891. * @since 2.1.002 (2008-02-12)
  15892. */
  15893. protected function _JScolor($color) {
  15894. static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
  15895. if (substr($color,0,1) == '#') {
  15896. return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
  15897. }
  15898. if (!in_array($color,$aColors)) {
  15899. $this->Error('Invalid color: '.$color);
  15900. }
  15901. return 'color.'.$color;
  15902. }
  15903. /**
  15904. * Adds a javascript form field.
  15905. * @param $type (string) field type
  15906. * @param $name (string) field name
  15907. * @param $x (int) horizontal position
  15908. * @param $y (int) vertical position
  15909. * @param $w (int) width
  15910. * @param $h (int) height
  15911. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  15912. * @protected
  15913. * @author Denis Van Nuffelen, Nicola Asuni
  15914. * @since 2.1.002 (2008-02-12)
  15915. */
  15916. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  15917. if ($this->rtl) {
  15918. $x = $x - $w;
  15919. }
  15920. // the followind avoid fields duplication after saving the document
  15921. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  15922. $k = $this->k;
  15923. $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%.2F,%.2F,%.2F,%.2F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
  15924. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  15925. while (list($key, $val) = each($prop)) {
  15926. if (strcmp(substr($key, -5), 'Color') == 0) {
  15927. $val = $this->_JScolor($val);
  15928. } else {
  15929. $val = "'".$val."'";
  15930. }
  15931. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  15932. }
  15933. if ($this->rtl) {
  15934. $this->x -= $w;
  15935. } else {
  15936. $this->x += $w;
  15937. }
  15938. $this->javascript .= '}';
  15939. }
  15940. // --- FORM FIELDS -----------------------------------------------------
  15941. /**
  15942. * Convert JavaScript form fields properties array to Annotation Properties array.
  15943. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  15944. * @return array of annotation properties
  15945. * @protected
  15946. * @author Nicola Asuni
  15947. * @since 4.8.000 (2009-09-06)
  15948. */
  15949. protected function getAnnotOptFromJSProp($prop) {
  15950. if (isset($prop['aopt']) AND is_array($prop['aopt'])) {
  15951. // the annotation options area lready defined
  15952. return $prop['aopt'];
  15953. }
  15954. $opt = array(); // value to be returned
  15955. // alignment: Controls how the text is laid out within the text field.
  15956. if (isset($prop['alignment'])) {
  15957. switch ($prop['alignment']) {
  15958. case 'left': {
  15959. $opt['q'] = 0;
  15960. break;
  15961. }
  15962. case 'center': {
  15963. $opt['q'] = 1;
  15964. break;
  15965. }
  15966. case 'right': {
  15967. $opt['q'] = 2;
  15968. break;
  15969. }
  15970. default: {
  15971. $opt['q'] = ($this->rtl)?2:0;
  15972. break;
  15973. }
  15974. }
  15975. }
  15976. // lineWidth: Specifies the thickness of the border when stroking the perimeter of a field's rectangle.
  15977. if (isset($prop['lineWidth'])) {
  15978. $linewidth = intval($prop['lineWidth']);
  15979. } else {
  15980. $linewidth = 1;
  15981. }
  15982. // borderStyle: The border style for a field.
  15983. if (isset($prop['borderStyle'])) {
  15984. switch ($prop['borderStyle']) {
  15985. case 'border.d':
  15986. case 'dashed': {
  15987. $opt['border'] = array(0, 0, $linewidth, array(3, 2));
  15988. $opt['bs'] = array('w'=>$linewidth, 's'=>'D', 'd'=>array(3, 2));
  15989. break;
  15990. }
  15991. case 'border.b':
  15992. case 'beveled': {
  15993. $opt['border'] = array(0, 0, $linewidth);
  15994. $opt['bs'] = array('w'=>$linewidth, 's'=>'B');
  15995. break;
  15996. }
  15997. case 'border.i':
  15998. case 'inset': {
  15999. $opt['border'] = array(0, 0, $linewidth);
  16000. $opt['bs'] = array('w'=>$linewidth, 's'=>'I');
  16001. break;
  16002. }
  16003. case 'border.u':
  16004. case 'underline': {
  16005. $opt['border'] = array(0, 0, $linewidth);
  16006. $opt['bs'] = array('w'=>$linewidth, 's'=>'U');
  16007. break;
  16008. }
  16009. case 'border.s':
  16010. case 'solid': {
  16011. $opt['border'] = array(0, 0, $linewidth);
  16012. $opt['bs'] = array('w'=>$linewidth, 's'=>'S');
  16013. break;
  16014. }
  16015. default: {
  16016. break;
  16017. }
  16018. }
  16019. }
  16020. if (isset($prop['border']) AND is_array($prop['border'])) {
  16021. $opt['border'] = $prop['border'];
  16022. }
  16023. if (!isset($opt['mk'])) {
  16024. $opt['mk'] = array();
  16025. }
  16026. if (!isset($opt['mk']['if'])) {
  16027. $opt['mk']['if'] = array();
  16028. }
  16029. $opt['mk']['if']['a'] = array(0.5, 0.5);
  16030. // buttonAlignX: Controls how space is distributed from the left of the button face with respect to the icon.
  16031. if (isset($prop['buttonAlignX'])) {
  16032. $opt['mk']['if']['a'][0] = $prop['buttonAlignX'];
  16033. }
  16034. // buttonAlignY: Controls how unused space is distributed from the bottom of the button face with respect to the icon.
  16035. if (isset($prop['buttonAlignY'])) {
  16036. $opt['mk']['if']['a'][1] = $prop['buttonAlignY'];
  16037. }
  16038. // buttonFitBounds: If true, the extent to which the icon may be scaled is set to the bounds of the button field.
  16039. if (isset($prop['buttonFitBounds']) AND ($prop['buttonFitBounds'] == 'true')) {
  16040. $opt['mk']['if']['fb'] = true;
  16041. }
  16042. // buttonScaleHow: Controls how the icon is scaled (if necessary) to fit inside the button face.
  16043. if (isset($prop['buttonScaleHow'])) {
  16044. switch ($prop['buttonScaleHow']) {
  16045. case 'scaleHow.proportional': {
  16046. $opt['mk']['if']['s'] = 'P';
  16047. break;
  16048. }
  16049. case 'scaleHow.anamorphic': {
  16050. $opt['mk']['if']['s'] = 'A';
  16051. break;
  16052. }
  16053. }
  16054. }
  16055. // buttonScaleWhen: Controls when an icon is scaled to fit inside the button face.
  16056. if (isset($prop['buttonScaleWhen'])) {
  16057. switch ($prop['buttonScaleWhen']) {
  16058. case 'scaleWhen.always': {
  16059. $opt['mk']['if']['sw'] = 'A';
  16060. break;
  16061. }
  16062. case 'scaleWhen.never': {
  16063. $opt['mk']['if']['sw'] = 'N';
  16064. break;
  16065. }
  16066. case 'scaleWhen.tooBig': {
  16067. $opt['mk']['if']['sw'] = 'B';
  16068. break;
  16069. }
  16070. case 'scaleWhen.tooSmall': {
  16071. $opt['mk']['if']['sw'] = 'S';
  16072. break;
  16073. }
  16074. }
  16075. }
  16076. // buttonPosition: Controls how the text and the icon of the button are positioned with respect to each other within the button face.
  16077. if (isset($prop['buttonPosition'])) {
  16078. switch ($prop['buttonPosition']) {
  16079. case 0:
  16080. case 'position.textOnly': {
  16081. $opt['mk']['tp'] = 0;
  16082. break;
  16083. }
  16084. case 1:
  16085. case 'position.iconOnly': {
  16086. $opt['mk']['tp'] = 1;
  16087. break;
  16088. }
  16089. case 2:
  16090. case 'position.iconTextV': {
  16091. $opt['mk']['tp'] = 2;
  16092. break;
  16093. }
  16094. case 3:
  16095. case 'position.textIconV': {
  16096. $opt['mk']['tp'] = 3;
  16097. break;
  16098. }
  16099. case 4:
  16100. case 'position.iconTextH': {
  16101. $opt['mk']['tp'] = 4;
  16102. break;
  16103. }
  16104. case 5:
  16105. case 'position.textIconH': {
  16106. $opt['mk']['tp'] = 5;
  16107. break;
  16108. }
  16109. case 6:
  16110. case 'position.overlay': {
  16111. $opt['mk']['tp'] = 6;
  16112. break;
  16113. }
  16114. }
  16115. }
  16116. // fillColor: Specifies the background color for a field.
  16117. if (isset($prop['fillColor'])) {
  16118. if (is_array($prop['fillColor'])) {
  16119. $opt['mk']['bg'] = $prop['fillColor'];
  16120. } else {
  16121. $opt['mk']['bg'] = $this->convertHTMLColorToDec($prop['fillColor']);
  16122. }
  16123. }
  16124. // strokeColor: Specifies the stroke color for a field that is used to stroke the rectangle of the field with a line as large as the line width.
  16125. if (isset($prop['strokeColor'])) {
  16126. if (is_array($prop['strokeColor'])) {
  16127. $opt['mk']['bc'] = $prop['strokeColor'];
  16128. } else {
  16129. $opt['mk']['bc'] = $this->convertHTMLColorToDec($prop['strokeColor']);
  16130. }
  16131. }
  16132. // rotation: The rotation of a widget in counterclockwise increments.
  16133. if (isset($prop['rotation'])) {
  16134. $opt['mk']['r'] = $prop['rotation'];
  16135. }
  16136. // charLimit: Limits the number of characters that a user can type into a text field.
  16137. if (isset($prop['charLimit'])) {
  16138. $opt['maxlen'] = intval($prop['charLimit']);
  16139. }
  16140. if (!isset($ff)) {
  16141. $ff = 0; // default value
  16142. }
  16143. // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
  16144. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
  16145. $ff += 1 << 0;
  16146. }
  16147. // required: Specifies whether a field requires a value.
  16148. if (isset($prop['required']) AND ($prop['required'] == 'true')) {
  16149. $ff += 1 << 1;
  16150. }
  16151. // multiline: Controls how text is wrapped within the field.
  16152. if (isset($prop['multiline']) AND ($prop['multiline'] == 'true')) {
  16153. $ff += 1 << 12;
  16154. }
  16155. // password: Specifies whether the field should display asterisks when data is entered in the field.
  16156. if (isset($prop['password']) AND ($prop['password'] == 'true')) {
  16157. $ff += 1 << 13;
  16158. }
  16159. // NoToggleToOff: If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect.
  16160. if (isset($prop['NoToggleToOff']) AND ($prop['NoToggleToOff'] == 'true')) {
  16161. $ff += 1 << 14;
  16162. }
  16163. // Radio: If set, the field is a set of radio buttons.
  16164. if (isset($prop['Radio']) AND ($prop['Radio'] == 'true')) {
  16165. $ff += 1 << 15;
  16166. }
  16167. // Pushbutton: If set, the field is a pushbutton that does not retain a permanent value.
  16168. if (isset($prop['Pushbutton']) AND ($prop['Pushbutton'] == 'true')) {
  16169. $ff += 1 << 16;
  16170. }
  16171. // Combo: If set, the field is a combo box; if clear, the field is a list box.
  16172. if (isset($prop['Combo']) AND ($prop['Combo'] == 'true')) {
  16173. $ff += 1 << 17;
  16174. }
  16175. // editable: Controls whether a combo box is editable.
  16176. if (isset($prop['editable']) AND ($prop['editable'] == 'true')) {
  16177. $ff += 1 << 18;
  16178. }
  16179. // Sort: If set, the field's option items shall be sorted alphabetically.
  16180. if (isset($prop['Sort']) AND ($prop['Sort'] == 'true')) {
  16181. $ff += 1 << 19;
  16182. }
  16183. // fileSelect: If true, sets the file-select flag in the Options tab of the text field (Field is Used for File Selection).
  16184. if (isset($prop['fileSelect']) AND ($prop['fileSelect'] == 'true')) {
  16185. $ff += 1 << 20;
  16186. }
  16187. // multipleSelection: If true, indicates that a list box allows a multiple selection of items.
  16188. if (isset($prop['multipleSelection']) AND ($prop['multipleSelection'] == 'true')) {
  16189. $ff += 1 << 21;
  16190. }
  16191. // doNotSpellCheck: If true, spell checking is not performed on this editable text field.
  16192. if (isset($prop['doNotSpellCheck']) AND ($prop['doNotSpellCheck'] == 'true')) {
  16193. $ff += 1 << 22;
  16194. }
  16195. // doNotScroll: If true, the text field does not scroll and the user, therefore, is limited by the rectangular region designed for the field.
  16196. if (isset($prop['doNotScroll']) AND ($prop['doNotScroll'] == 'true')) {
  16197. $ff += 1 << 23;
  16198. }
  16199. // comb: If set to true, the field background is drawn as series of boxes (one for each character in the value of the field) and each character of the content is drawn within those boxes. The number of boxes drawn is determined from the charLimit property. It applies only to text fields. The setter will also raise if any of the following field properties are also set multiline, password, and fileSelect. A side-effect of setting this property is that the doNotScroll property is also set.
  16200. if (isset($prop['comb']) AND ($prop['comb'] == 'true')) {
  16201. $ff += 1 << 24;
  16202. }
  16203. // radiosInUnison: If false, even if a group of radio buttons have the same name and export value, they behave in a mutually exclusive fashion, like HTML radio buttons.
  16204. if (isset($prop['radiosInUnison']) AND ($prop['radiosInUnison'] == 'true')) {
  16205. $ff += 1 << 25;
  16206. }
  16207. // richText: If true, the field allows rich text formatting.
  16208. if (isset($prop['richText']) AND ($prop['richText'] == 'true')) {
  16209. $ff += 1 << 25;
  16210. }
  16211. // commitOnSelChange: Controls whether a field value is committed after a selection change.
  16212. if (isset($prop['commitOnSelChange']) AND ($prop['commitOnSelChange'] == 'true')) {
  16213. $ff += 1 << 26;
  16214. }
  16215. $opt['ff'] = $ff;
  16216. // defaultValue: The default value of a field - that is, the value that the field is set to when the form is reset.
  16217. if (isset($prop['defaultValue'])) {
  16218. $opt['dv'] = $prop['defaultValue'];
  16219. }
  16220. $f = 4; // default value for annotation flags
  16221. // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
  16222. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
  16223. $f += 1 << 6;
  16224. }
  16225. // display: Controls whether the field is hidden or visible on screen and in print.
  16226. if (isset($prop['display'])) {
  16227. if ($prop['display'] == 'display.visible') {
  16228. //
  16229. } elseif ($prop['display'] == 'display.hidden') {
  16230. $f += 1 << 1;
  16231. } elseif ($prop['display'] == 'display.noPrint') {
  16232. $f -= 1 << 2;
  16233. } elseif ($prop['display'] == 'display.noView') {
  16234. $f += 1 << 5;
  16235. }
  16236. }
  16237. $opt['f'] = $f;
  16238. // currentValueIndices: Reads and writes single or multiple values of a list box or combo box.
  16239. if (isset($prop['currentValueIndices']) AND is_array($prop['currentValueIndices'])) {
  16240. $opt['i'] = $prop['currentValueIndices'];
  16241. }
  16242. // value: The value of the field data that the user has entered.
  16243. if (isset($prop['value'])) {
  16244. if (is_array($prop['value'])) {
  16245. $opt['opt'] = array();
  16246. foreach ($prop['value'] AS $key => $optval) {
  16247. // exportValues: An array of strings representing the export values for the field.
  16248. if (isset($prop['exportValues'][$key])) {
  16249. $opt['opt'][$key] = array($prop['exportValues'][$key], $prop['value'][$key]);
  16250. } else {
  16251. $opt['opt'][$key] = $prop['value'][$key];
  16252. }
  16253. }
  16254. } else {
  16255. $opt['v'] = $prop['value'];
  16256. }
  16257. }
  16258. // richValue: This property specifies the text contents and formatting of a rich text field.
  16259. if (isset($prop['richValue'])) {
  16260. $opt['rv'] = $prop['richValue'];
  16261. }
  16262. // submitName: If nonempty, used during form submission instead of name. Only applicable if submitting in HTML format (that is, URL-encoded).
  16263. if (isset($prop['submitName'])) {
  16264. $opt['tm'] = $prop['submitName'];
  16265. }
  16266. // name: Fully qualified field name.
  16267. if (isset($prop['name'])) {
  16268. $opt['t'] = $prop['name'];
  16269. }
  16270. // userName: The user name (short description string) of the field.
  16271. if (isset($prop['userName'])) {
  16272. $opt['tu'] = $prop['userName'];
  16273. }
  16274. // highlight: Defines how a button reacts when a user clicks it.
  16275. if (isset($prop['highlight'])) {
  16276. switch ($prop['highlight']) {
  16277. case 'none':
  16278. case 'highlight.n': {
  16279. $opt['h'] = 'N';
  16280. break;
  16281. }
  16282. case 'invert':
  16283. case 'highlight.i': {
  16284. $opt['h'] = 'i';
  16285. break;
  16286. }
  16287. case 'push':
  16288. case 'highlight.p': {
  16289. $opt['h'] = 'P';
  16290. break;
  16291. }
  16292. case 'outline':
  16293. case 'highlight.o': {
  16294. $opt['h'] = 'O';
  16295. break;
  16296. }
  16297. }
  16298. }
  16299. // Unsupported options:
  16300. // - calcOrderIndex: Changes the calculation order of fields in the document.
  16301. // - delay: Delays the redrawing of a field's appearance.
  16302. // - defaultStyle: This property defines the default style attributes for the form field.
  16303. // - style: Allows the user to set the glyph style of a check box or radio button.
  16304. // - textColor, textFont, textSize
  16305. return $opt;
  16306. }
  16307. /**
  16308. * Set default properties for form fields.
  16309. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16310. * @public
  16311. * @author Nicola Asuni
  16312. * @since 4.8.000 (2009-09-06)
  16313. */
  16314. public function setFormDefaultProp($prop=array()) {
  16315. $this->default_form_prop = $prop;
  16316. }
  16317. /**
  16318. * Return the default properties for form fields.
  16319. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16320. * @public
  16321. * @author Nicola Asuni
  16322. * @since 4.8.000 (2009-09-06)
  16323. */
  16324. public function getFormDefaultProp() {
  16325. return $this->default_form_prop;
  16326. }
  16327. /**
  16328. * Creates a text field
  16329. * @param $name (string) field name
  16330. * @param $w (float) Width of the rectangle
  16331. * @param $h (float) Height of the rectangle
  16332. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16333. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16334. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16335. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16336. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16337. * @public
  16338. * @author Nicola Asuni
  16339. * @since 4.8.000 (2009-09-07)
  16340. */
  16341. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  16342. if ($x === '') {
  16343. $x = $this->x;
  16344. }
  16345. if ($y === '') {
  16346. $y = $this->y;
  16347. }
  16348. // check page for no-write regions and adapt page margins if necessary
  16349. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  16350. if ($js) {
  16351. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  16352. return;
  16353. }
  16354. // get default style
  16355. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16356. // get annotation data
  16357. $popt = $this->getAnnotOptFromJSProp($prop);
  16358. // set default appearance stream
  16359. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  16360. $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  16361. $popt['da'] = $fontstyle;
  16362. // build appearance stream
  16363. $popt['ap'] = array();
  16364. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  16365. $text = '';
  16366. if (isset($prop['value']) AND !empty($prop['value'])) {
  16367. $text = $prop['value'];
  16368. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  16369. $text = $opt['v'];
  16370. }
  16371. $tmpid = $this->startTemplate($w, $h, false);
  16372. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  16373. $this->endTemplate();
  16374. --$this->n;
  16375. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  16376. unset($this->xobjects[$tmpid]);
  16377. $popt['ap']['n'] .= 'Q EMC';
  16378. // merge options
  16379. $opt = array_merge($popt, $opt);
  16380. // remove some conflicting options
  16381. unset($opt['bs']);
  16382. // set remaining annotation data
  16383. $opt['Subtype'] = 'Widget';
  16384. $opt['ft'] = 'Tx';
  16385. $opt['t'] = $name;
  16386. // Additional annotation's parameters (check _putannotsobj() method):
  16387. //$opt['f']
  16388. //$opt['as']
  16389. //$opt['bs']
  16390. //$opt['be']
  16391. //$opt['c']
  16392. //$opt['border']
  16393. //$opt['h']
  16394. //$opt['mk'];
  16395. //$opt['mk']['r']
  16396. //$opt['mk']['bc'];
  16397. //$opt['mk']['bg'];
  16398. unset($opt['mk']['ca']);
  16399. unset($opt['mk']['rc']);
  16400. unset($opt['mk']['ac']);
  16401. unset($opt['mk']['i']);
  16402. unset($opt['mk']['ri']);
  16403. unset($opt['mk']['ix']);
  16404. unset($opt['mk']['if']);
  16405. //$opt['mk']['if']['sw'];
  16406. //$opt['mk']['if']['s'];
  16407. //$opt['mk']['if']['a'];
  16408. //$opt['mk']['if']['fb'];
  16409. unset($opt['mk']['tp']);
  16410. //$opt['tu']
  16411. //$opt['tm']
  16412. //$opt['ff']
  16413. //$opt['v']
  16414. //$opt['dv']
  16415. //$opt['a']
  16416. //$opt['aa']
  16417. //$opt['q']
  16418. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  16419. if ($this->rtl) {
  16420. $this->x -= $w;
  16421. } else {
  16422. $this->x += $w;
  16423. }
  16424. }
  16425. /**
  16426. * Creates a RadioButton field.
  16427. * @param $name (string) Field name.
  16428. * @param $w (int) Width or the radio button.
  16429. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16430. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16431. * @param $onvalue (string) Value to be returned if selected.
  16432. * @param $checked (boolean) Define the initial state.
  16433. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16434. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16435. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16436. * @public
  16437. * @author Nicola Asuni
  16438. * @since 4.8.000 (2009-09-07)
  16439. */
  16440. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  16441. if ($x === '') {
  16442. $x = $this->x;
  16443. }
  16444. if ($y === '') {
  16445. $y = $this->y;
  16446. }
  16447. // check page for no-write regions and adapt page margins if necessary
  16448. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  16449. if ($js) {
  16450. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  16451. return;
  16452. }
  16453. if ($this->empty_string($onvalue)) {
  16454. $onvalue = 'On';
  16455. }
  16456. if ($checked) {
  16457. $defval = $onvalue;
  16458. } else {
  16459. $defval = 'Off';
  16460. }
  16461. // set font
  16462. $font = 'zapfdingbats';
  16463. $this->AddFont($font);
  16464. $tmpfont = $this->getFontBuffer($font);
  16465. // set data for parent group
  16466. if (!isset($this->radiobutton_groups[$this->page])) {
  16467. $this->radiobutton_groups[$this->page] = array();
  16468. }
  16469. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  16470. $this->radiobutton_groups[$this->page][$name] = array();
  16471. ++$this->n;
  16472. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  16473. $this->radio_groups[] = $this->n;
  16474. }
  16475. $kid = ($this->n + 1);
  16476. // save object ID to be added on Kids entry on parent object
  16477. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  16478. // get default style
  16479. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16480. $prop['NoToggleToOff'] = 'true';
  16481. $prop['Radio'] = 'true';
  16482. $prop['borderStyle'] = 'inset';
  16483. // get annotation data
  16484. $popt = $this->getAnnotOptFromJSProp($prop);
  16485. // set additional default options
  16486. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  16487. $fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  16488. $popt['da'] = $fontstyle;
  16489. // build appearance stream
  16490. $popt['ap'] = array();
  16491. $popt['ap']['n'] = array();
  16492. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  16493. $popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %.2F Tf %.2F %.2F Td ('.chr(108).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  16494. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %.2F Tf %.2F %.2F Td ('.chr(109).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  16495. if (!isset($popt['mk'])) {
  16496. $popt['mk'] = array();
  16497. }
  16498. $popt['mk']['ca'] = '(l)';
  16499. // merge options
  16500. $opt = array_merge($popt, $opt);
  16501. // set remaining annotation data
  16502. $opt['Subtype'] = 'Widget';
  16503. $opt['ft'] = 'Btn';
  16504. if ($checked) {
  16505. $opt['v'] = array('/'.$onvalue);
  16506. $opt['as'] = $onvalue;
  16507. } else {
  16508. $opt['as'] = 'Off';
  16509. }
  16510. // store readonly flag
  16511. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  16512. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  16513. }
  16514. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  16515. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  16516. if ($this->rtl) {
  16517. $this->x -= $w;
  16518. } else {
  16519. $this->x += $w;
  16520. }
  16521. }
  16522. /**
  16523. * Creates a List-box field
  16524. * @param $name (string) field name
  16525. * @param $w (int) width
  16526. * @param $h (int) height
  16527. * @param $values (array) array containing the list of values.
  16528. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16529. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16530. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16531. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16532. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16533. * @public
  16534. * @author Nicola Asuni
  16535. * @since 4.8.000 (2009-09-07)
  16536. */
  16537. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  16538. if ($x === '') {
  16539. $x = $this->x;
  16540. }
  16541. if ($y === '') {
  16542. $y = $this->y;
  16543. }
  16544. // check page for no-write regions and adapt page margins if necessary
  16545. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  16546. if ($js) {
  16547. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  16548. $s = '';
  16549. foreach ($values as $value) {
  16550. $s .= '\''.addslashes($value).'\',';
  16551. }
  16552. $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
  16553. return;
  16554. }
  16555. // get default style
  16556. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16557. // get annotation data
  16558. $popt = $this->getAnnotOptFromJSProp($prop);
  16559. // set additional default values
  16560. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  16561. $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  16562. $popt['da'] = $fontstyle;
  16563. // build appearance stream
  16564. $popt['ap'] = array();
  16565. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  16566. $text = '';
  16567. foreach($values as $item) {
  16568. $text .= $item."\n";
  16569. }
  16570. $tmpid = $this->startTemplate($w, $h, false);
  16571. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  16572. $this->endTemplate();
  16573. --$this->n;
  16574. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  16575. unset($this->xobjects[$tmpid]);
  16576. $popt['ap']['n'] .= 'Q EMC';
  16577. // merge options
  16578. $opt = array_merge($popt, $opt);
  16579. // set remaining annotation data
  16580. $opt['Subtype'] = 'Widget';
  16581. $opt['ft'] = 'Ch';
  16582. $opt['t'] = $name;
  16583. $opt['opt'] = $values;
  16584. unset($opt['mk']['ca']);
  16585. unset($opt['mk']['rc']);
  16586. unset($opt['mk']['ac']);
  16587. unset($opt['mk']['i']);
  16588. unset($opt['mk']['ri']);
  16589. unset($opt['mk']['ix']);
  16590. unset($opt['mk']['if']);
  16591. unset($opt['mk']['tp']);
  16592. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  16593. if ($this->rtl) {
  16594. $this->x -= $w;
  16595. } else {
  16596. $this->x += $w;
  16597. }
  16598. }
  16599. /**
  16600. * Creates a Combo-box field
  16601. * @param $name (string) field name
  16602. * @param $w (int) width
  16603. * @param $h (int) height
  16604. * @param $values (array) array containing the list of values.
  16605. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16606. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16607. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16608. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16609. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16610. * @public
  16611. * @author Nicola Asuni
  16612. * @since 4.8.000 (2009-09-07)
  16613. */
  16614. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  16615. if ($x === '') {
  16616. $x = $this->x;
  16617. }
  16618. if ($y === '') {
  16619. $y = $this->y;
  16620. }
  16621. // check page for no-write regions and adapt page margins if necessary
  16622. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  16623. if ($js) {
  16624. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  16625. $s = '';
  16626. foreach ($values as $value) {
  16627. $s .= "'".addslashes($value)."',";
  16628. }
  16629. $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
  16630. return;
  16631. }
  16632. // get default style
  16633. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16634. $prop['Combo'] = true;
  16635. // get annotation data
  16636. $popt = $this->getAnnotOptFromJSProp($prop);
  16637. // set additional default options
  16638. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  16639. $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  16640. $popt['da'] = $fontstyle;
  16641. // build appearance stream
  16642. $popt['ap'] = array();
  16643. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  16644. $text = '';
  16645. foreach($values as $item) {
  16646. $text .= $item[1]."\n";
  16647. }
  16648. $tmpid = $this->startTemplate($w, $h, false);
  16649. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  16650. $this->endTemplate();
  16651. --$this->n;
  16652. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  16653. unset($this->xobjects[$tmpid]);
  16654. $popt['ap']['n'] .= 'Q EMC';
  16655. // merge options
  16656. $opt = array_merge($popt, $opt);
  16657. // set remaining annotation data
  16658. $opt['Subtype'] = 'Widget';
  16659. $opt['ft'] = 'Ch';
  16660. $opt['t'] = $name;
  16661. $opt['opt'] = $values;
  16662. unset($opt['mk']['ca']);
  16663. unset($opt['mk']['rc']);
  16664. unset($opt['mk']['ac']);
  16665. unset($opt['mk']['i']);
  16666. unset($opt['mk']['ri']);
  16667. unset($opt['mk']['ix']);
  16668. unset($opt['mk']['if']);
  16669. unset($opt['mk']['tp']);
  16670. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  16671. if ($this->rtl) {
  16672. $this->x -= $w;
  16673. } else {
  16674. $this->x += $w;
  16675. }
  16676. }
  16677. /**
  16678. * Creates a CheckBox field
  16679. * @param $name (string) field name
  16680. * @param $w (int) width
  16681. * @param $checked (boolean) define the initial state.
  16682. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16683. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16684. * @param $onvalue (string) value to be returned if selected.
  16685. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16686. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16687. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16688. * @public
  16689. * @author Nicola Asuni
  16690. * @since 4.8.000 (2009-09-07)
  16691. */
  16692. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  16693. if ($x === '') {
  16694. $x = $this->x;
  16695. }
  16696. if ($y === '') {
  16697. $y = $this->y;
  16698. }
  16699. // check page for no-write regions and adapt page margins if necessary
  16700. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  16701. if ($js) {
  16702. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  16703. return;
  16704. }
  16705. if (!isset($prop['value'])) {
  16706. $prop['value'] = array('Yes');
  16707. }
  16708. // get default style
  16709. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16710. $prop['borderStyle'] = 'inset';
  16711. // get annotation data
  16712. $popt = $this->getAnnotOptFromJSProp($prop);
  16713. // set additional default options
  16714. $font = 'zapfdingbats';
  16715. $this->AddFont($font);
  16716. $tmpfont = $this->getFontBuffer($font);
  16717. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  16718. $fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  16719. $popt['da'] = $fontstyle;
  16720. // build appearance stream
  16721. $popt['ap'] = array();
  16722. $popt['ap']['n'] = array();
  16723. $fy = ((($tmpfont['desc']['Ascent'] + $tmpfont['desc']['Descent']) * $this->FontSizePt) / (1000 * $this->k));
  16724. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  16725. $popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %.2F Tf %.2F %.2F Td ('.chr(110).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  16726. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %.2F Tf %.2F %.2F Td ('.chr(111).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  16727. // merge options
  16728. $opt = array_merge($popt, $opt);
  16729. // set remaining annotation data
  16730. $opt['Subtype'] = 'Widget';
  16731. $opt['ft'] = 'Btn';
  16732. $opt['t'] = $name;
  16733. if ($this->empty_string($onvalue)) {
  16734. $onvalue = 'Yes';
  16735. }
  16736. $opt['opt'] = array($onvalue);
  16737. if ($checked) {
  16738. $opt['v'] = array('/Yes');
  16739. $opt['as'] = 'Yes';
  16740. } else {
  16741. $opt['v'] = array('/Off');
  16742. $opt['as'] = 'Off';
  16743. }
  16744. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  16745. if ($this->rtl) {
  16746. $this->x -= $w;
  16747. } else {
  16748. $this->x += $w;
  16749. }
  16750. }
  16751. /**
  16752. * Creates a button field
  16753. * @param $name (string) field name
  16754. * @param $w (int) width
  16755. * @param $h (int) height
  16756. * @param $caption (string) caption.
  16757. * @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.
  16758. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16759. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16760. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16761. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16762. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16763. * @public
  16764. * @author Nicola Asuni
  16765. * @since 4.8.000 (2009-09-07)
  16766. */
  16767. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  16768. if ($x === '') {
  16769. $x = $this->x;
  16770. }
  16771. if ($y === '') {
  16772. $y = $this->y;
  16773. }
  16774. // check page for no-write regions and adapt page margins if necessary
  16775. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  16776. if ($js) {
  16777. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  16778. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  16779. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  16780. $this->javascript .= 'f'.$name.".highlight='push';\n";
  16781. $this->javascript .= 'f'.$name.".print=false;\n";
  16782. return;
  16783. }
  16784. // get default style
  16785. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16786. $prop['Pushbutton'] = 'true';
  16787. $prop['highlight'] = 'push';
  16788. $prop['display'] = 'display.noPrint';
  16789. // get annotation data
  16790. $popt = $this->getAnnotOptFromJSProp($prop);
  16791. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  16792. $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  16793. $popt['da'] = $fontstyle;
  16794. // build appearance stream
  16795. $popt['ap'] = array();
  16796. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  16797. $tmpid = $this->startTemplate($w, $h, false);
  16798. $bw = (2 / $this->k); // border width
  16799. $border = array(
  16800. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  16801. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  16802. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  16803. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  16804. $this->SetFillColor(204);
  16805. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  16806. $this->endTemplate();
  16807. --$this->n;
  16808. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  16809. unset($this->xobjects[$tmpid]);
  16810. $popt['ap']['n'] .= 'Q EMC';
  16811. // set additional default options
  16812. if (!isset($popt['mk'])) {
  16813. $popt['mk'] = array();
  16814. }
  16815. $ann_obj_id = ($this->n + 1);
  16816. if (!empty($action) AND !is_array($action)) {
  16817. $ann_obj_id = ($this->n + 2);
  16818. }
  16819. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  16820. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  16821. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  16822. // merge options
  16823. $opt = array_merge($popt, $opt);
  16824. // set remaining annotation data
  16825. $opt['Subtype'] = 'Widget';
  16826. $opt['ft'] = 'Btn';
  16827. $opt['t'] = $caption;
  16828. $opt['v'] = $name;
  16829. if (!empty($action)) {
  16830. if (is_array($action)) {
  16831. // form action options as on section 12.7.5 of PDF32000_2008.
  16832. $opt['aa'] = '/D <<';
  16833. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  16834. foreach ($action AS $key => $val) {
  16835. if (($key == 'S') AND in_array($val, $bmode)) {
  16836. $opt['aa'] .= ' /S /'.$val;
  16837. } elseif (($key == 'F') AND (!empty($val))) {
  16838. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  16839. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  16840. $opt['aa'] .= ' /Fields [';
  16841. foreach ($val AS $field) {
  16842. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  16843. }
  16844. $opt['aa'] .= ']';
  16845. } elseif (($key == 'Flags')) {
  16846. $ff = 0;
  16847. if (is_array($val)) {
  16848. foreach ($val AS $flag) {
  16849. switch ($flag) {
  16850. case 'Include/Exclude': {
  16851. $ff += 1 << 0;
  16852. break;
  16853. }
  16854. case 'IncludeNoValueFields': {
  16855. $ff += 1 << 1;
  16856. break;
  16857. }
  16858. case 'ExportFormat': {
  16859. $ff += 1 << 2;
  16860. break;
  16861. }
  16862. case 'GetMethod': {
  16863. $ff += 1 << 3;
  16864. break;
  16865. }
  16866. case 'SubmitCoordinates': {
  16867. $ff += 1 << 4;
  16868. break;
  16869. }
  16870. case 'XFDF': {
  16871. $ff += 1 << 5;
  16872. break;
  16873. }
  16874. case 'IncludeAppendSaves': {
  16875. $ff += 1 << 6;
  16876. break;
  16877. }
  16878. case 'IncludeAnnotations': {
  16879. $ff += 1 << 7;
  16880. break;
  16881. }
  16882. case 'SubmitPDF': {
  16883. $ff += 1 << 8;
  16884. break;
  16885. }
  16886. case 'CanonicalFormat': {
  16887. $ff += 1 << 9;
  16888. break;
  16889. }
  16890. case 'ExclNonUserAnnots': {
  16891. $ff += 1 << 10;
  16892. break;
  16893. }
  16894. case 'ExclFKey': {
  16895. $ff += 1 << 11;
  16896. break;
  16897. }
  16898. case 'EmbedForm': {
  16899. $ff += 1 << 13;
  16900. break;
  16901. }
  16902. }
  16903. }
  16904. } else {
  16905. $ff = intval($val);
  16906. }
  16907. $opt['aa'] .= ' /Flags '.$ff;
  16908. }
  16909. }
  16910. $opt['aa'] .= ' >>';
  16911. } else {
  16912. // Javascript action or raw action command
  16913. $js_obj_id = $this->addJavascriptObject($action);
  16914. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  16915. }
  16916. }
  16917. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  16918. if ($this->rtl) {
  16919. $this->x -= $w;
  16920. } else {
  16921. $this->x += $w;
  16922. }
  16923. }
  16924. // --- END FORMS FIELDS ------------------------------------------------
  16925. /**
  16926. * Add certification signature (DocMDP or UR3)
  16927. * You can set only one signature type
  16928. * @protected
  16929. * @author Nicola Asuni
  16930. * @since 4.6.008 (2009-05-07)
  16931. */
  16932. protected function _putsignature() {
  16933. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  16934. return;
  16935. }
  16936. $sigobjid = ($this->sig_obj_id + 1);
  16937. $out = $this->_getobj($sigobjid)."\n";
  16938. $out .= '<< /Type /Sig';
  16939. $out .= ' /Filter /Adobe.PPKLite';
  16940. $out .= ' /SubFilter /adbe.pkcs7.detached';
  16941. $out .= ' '.$this->byterange_string;
  16942. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  16943. $out .= ' /Reference ['; // array of signature reference dictionaries
  16944. $out .= ' << /Type /SigRef';
  16945. if ($this->signature_data['cert_type'] > 0) {
  16946. $out .= ' /TransformMethod /DocMDP';
  16947. $out .= ' /TransformParams <<';
  16948. $out .= ' /Type /TransformParams';
  16949. $out .= ' /P '.$this->signature_data['cert_type'];
  16950. $out .= ' /V /1.2';
  16951. } else {
  16952. $out .= ' /TransformMethod /UR3';
  16953. $out .= ' /TransformParams <<';
  16954. $out .= ' /Type /TransformParams';
  16955. $out .= ' /V /2.2';
  16956. if (!$this->empty_string($this->ur['document'])) {
  16957. $out .= ' /Document['.$this->ur['document'].']';
  16958. }
  16959. if (!$this->empty_string($this->ur['form'])) {
  16960. $out .= ' /Form['.$this->ur['form'].']';
  16961. }
  16962. if (!$this->empty_string($this->ur['signature'])) {
  16963. $out .= ' /Signature['.$this->ur['signature'].']';
  16964. }
  16965. if (!$this->empty_string($this->ur['annots'])) {
  16966. $out .= ' /Annots['.$this->ur['annots'].']';
  16967. }
  16968. if (!$this->empty_string($this->ur['ef'])) {
  16969. $out .= ' /EF['.$this->ur['ef'].']';
  16970. }
  16971. if (!$this->empty_string($this->ur['formex'])) {
  16972. $out .= ' /FormEX['.$this->ur['formex'].']';
  16973. }
  16974. }
  16975. $out .= ' >>'; // close TransformParams
  16976. // optional digest data (values must be calculated and replaced later)
  16977. //$out .= ' /Data ********** 0 R';
  16978. //$out .= ' /DigestMethod/MD5';
  16979. //$out .= ' /DigestLocation[********** 34]';
  16980. //$out .= ' /DigestValue<********************************>';
  16981. $out .= ' >>';
  16982. $out .= ' ]'; // end of reference
  16983. if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
  16984. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  16985. }
  16986. if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
  16987. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  16988. }
  16989. if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
  16990. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  16991. }
  16992. if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
  16993. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  16994. }
  16995. $out .= ' /M '.$this->_datestring($sigobjid);
  16996. $out .= ' >>';
  16997. $out .= "\n".'endobj';
  16998. $this->_out($out);
  16999. }
  17000. /**
  17001. * Set User's Rights for PDF Reader
  17002. * WARNING: This is experimental and currently do not work.
  17003. * Check the PDF Reference 8.7.1 Transform Methods,
  17004. * Table 8.105 Entries in the UR transform parameters dictionary
  17005. * @param $enable (boolean) if true enable user's rights on PDF reader
  17006. * @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.
  17007. * @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.
  17008. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  17009. * @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.
  17010. * @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
  17011. Names specifying additional embedded-files-related usage rights for the document.
  17012. * @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.
  17013. * @public
  17014. * @author Nicola Asuni
  17015. * @since 2.9.000 (2008-03-26)
  17016. */
  17017. public function setUserRights(
  17018. $enable=true,
  17019. $document='/FullSave',
  17020. $annots='/Create/Delete/Modify/Copy/Import/Export',
  17021. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  17022. $signature='/Modify',
  17023. $ef='/Create/Delete/Modify/Import',
  17024. $formex='') {
  17025. $this->ur['enabled'] = $enable;
  17026. $this->ur['document'] = $document;
  17027. $this->ur['annots'] = $annots;
  17028. $this->ur['form'] = $form;
  17029. $this->ur['signature'] = $signature;
  17030. $this->ur['ef'] = $ef;
  17031. $this->ur['formex'] = $formex;
  17032. if (!$this->sign) {
  17033. $this->setSignature('', '', '', '', 0, array());
  17034. }
  17035. }
  17036. /**
  17037. * Enable document signature (requires the OpenSSL Library).
  17038. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  17039. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  17040. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  17041. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  17042. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  17043. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  17044. * @param $private_key_password (string) password
  17045. * @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.
  17046. * @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.
  17047. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  17048. * @public
  17049. * @author Nicola Asuni
  17050. * @since 4.6.005 (2009-04-24)
  17051. */
  17052. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
  17053. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  17054. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  17055. // to convert pfx certificate to pem: openssl
  17056. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  17057. $this->sign = true;
  17058. ++$this->n;
  17059. $this->sig_obj_id = $this->n; // signature widget
  17060. ++$this->n; // signature object ($this->sig_obj_id + 1)
  17061. $this->signature_data = array();
  17062. if (strlen($signing_cert) == 0) {
  17063. $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.crt';
  17064. $private_key_password = 'tcpdfdemo';
  17065. }
  17066. if (strlen($private_key) == 0) {
  17067. $private_key = $signing_cert;
  17068. }
  17069. $this->signature_data['signcert'] = $signing_cert;
  17070. $this->signature_data['privkey'] = $private_key;
  17071. $this->signature_data['password'] = $private_key_password;
  17072. $this->signature_data['extracerts'] = $extracerts;
  17073. $this->signature_data['cert_type'] = $cert_type;
  17074. $this->signature_data['info'] = $info;
  17075. }
  17076. /**
  17077. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  17078. * @param $x (float) Abscissa of the upper-left corner.
  17079. * @param $y (float) Ordinate of the upper-left corner.
  17080. * @param $w (float) Width of the signature area.
  17081. * @param $h (float) Height of the signature area.
  17082. * @param $page (int) option page number (if < 0 the current page is used).
  17083. * @public
  17084. * @author Nicola Asuni
  17085. * @since 5.3.011 (2010-06-17)
  17086. */
  17087. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) {
  17088. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page);
  17089. }
  17090. /**
  17091. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  17092. * @param $x (float) Abscissa of the upper-left corner.
  17093. * @param $y (float) Ordinate of the upper-left corner.
  17094. * @param $w (float) Width of the signature area.
  17095. * @param $h (float) Height of the signature area.
  17096. * @param $page (int) option page number (if < 0 the current page is used).
  17097. * @public
  17098. * @author Nicola Asuni
  17099. * @since 5.9.101 (2011-07-06)
  17100. */
  17101. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) {
  17102. ++$this->n;
  17103. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page);
  17104. }
  17105. /**
  17106. * Get the array that defines the signature appearance (page and rectangle coordinates).
  17107. * @param $x (float) Abscissa of the upper-left corner.
  17108. * @param $y (float) Ordinate of the upper-left corner.
  17109. * @param $w (float) Width of the signature area.
  17110. * @param $h (float) Height of the signature area.
  17111. * @param $page (int) option page number (if < 0 the current page is used).
  17112. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  17113. * @protected
  17114. * @author Nicola Asuni
  17115. * @since 5.9.101 (2011-07-06)
  17116. */
  17117. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1) {
  17118. $sigapp = array();
  17119. if (($page < 1) OR ($page > $this->numpages)) {
  17120. $sigapp['page'] = $this->page;
  17121. } else {
  17122. $sigapp['page'] = intval($page);
  17123. }
  17124. $a = $x * $this->k;
  17125. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  17126. $c = $w * $this->k;
  17127. $d = $h * $this->k;
  17128. $sigapp['rect'] = sprintf('%.2F %.2F %.2F %.2F', $a, $b, ($a + $c), ($b + $d));
  17129. return $sigapp;
  17130. }
  17131. /**
  17132. * Create a new page group.
  17133. * NOTE: call this function before calling AddPage()
  17134. * @param $page (int) starting group page (leave empty for next page).
  17135. * @public
  17136. * @since 3.0.000 (2008-03-27)
  17137. */
  17138. public function startPageGroup($page='') {
  17139. if (empty($page)) {
  17140. $page = $this->page + 1;
  17141. }
  17142. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  17143. }
  17144. /**
  17145. * This method is DEPRECATED and doesn't have any effect.
  17146. * Please remove any reference to this method.
  17147. * @param $s (string) Empty parameter.
  17148. * @deprecated deprecated since version 5.9.089 (2011-06-13)
  17149. * @public
  17150. */
  17151. public function AliasNbPages($s='') {}
  17152. /**
  17153. * This method is DEPRECATED and doesn't have any effect.
  17154. * Please remove any reference to this method.
  17155. * @param $s (string) Empty parameter.
  17156. * @deprecated deprecated since version 5.9.089 (2011-06-13)
  17157. * @public
  17158. */
  17159. public function AliasNumPage($s='') {}
  17160. /**
  17161. * Set the starting page number.
  17162. * @param $num (int) Starting page number.
  17163. * @since 5.9.093 (2011-06-16)
  17164. * @public
  17165. */
  17166. public function setStartingPageNumber($num=1) {
  17167. $this->starting_page_number = max(0, intval($num));
  17168. }
  17169. /**
  17170. * Returns the string alias used right align page numbers.
  17171. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  17172. * @return string
  17173. * @since 5.9.099 (2011-06-27)
  17174. * @public
  17175. */
  17176. public function getAliasRightShift() {
  17177. // calculate aproximatively the ratio between widths of aliases and replacements.
  17178. $ref = '{'.$this->alias_right_shift.'}{'.$this->alias_tot_pages.'}{'.$this->alias_num_page.'}';
  17179. $rep = str_repeat(' ', $this->GetNumChars($ref));
  17180. $wdiff = max(1, ($this->GetStringWidth($ref) / $this->GetStringWidth($rep)));
  17181. $sdiff = sprintf('%.3F', $wdiff);
  17182. $alias = $this->alias_right_shift.$sdiff.'}';
  17183. if ($this->isUnicodeFont()) {
  17184. $alias = '{'.$alias;
  17185. }
  17186. return $alias;
  17187. }
  17188. /**
  17189. * Returns the string alias used for the total number of pages.
  17190. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17191. * This alias will be replaced by the total number of pages in the document.
  17192. * @return string
  17193. * @since 4.0.018 (2008-08-08)
  17194. * @public
  17195. */
  17196. public function getAliasNbPages() {
  17197. if ($this->isUnicodeFont()) {
  17198. return '{'.$this->alias_tot_pages.'}';
  17199. }
  17200. return $this->alias_tot_pages;
  17201. }
  17202. /**
  17203. * Returns the string alias used for the page number.
  17204. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17205. * This alias will be replaced by the page number.
  17206. * @return string
  17207. * @since 4.5.000 (2009-01-02)
  17208. * @public
  17209. */
  17210. public function getAliasNumPage() {
  17211. if ($this->isUnicodeFont()) {
  17212. return '{'.$this->alias_num_page.'}';
  17213. }
  17214. return $this->alias_num_page;
  17215. }
  17216. /**
  17217. * Return the alias for the total number of pages in the current page group.
  17218. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17219. * This alias will be replaced by the total number of pages in this group.
  17220. * @return alias of the current page group
  17221. * @public
  17222. * @since 3.0.000 (2008-03-27)
  17223. */
  17224. public function getPageGroupAlias() {
  17225. if ($this->isUnicodeFont()) {
  17226. return '{'.$this->alias_group_tot_pages.'}';
  17227. }
  17228. return $this->alias_group_tot_pages;
  17229. }
  17230. /**
  17231. * Return the alias for the page number on the current page group.
  17232. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17233. * This alias will be replaced by the page number (relative to the belonging group).
  17234. * @return alias of the current page group
  17235. * @public
  17236. * @since 4.5.000 (2009-01-02)
  17237. */
  17238. public function getPageNumGroupAlias() {
  17239. if ($this->isUnicodeFont()) {
  17240. return '{'.$this->alias_group_num_page.'}';
  17241. }
  17242. return $this->alias_group_num_page;
  17243. }
  17244. /**
  17245. * Return the current page in the group.
  17246. * @return current page in the group
  17247. * @public
  17248. * @since 3.0.000 (2008-03-27)
  17249. */
  17250. public function getGroupPageNo() {
  17251. return $this->pagegroups[$this->currpagegroup];
  17252. }
  17253. /**
  17254. * Returns the current group page number formatted as a string.
  17255. * @public
  17256. * @since 4.3.003 (2008-11-18)
  17257. * @see PaneNo(), formatPageNumber()
  17258. */
  17259. public function getGroupPageNoFormatted() {
  17260. return $this->formatPageNumber($this->getGroupPageNo());
  17261. }
  17262. /**
  17263. * Format the page numbers.
  17264. * This method can be overriden for custom formats.
  17265. * @param $num (int) page number
  17266. * @protected
  17267. * @since 4.2.005 (2008-11-06)
  17268. */
  17269. protected function formatPageNumber($num) {
  17270. return number_format((float)$num, 0, '', '.');
  17271. }
  17272. /**
  17273. * Format the page numbers on the Table Of Content.
  17274. * This method can be overriden for custom formats.
  17275. * @param $num (int) page number
  17276. * @protected
  17277. * @since 4.5.001 (2009-01-04)
  17278. * @see addTOC(), addHTMLTOC()
  17279. */
  17280. protected function formatTOCPageNumber($num) {
  17281. return number_format((float)$num, 0, '', '.');
  17282. }
  17283. /**
  17284. * Returns the current page number formatted as a string.
  17285. * @public
  17286. * @since 4.2.005 (2008-11-06)
  17287. * @see PaneNo(), formatPageNumber()
  17288. */
  17289. public function PageNoFormatted() {
  17290. return $this->formatPageNumber($this->PageNo());
  17291. }
  17292. /**
  17293. * Put pdf layers.
  17294. * @protected
  17295. * @since 3.0.000 (2008-03-27)
  17296. */
  17297. protected function _putocg() {
  17298. if (empty($this->pdflayers)) {
  17299. return;
  17300. }
  17301. foreach ($this->pdflayers as $key => $layer) {
  17302. $this->pdflayers[$key]['objid'] = $this->_newobj();
  17303. $out = '<< /Type /OCG';
  17304. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  17305. $out .= ' /Usage <<';
  17306. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  17307. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  17308. $out .= ' >> >>';
  17309. $out .= "\n".'endobj';
  17310. $this->_out($out);
  17311. }
  17312. }
  17313. /**
  17314. * Start a new pdf layer.
  17315. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  17316. * @param $print (boolean) Set to true to print this layer.
  17317. * @param $view (boolean) Set to true to view this layer.
  17318. * @public
  17319. * @since 5.9.102 (2011-07-13)
  17320. */
  17321. public function startLayer($name='', $print=true, $view=true) {
  17322. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  17323. if (empty($name)) {
  17324. $name = $layer;
  17325. } else {
  17326. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  17327. }
  17328. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view);
  17329. $this->openMarkedContent = true;
  17330. $this->_out('/OC /'.$layer.' BDC');
  17331. }
  17332. /**
  17333. * End the current PDF layer.
  17334. * @public
  17335. * @since 5.9.102 (2011-07-13)
  17336. */
  17337. public function endLayer() {
  17338. if ($this->openMarkedContent) {
  17339. // close existing open marked-content layer
  17340. $this->_out('EMC');
  17341. $this->openMarkedContent = false;
  17342. }
  17343. }
  17344. /**
  17345. * Set the visibility of the successive elements.
  17346. * This can be useful, for instance, to put a background
  17347. * image or color that will show on screen but won't print.
  17348. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  17349. * @public
  17350. * @since 3.0.000 (2008-03-27)
  17351. */
  17352. public function setVisibility($v) {
  17353. $this->endLayer();
  17354. switch($v) {
  17355. case 'print': {
  17356. $this->startLayer('Print', true, false);
  17357. break;
  17358. }
  17359. case 'view':
  17360. case 'screen': {
  17361. $this->startLayer('View', false, true);
  17362. break;
  17363. }
  17364. case 'all': {
  17365. $this->_out('');
  17366. break;
  17367. }
  17368. default: {
  17369. $this->Error('Incorrect visibility: '.$v);
  17370. break;
  17371. }
  17372. }
  17373. }
  17374. /**
  17375. * Add transparency parameters to the current extgstate
  17376. * @param $parms (array) parameters
  17377. * @return the number of extgstates
  17378. * @protected
  17379. * @since 3.0.000 (2008-03-27)
  17380. */
  17381. protected function addExtGState($parms) {
  17382. if ($this->pdfa_mode) {
  17383. // transparencies are not allowed in PDF/A mode
  17384. return;
  17385. }
  17386. // check if this ExtGState already exist
  17387. foreach ($this->extgstates as $i => $ext) {
  17388. if ($ext['parms'] == $parms) {
  17389. if ($this->inxobj) {
  17390. // we are inside an XObject template
  17391. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  17392. }
  17393. // return reference to existing ExtGState
  17394. return $i;
  17395. }
  17396. }
  17397. $n = (count($this->extgstates) + 1);
  17398. $this->extgstates[$n] = array('parms' => $parms);
  17399. if ($this->inxobj) {
  17400. // we are inside an XObject template
  17401. $this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
  17402. }
  17403. return $n;
  17404. }
  17405. /**
  17406. * Add an extgstate
  17407. * @param $gs (array) extgstate
  17408. * @protected
  17409. * @since 3.0.000 (2008-03-27)
  17410. */
  17411. protected function setExtGState($gs) {
  17412. if ($this->pdfa_mode) {
  17413. // transparency is not allowed in PDF/A mode
  17414. return;
  17415. }
  17416. $this->_out(sprintf('/GS%d gs', $gs));
  17417. }
  17418. /**
  17419. * Put extgstates for object transparency
  17420. * @protected
  17421. * @since 3.0.000 (2008-03-27)
  17422. */
  17423. protected function _putextgstates() {
  17424. if ($this->pdfa_mode) {
  17425. // transparencies are not allowed in PDF/A mode
  17426. return;
  17427. }
  17428. foreach ($this->extgstates as $i => $ext) {
  17429. $this->extgstates[$i]['n'] = $this->_newobj();
  17430. $out = '<< /Type /ExtGState';
  17431. foreach ($ext['parms'] as $k => $v) {
  17432. if (is_float($v)) {
  17433. $v = sprintf('%.2F', $v);
  17434. }
  17435. $out .= ' /'.$k.' '.$v;
  17436. }
  17437. $out .= ' >>';
  17438. $out .= "\n".'endobj';
  17439. $this->_out($out);
  17440. }
  17441. }
  17442. /**
  17443. * Set alpha for stroking (CA) and non-stroking (ca) operations.
  17444. * @param $alpha (float) real value from 0 (transparent) to 1 (opaque)
  17445. * @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
  17446. * @public
  17447. * @since 3.0.000 (2008-03-27)
  17448. */
  17449. public function setAlpha($alpha, $bm='Normal') {
  17450. if ($this->pdfa_mode) {
  17451. // transparency is not allowed in PDF/A mode
  17452. return;
  17453. }
  17454. $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm, 'AIS' => 'false'));
  17455. $this->setExtGState($gs);
  17456. }
  17457. /**
  17458. * Set the default JPEG compression quality (1-100)
  17459. * @param $quality (int) JPEG quality, integer between 1 and 100
  17460. * @public
  17461. * @since 3.0.000 (2008-03-27)
  17462. */
  17463. public function setJPEGQuality($quality) {
  17464. if (($quality < 1) OR ($quality > 100)) {
  17465. $quality = 75;
  17466. }
  17467. $this->jpeg_quality = intval($quality);
  17468. }
  17469. /**
  17470. * Set the default number of columns in a row for HTML tables.
  17471. * @param $cols (int) number of columns
  17472. * @public
  17473. * @since 3.0.014 (2008-06-04)
  17474. */
  17475. public function setDefaultTableColumns($cols=4) {
  17476. $this->default_table_columns = intval($cols);
  17477. }
  17478. /**
  17479. * Set the height of the cell (line height) respect the font height.
  17480. * @param $h (int) cell proportion respect font height (typical value = 1.25).
  17481. * @public
  17482. * @since 3.0.014 (2008-06-04)
  17483. */
  17484. public function setCellHeightRatio($h) {
  17485. $this->cell_height_ratio = $h;
  17486. }
  17487. /**
  17488. * return the height of cell repect font height.
  17489. * @public
  17490. * @since 4.0.012 (2008-07-24)
  17491. */
  17492. public function getCellHeightRatio() {
  17493. return $this->cell_height_ratio;
  17494. }
  17495. /**
  17496. * Set the PDF version (check PDF reference for valid values).
  17497. * @param $version (string) PDF document version.
  17498. * @public
  17499. * @since 3.1.000 (2008-06-09)
  17500. */
  17501. public function setPDFVersion($version='1.7') {
  17502. if ($this->pdfa_mode) {
  17503. // PDF/A mode
  17504. $this->PDFVersion = '1.4';
  17505. } else {
  17506. $this->PDFVersion = $version;
  17507. }
  17508. }
  17509. /**
  17510. * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
  17511. * (see Section 8.1 of PDF reference, "Viewer Preferences").
  17512. * <ul><li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li><li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li><li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li><li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li><li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li><li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li><li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li></ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li><li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li></ul></li><li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li><li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li><li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li><li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li></ul>
  17513. * @param $preferences (array) array of options.
  17514. * @author Nicola Asuni
  17515. * @public
  17516. * @since 3.1.000 (2008-06-09)
  17517. */
  17518. public function setViewerPreferences($preferences) {
  17519. $this->viewer_preferences = $preferences;
  17520. }
  17521. /**
  17522. * Paints color transition registration bars
  17523. * @param $x (float) abscissa of the top left corner of the rectangle.
  17524. * @param $y (float) ordinate of the top left corner of the rectangle.
  17525. * @param $w (float) width of the rectangle.
  17526. * @param $h (float) height of the rectangle.
  17527. * @param $transition (boolean) if true prints tcolor transitions to white.
  17528. * @param $vertical (boolean) if true prints bar vertically.
  17529. * @param $colors (string) colors to print, one letter per color separated by comma (for example 'A,W,R,G,B,C,M,Y,K'): A=black, W=white, R=red, G=green, B=blue, C=cyan, M=magenta, Y=yellow, K=black.
  17530. * @author Nicola Asuni
  17531. * @since 4.9.000 (2010-03-26)
  17532. * @public
  17533. */
  17534. public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
  17535. $bars = explode(',', $colors);
  17536. $numbars = count($bars); // number of bars to print
  17537. // set bar measures
  17538. if ($vertical) {
  17539. $coords = array(0, 0, 0, 1);
  17540. $wb = $w / $numbars; // bar width
  17541. $hb = $h; // bar height
  17542. $xd = $wb; // delta x
  17543. $yd = 0; // delta y
  17544. } else {
  17545. $coords = array(1, 0, 0, 0);
  17546. $wb = $w; // bar width
  17547. $hb = $h / $numbars; // bar height
  17548. $xd = 0; // delta x
  17549. $yd = $hb; // delta y
  17550. }
  17551. $xb = $x;
  17552. $yb = $y;
  17553. foreach ($bars as $col) {
  17554. switch ($col) {
  17555. // set transition colors
  17556. case 'A': { // BLACK
  17557. $col_a = array(255);
  17558. $col_b = array(0);
  17559. break;
  17560. }
  17561. case 'W': { // WHITE
  17562. $col_a = array(0);
  17563. $col_b = array(255);
  17564. break;
  17565. }
  17566. case 'R': { // R
  17567. $col_a = array(255,255,255);
  17568. $col_b = array(255,0,0);
  17569. break;
  17570. }
  17571. case 'G': { // G
  17572. $col_a = array(255,255,255);
  17573. $col_b = array(0,255,0);
  17574. break;
  17575. }
  17576. case 'B': { // B
  17577. $col_a = array(255,255,255);
  17578. $col_b = array(0,0,255);
  17579. break;
  17580. }
  17581. case 'C': { // C
  17582. $col_a = array(0,0,0,0);
  17583. $col_b = array(100,0,0,0);
  17584. break;
  17585. }
  17586. case 'M': { // M
  17587. $col_a = array(0,0,0,0);
  17588. $col_b = array(0,100,0,0);
  17589. break;
  17590. }
  17591. case 'Y': { // Y
  17592. $col_a = array(0,0,0,0);
  17593. $col_b = array(0,0,100,0);
  17594. break;
  17595. }
  17596. case 'K': { // K
  17597. $col_a = array(0,0,0,0);
  17598. $col_b = array(0,0,0,100);
  17599. break;
  17600. }
  17601. default: { // GRAY
  17602. $col_a = array(255);
  17603. $col_b = array(0);
  17604. break;
  17605. }
  17606. }
  17607. if ($transition) {
  17608. // color gradient
  17609. $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
  17610. } else {
  17611. // color rectangle
  17612. $this->SetFillColorArray($col_b);
  17613. $this->Rect($xb, $yb, $wb, $hb, 'F', array());
  17614. }
  17615. $xb += $xd;
  17616. $yb += $yd;
  17617. }
  17618. }
  17619. /**
  17620. * Paints crop marks.
  17621. * @param $x (float) abscissa of the crop mark center.
  17622. * @param $y (float) ordinate of the crop mark center.
  17623. * @param $w (float) width of the crop mark.
  17624. * @param $h (float) height of the crop mark.
  17625. * @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.
  17626. * @param $color (array) crop mark color (default black).
  17627. * @author Nicola Asuni
  17628. * @since 4.9.000 (2010-03-26)
  17629. * @public
  17630. */
  17631. public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(0,0,0)) {
  17632. $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
  17633. $type = strtoupper($type);
  17634. $type = preg_replace('/[^A-Z\-\,]*/', '', $type);
  17635. // split type in single components
  17636. $type = str_replace('-', ',', $type);
  17637. $type = str_replace('TL', 'T,L', $type);
  17638. $type = str_replace('TR', 'T,R', $type);
  17639. $type = str_replace('BL', 'F,L', $type);
  17640. $type = str_replace('BR', 'F,R', $type);
  17641. $type = str_replace('A', 'T,L', $type);
  17642. $type = str_replace('B', 'T,R', $type);
  17643. $type = str_replace('T,RO', 'BO', $type);
  17644. $type = str_replace('C', 'F,L', $type);
  17645. $type = str_replace('D', 'F,R', $type);
  17646. $crops = explode(',', strtoupper($type));
  17647. // remove duplicates
  17648. $crops = array_unique($crops);
  17649. $dw = ($w / 4); // horizontal space to leave before the intersection point
  17650. $dh = ($h / 4); // vertical space to leave before the intersection point
  17651. foreach ($crops as $crop) {
  17652. switch ($crop) {
  17653. case 'T':
  17654. case 'TOP': {
  17655. $x1 = $x;
  17656. $y1 = ($y - $h);
  17657. $x2 = $x;
  17658. $y2 = ($y - $dh);
  17659. break;
  17660. }
  17661. case 'F':
  17662. case 'BOTTOM': {
  17663. $x1 = $x;
  17664. $y1 = ($y + $dh);
  17665. $x2 = $x;
  17666. $y2 = ($y + $h);
  17667. break;
  17668. }
  17669. case 'L':
  17670. case 'LEFT': {
  17671. $x1 = ($x - $w);
  17672. $y1 = $y;
  17673. $x2 = ($x - $dw);
  17674. $y2 = $y;
  17675. break;
  17676. }
  17677. case 'R':
  17678. case 'RIGHT': {
  17679. $x1 = ($x + $dw);
  17680. $y1 = $y;
  17681. $x2 = ($x + $w);
  17682. $y2 = $y;
  17683. break;
  17684. }
  17685. }
  17686. $this->Line($x1, $y1, $x2, $y2);
  17687. }
  17688. }
  17689. /**
  17690. * Paints a registration mark
  17691. * @param $x (float) abscissa of the registration mark center.
  17692. * @param $y (float) ordinate of the registration mark center.
  17693. * @param $r (float) radius of the crop mark.
  17694. * @param $double (boolean) if true print two concentric crop marks.
  17695. * @param $cola (array) crop mark color (default black).
  17696. * @param $colb (array) second crop mark color.
  17697. * @author Nicola Asuni
  17698. * @since 4.9.000 (2010-03-26)
  17699. * @public
  17700. */
  17701. public function registrationMark($x, $y, $r, $double=false, $cola=array(0,0,0), $colb=array(255,255,255)) {
  17702. $line_style = array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
  17703. $this->SetFillColorArray($cola);
  17704. $this->PieSector($x, $y, $r, 90, 180, 'F');
  17705. $this->PieSector($x, $y, $r, 270, 360, 'F');
  17706. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  17707. if ($double) {
  17708. $r2 = $r * 0.5;
  17709. $this->SetFillColorArray($colb);
  17710. $this->PieSector($x, $y, $r2, 90, 180, 'F');
  17711. $this->PieSector($x, $y, $r2, 270, 360, 'F');
  17712. $this->SetFillColorArray($cola);
  17713. $this->PieSector($x, $y, $r2, 0, 90, 'F');
  17714. $this->PieSector($x, $y, $r2, 180, 270, 'F');
  17715. $this->Circle($x, $y, $r2, 0, 360, 'C', $line_style, array(), 8);
  17716. }
  17717. }
  17718. /**
  17719. * Paints a linear colour gradient.
  17720. * @param $x (float) abscissa of the top left corner of the rectangle.
  17721. * @param $y (float) ordinate of the top left corner of the rectangle.
  17722. * @param $w (float) width of the rectangle.
  17723. * @param $h (float) height of the rectangle.
  17724. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  17725. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  17726. * @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).
  17727. * @author Andreas Würmser, Nicola Asuni
  17728. * @since 3.1.000 (2008-06-09)
  17729. * @public
  17730. */
  17731. public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
  17732. $this->Clip($x, $y, $w, $h);
  17733. $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  17734. }
  17735. /**
  17736. * Paints a radial colour gradient.
  17737. * @param $x (float) abscissa of the top left corner of the rectangle.
  17738. * @param $y (float) ordinate of the top left corner of the rectangle.
  17739. * @param $w (float) width of the rectangle.
  17740. * @param $h (float) height of the rectangle.
  17741. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  17742. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  17743. * @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.
  17744. * @author Andreas Würmser, Nicola Asuni
  17745. * @since 3.1.000 (2008-06-09)
  17746. * @public
  17747. */
  17748. public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
  17749. $this->Clip($x, $y, $w, $h);
  17750. $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  17751. }
  17752. /**
  17753. * Paints a coons patch mesh.
  17754. * @param $x (float) abscissa of the top left corner of the rectangle.
  17755. * @param $y (float) ordinate of the top left corner of the rectangle.
  17756. * @param $w (float) width of the rectangle.
  17757. * @param $h (float) height of the rectangle.
  17758. * @param $col1 (array) first color (lower left corner) (RGB components).
  17759. * @param $col2 (array) second color (lower right corner) (RGB components).
  17760. * @param $col3 (array) third color (upper right corner) (RGB components).
  17761. * @param $col4 (array) fourth color (upper left corner) (RGB components).
  17762. * @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>
  17763. * @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
  17764. * @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
  17765. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  17766. * @author Andreas Würmser, Nicola Asuni
  17767. * @since 3.1.000 (2008-06-09)
  17768. * @public
  17769. */
  17770. 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) {
  17771. if ($this->pdfa_mode) {
  17772. return;
  17773. }
  17774. $this->Clip($x, $y, $w, $h);
  17775. $n = count($this->gradients) + 1;
  17776. $this->gradients[$n] = array();
  17777. $this->gradients[$n]['type'] = 6; //coons patch mesh
  17778. $this->gradients[$n]['coords'] = array();
  17779. $this->gradients[$n]['antialias'] = $antialias;
  17780. $this->gradients[$n]['colors'] = array();
  17781. $this->gradients[$n]['transparency'] = false;
  17782. //check the coords array if it is the simple array or the multi patch array
  17783. if (!isset($coords[0]['f'])) {
  17784. //simple array -> convert to multi patch array
  17785. if (!isset($col1[1])) {
  17786. $col1[1] = $col1[2] = $col1[0];
  17787. }
  17788. if (!isset($col2[1])) {
  17789. $col2[1] = $col2[2] = $col2[0];
  17790. }
  17791. if (!isset($col3[1])) {
  17792. $col3[1] = $col3[2] = $col3[0];
  17793. }
  17794. if (!isset($col4[1])) {
  17795. $col4[1] = $col4[2] = $col4[0];
  17796. }
  17797. $patch_array[0]['f'] = 0;
  17798. $patch_array[0]['points'] = $coords;
  17799. $patch_array[0]['colors'][0]['r'] = $col1[0];
  17800. $patch_array[0]['colors'][0]['g'] = $col1[1];
  17801. $patch_array[0]['colors'][0]['b'] = $col1[2];
  17802. $patch_array[0]['colors'][1]['r'] = $col2[0];
  17803. $patch_array[0]['colors'][1]['g'] = $col2[1];
  17804. $patch_array[0]['colors'][1]['b'] = $col2[2];
  17805. $patch_array[0]['colors'][2]['r'] = $col3[0];
  17806. $patch_array[0]['colors'][2]['g'] = $col3[1];
  17807. $patch_array[0]['colors'][2]['b'] = $col3[2];
  17808. $patch_array[0]['colors'][3]['r'] = $col4[0];
  17809. $patch_array[0]['colors'][3]['g'] = $col4[1];
  17810. $patch_array[0]['colors'][3]['b'] = $col4[2];
  17811. } else {
  17812. //multi patch array
  17813. $patch_array = $coords;
  17814. }
  17815. $bpcd = 65535; //16 bits per coordinate
  17816. //build the data stream
  17817. $this->gradients[$n]['stream'] = '';
  17818. $count_patch = count($patch_array);
  17819. for ($i=0; $i < $count_patch; ++$i) {
  17820. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
  17821. $count_points = count($patch_array[$i]['points']);
  17822. for ($j=0; $j < $count_points; ++$j) {
  17823. //each point as 16 bit
  17824. $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
  17825. if ($patch_array[$i]['points'][$j] < 0) {
  17826. $patch_array[$i]['points'][$j] = 0;
  17827. }
  17828. if ($patch_array[$i]['points'][$j] > $bpcd) {
  17829. $patch_array[$i]['points'][$j] = $bpcd;
  17830. }
  17831. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
  17832. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
  17833. }
  17834. $count_cols = count($patch_array[$i]['colors']);
  17835. for ($j=0; $j < $count_cols; ++$j) {
  17836. //each color component as 8 bit
  17837. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
  17838. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
  17839. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
  17840. }
  17841. }
  17842. //paint the gradient
  17843. $this->_out('/Sh'.$n.' sh');
  17844. //restore previous Graphic State
  17845. $this->_out('Q');
  17846. if ($this->inxobj) {
  17847. // we are inside an XObject template
  17848. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  17849. }
  17850. }
  17851. /**
  17852. * Set a rectangular clipping area.
  17853. * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
  17854. * @param $y (float) ordinate of the top left corner of the rectangle.
  17855. * @param $w (float) width of the rectangle.
  17856. * @param $h (float) height of the rectangle.
  17857. * @author Andreas Würmser, Nicola Asuni
  17858. * @since 3.1.000 (2008-06-09)
  17859. * @protected
  17860. */
  17861. protected function Clip($x, $y, $w, $h) {
  17862. if ($this->rtl) {
  17863. $x = $this->w - $x - $w;
  17864. }
  17865. //save current Graphic State
  17866. $s = 'q';
  17867. //set clipping area
  17868. $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
  17869. //set up transformation matrix for gradient
  17870. $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
  17871. $this->_out($s);
  17872. }
  17873. /**
  17874. * Output gradient.
  17875. * @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)
  17876. * @param $coords (array) array of coordinates.
  17877. * @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).
  17878. * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
  17879. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  17880. * @author Nicola Asuni
  17881. * @since 3.1.000 (2008-06-09)
  17882. * @public
  17883. */
  17884. public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
  17885. if ($this->pdfa_mode) {
  17886. return;
  17887. }
  17888. $n = count($this->gradients) + 1;
  17889. $this->gradients[$n] = array();
  17890. $this->gradients[$n]['type'] = $type;
  17891. $this->gradients[$n]['coords'] = $coords;
  17892. $this->gradients[$n]['antialias'] = $antialias;
  17893. $this->gradients[$n]['colors'] = array();
  17894. $this->gradients[$n]['transparency'] = false;
  17895. // color space
  17896. $numcolspace = count($stops[0]['color']);
  17897. $bcolor = array_values($background);
  17898. switch($numcolspace) {
  17899. case 4: { // CMYK
  17900. $this->gradients[$n]['colspace'] = 'DeviceCMYK';
  17901. if (!empty($background)) {
  17902. $this->gradients[$n]['background'] = sprintf('%.3F %.3F %.3F %.3F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
  17903. }
  17904. break;
  17905. }
  17906. case 3: { // RGB
  17907. $this->gradients[$n]['colspace'] = 'DeviceRGB';
  17908. if (!empty($background)) {
  17909. $this->gradients[$n]['background'] = sprintf('%.3F %.3F %.3F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
  17910. }
  17911. break;
  17912. }
  17913. case 1: { // Gray scale
  17914. $this->gradients[$n]['colspace'] = 'DeviceGray';
  17915. if (!empty($background)) {
  17916. $this->gradients[$n]['background'] = sprintf('%.3F', $bcolor[0]/255);
  17917. }
  17918. break;
  17919. }
  17920. }
  17921. $num_stops = count($stops);
  17922. $last_stop_id = $num_stops - 1;
  17923. foreach ($stops as $key => $stop) {
  17924. $this->gradients[$n]['colors'][$key] = array();
  17925. // offset represents a location along the gradient vector
  17926. if (isset($stop['offset'])) {
  17927. $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
  17928. } else {
  17929. if ($key == 0) {
  17930. $this->gradients[$n]['colors'][$key]['offset'] = 0;
  17931. } elseif ($key == $last_stop_id) {
  17932. $this->gradients[$n]['colors'][$key]['offset'] = 1;
  17933. } else {
  17934. $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
  17935. $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
  17936. }
  17937. }
  17938. if (isset($stop['opacity'])) {
  17939. $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
  17940. if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
  17941. $this->gradients[$n]['transparency'] = true;
  17942. }
  17943. } else {
  17944. $this->gradients[$n]['colors'][$key]['opacity'] = 1;
  17945. }
  17946. // exponent for the exponential interpolation function
  17947. if (isset($stop['exponent'])) {
  17948. $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
  17949. } else {
  17950. $this->gradients[$n]['colors'][$key]['exponent'] = 1;
  17951. }
  17952. // set colors
  17953. $color = array_values($stop['color']);
  17954. switch($numcolspace) {
  17955. case 4: { // CMYK
  17956. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F %.3F %.3F %.3F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
  17957. break;
  17958. }
  17959. case 3: { // RGB
  17960. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F %.3F %.3F', $color[0]/255, $color[1]/255, $color[2]/255);
  17961. break;
  17962. }
  17963. case 1: { // Gray scale
  17964. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F', $color[0]/255);
  17965. break;
  17966. }
  17967. }
  17968. }
  17969. if ($this->gradients[$n]['transparency']) {
  17970. // paint luminosity gradient
  17971. $this->_out('/TGS'.$n.' gs');
  17972. }
  17973. //paint the gradient
  17974. $this->_out('/Sh'.$n.' sh');
  17975. //restore previous Graphic State
  17976. $this->_out('Q');
  17977. if ($this->inxobj) {
  17978. // we are inside an XObject template
  17979. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  17980. }
  17981. }
  17982. /**
  17983. * Output gradient shaders.
  17984. * @author Nicola Asuni
  17985. * @since 3.1.000 (2008-06-09)
  17986. * @protected
  17987. */
  17988. function _putshaders() {
  17989. if ($this->pdfa_mode) {
  17990. return;
  17991. }
  17992. $idt = count($this->gradients); //index for transparency gradients
  17993. foreach ($this->gradients as $id => $grad) {
  17994. if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
  17995. $fc = $this->_newobj();
  17996. $out = '<<';
  17997. $out .= ' /FunctionType 3';
  17998. $out .= ' /Domain [0 1]';
  17999. $functions = '';
  18000. $bounds = '';
  18001. $encode = '';
  18002. $i = 1;
  18003. $num_cols = count($grad['colors']);
  18004. $lastcols = $num_cols - 1;
  18005. for ($i = 1; $i < $num_cols; ++$i) {
  18006. $functions .= ($fc + $i).' 0 R ';
  18007. if ($i < $lastcols) {
  18008. $bounds .= sprintf('%.3F ', $grad['colors'][$i]['offset']);
  18009. }
  18010. $encode .= '0 1 ';
  18011. }
  18012. $out .= ' /Functions ['.trim($functions).']';
  18013. $out .= ' /Bounds ['.trim($bounds).']';
  18014. $out .= ' /Encode ['.trim($encode).']';
  18015. $out .= ' >>';
  18016. $out .= "\n".'endobj';
  18017. $this->_out($out);
  18018. for ($i = 1; $i < $num_cols; ++$i) {
  18019. $this->_newobj();
  18020. $out = '<<';
  18021. $out .= ' /FunctionType 2';
  18022. $out .= ' /Domain [0 1]';
  18023. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
  18024. $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
  18025. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  18026. $out .= ' >>';
  18027. $out .= "\n".'endobj';
  18028. $this->_out($out);
  18029. }
  18030. // set transparency fuctions
  18031. if ($grad['transparency']) {
  18032. $ft = $this->_newobj();
  18033. $out = '<<';
  18034. $out .= ' /FunctionType 3';
  18035. $out .= ' /Domain [0 1]';
  18036. $functions = '';
  18037. $i = 1;
  18038. $num_cols = count($grad['colors']);
  18039. for ($i = 1; $i < $num_cols; ++$i) {
  18040. $functions .= ($ft + $i).' 0 R ';
  18041. }
  18042. $out .= ' /Functions ['.trim($functions).']';
  18043. $out .= ' /Bounds ['.trim($bounds).']';
  18044. $out .= ' /Encode ['.trim($encode).']';
  18045. $out .= ' >>';
  18046. $out .= "\n".'endobj';
  18047. $this->_out($out);
  18048. for ($i = 1; $i < $num_cols; ++$i) {
  18049. $this->_newobj();
  18050. $out = '<<';
  18051. $out .= ' /FunctionType 2';
  18052. $out .= ' /Domain [0 1]';
  18053. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
  18054. $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
  18055. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  18056. $out .= ' >>';
  18057. $out .= "\n".'endobj';
  18058. $this->_out($out);
  18059. }
  18060. }
  18061. }
  18062. // set shading object
  18063. $this->_newobj();
  18064. $out = '<< /ShadingType '.$grad['type'];
  18065. if (isset($grad['colspace'])) {
  18066. $out .= ' /ColorSpace /'.$grad['colspace'];
  18067. } else {
  18068. $out .= ' /ColorSpace /DeviceRGB';
  18069. }
  18070. if (isset($grad['background']) AND !empty($grad['background'])) {
  18071. $out .= ' /Background ['.$grad['background'].']';
  18072. }
  18073. if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
  18074. $out .= ' /AntiAlias true';
  18075. }
  18076. if ($grad['type'] == 2) {
  18077. $out .= ' '.sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
  18078. $out .= ' /Domain [0 1]';
  18079. $out .= ' /Function '.$fc.' 0 R';
  18080. $out .= ' /Extend [true true]';
  18081. $out .= ' >>';
  18082. } elseif ($grad['type'] == 3) {
  18083. //x0, y0, r0, x1, y1, r1
  18084. //at this this time radius of inner circle is 0
  18085. $out .= ' '.sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
  18086. $out .= ' /Domain [0 1]';
  18087. $out .= ' /Function '.$fc.' 0 R';
  18088. $out .= ' /Extend [true true]';
  18089. $out .= ' >>';
  18090. } elseif ($grad['type'] == 6) {
  18091. $out .= ' /BitsPerCoordinate 16';
  18092. $out .= ' /BitsPerComponent 8';
  18093. $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
  18094. $out .= ' /BitsPerFlag 8';
  18095. $stream = $this->_getrawstream($grad['stream']);
  18096. $out .= ' /Length '.strlen($stream);
  18097. $out .= ' >>';
  18098. $out .= ' stream'."\n".$stream."\n".'endstream';
  18099. }
  18100. $out .= "\n".'endobj';
  18101. $this->_out($out);
  18102. if ($grad['transparency']) {
  18103. $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
  18104. $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
  18105. }
  18106. $this->gradients[$id]['id'] = $this->n;
  18107. // set pattern object
  18108. $this->_newobj();
  18109. $out = '<< /Type /Pattern /PatternType 2';
  18110. $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
  18111. $out .= ' >>';
  18112. $out .= "\n".'endobj';
  18113. $this->_out($out);
  18114. $this->gradients[$id]['pattern'] = $this->n;
  18115. // set shading and pattern for transparency mask
  18116. if ($grad['transparency']) {
  18117. // luminosity pattern
  18118. $idgs = $id + $idt;
  18119. $this->_newobj();
  18120. $this->_out($shading_transparency);
  18121. $this->gradients[$idgs]['id'] = $this->n;
  18122. $this->_newobj();
  18123. $out = '<< /Type /Pattern /PatternType 2';
  18124. $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
  18125. $out .= ' >>';
  18126. $out .= "\n".'endobj';
  18127. $this->_out($out);
  18128. $this->gradients[$idgs]['pattern'] = $this->n;
  18129. // luminosity XObject
  18130. $oid = $this->_newobj();
  18131. $this->xobjects['LX'.$oid] = array('n' => $oid);
  18132. $filter = '';
  18133. $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
  18134. if ($this->compress) {
  18135. $filter = ' /Filter /FlateDecode';
  18136. $stream = gzcompress($stream);
  18137. }
  18138. $stream = $this->_getrawstream($stream);
  18139. $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
  18140. $out .= ' /Length '.strlen($stream);
  18141. $rect = sprintf('%.2F %.2F', $this->wPt, $this->hPt);
  18142. $out .= ' /BBox [0 0 '.$rect.']';
  18143. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
  18144. $out .= ' /Resources <<';
  18145. $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
  18146. $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
  18147. $out .= ' >>';
  18148. $out .= ' >> ';
  18149. $out .= ' stream'."\n".$stream."\n".'endstream';
  18150. $out .= "\n".'endobj';
  18151. $this->_out($out);
  18152. // SMask
  18153. $this->_newobj();
  18154. $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
  18155. $this->_out($out);
  18156. // ExtGState
  18157. $this->_newobj();
  18158. $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
  18159. $this->_out($out);
  18160. $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
  18161. }
  18162. }
  18163. }
  18164. /**
  18165. * Draw the sector of a circle.
  18166. * It can be used for instance to render pie charts.
  18167. * @param $xc (float) abscissa of the center.
  18168. * @param $yc (float) ordinate of the center.
  18169. * @param $r (float) radius.
  18170. * @param $a (float) start angle (in degrees).
  18171. * @param $b (float) end angle (in degrees).
  18172. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  18173. * @param $cw: (float) indicates whether to go clockwise (default: true).
  18174. * @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.
  18175. * @author Maxime Delorme, Nicola Asuni
  18176. * @since 3.1.000 (2008-06-09)
  18177. * @public
  18178. */
  18179. public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
  18180. $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
  18181. }
  18182. /**
  18183. * Draw the sector of an ellipse.
  18184. * It can be used for instance to render pie charts.
  18185. * @param $xc (float) abscissa of the center.
  18186. * @param $yc (float) ordinate of the center.
  18187. * @param $rx (float) the x-axis radius.
  18188. * @param $ry (float) the y-axis radius.
  18189. * @param $a (float) start angle (in degrees).
  18190. * @param $b (float) end angle (in degrees).
  18191. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  18192. * @param $cw: (float) indicates whether to go clockwise.
  18193. * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
  18194. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
  18195. * @author Maxime Delorme, Nicola Asuni
  18196. * @since 3.1.000 (2008-06-09)
  18197. * @public
  18198. */
  18199. public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
  18200. if ($this->rtl) {
  18201. $xc = $this->w - $xc;
  18202. }
  18203. $op = $this->getPathPaintOperator($style);
  18204. if ($op == 'f') {
  18205. $line_style = array();
  18206. }
  18207. if ($cw) {
  18208. $d = $b;
  18209. $b = 360 - $a + $o;
  18210. $a = 360 - $d + $o;
  18211. } else {
  18212. $b += $o;
  18213. $a += $o;
  18214. }
  18215. $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
  18216. $this->_out($op);
  18217. }
  18218. /**
  18219. * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
  18220. * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  18221. * Only vector drawing is supported, not text or bitmap.
  18222. * 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).
  18223. * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
  18224. * @param $x (float) Abscissa of the upper-left corner.
  18225. * @param $y (float) Ordinate of the upper-left corner.
  18226. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  18227. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  18228. * @param $link (mixed) URL or identifier returned by AddLink().
  18229. * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
  18230. * @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>
  18231. * @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>
  18232. * @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)))
  18233. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  18234. * @param $fixoutvals (boolean) if true remove values outside the bounding box.
  18235. * @author Valentin Schmidt, Nicola Asuni
  18236. * @since 3.1.000 (2008-06-09)
  18237. * @public
  18238. */
  18239. public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
  18240. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  18241. // convert EPS to raster image using GD or ImageMagick libraries
  18242. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  18243. }
  18244. if ($x === '') {
  18245. $x = $this->x;
  18246. }
  18247. if ($y === '') {
  18248. $y = $this->y;
  18249. }
  18250. // check page for no-write regions and adapt page margins if necessary
  18251. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  18252. $k = $this->k;
  18253. if ($file{0} === '@') { // image from string
  18254. $data = substr($file, 1);
  18255. } else { // EPS/AI file
  18256. $data = file_get_contents($file);
  18257. }
  18258. if ($data === false) {
  18259. $this->Error('EPS file not found: '.$file);
  18260. }
  18261. $regs = array();
  18262. // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
  18263. preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
  18264. if (count($regs) > 1) {
  18265. $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
  18266. if (strpos($version_str, 'Adobe Illustrator') !== false) {
  18267. $versexp = explode(' ', $version_str);
  18268. $version = (float)array_pop($versexp);
  18269. if ($version >= 9) {
  18270. $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
  18271. }
  18272. }
  18273. }
  18274. // strip binary bytes in front of PS-header
  18275. $start = strpos($data, '%!PS-Adobe');
  18276. if ($start > 0) {
  18277. $data = substr($data, $start);
  18278. }
  18279. // find BoundingBox params
  18280. preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
  18281. if (count($regs) > 1) {
  18282. list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
  18283. } else {
  18284. $this->Error('No BoundingBox found in EPS/AI file: '.$file);
  18285. }
  18286. $start = strpos($data, '%%EndSetup');
  18287. if ($start === false) {
  18288. $start = strpos($data, '%%EndProlog');
  18289. }
  18290. if ($start === false) {
  18291. $start = strpos($data, '%%BoundingBox');
  18292. }
  18293. $data = substr($data, $start);
  18294. $end = strpos($data, '%%PageTrailer');
  18295. if ($end===false) {
  18296. $end = strpos($data, 'showpage');
  18297. }
  18298. if ($end) {
  18299. $data = substr($data, 0, $end);
  18300. }
  18301. // calculate image width and height on document
  18302. if (($w <= 0) AND ($h <= 0)) {
  18303. $w = ($x2 - $x1) / $k;
  18304. $h = ($y2 - $y1) / $k;
  18305. } elseif ($w <= 0) {
  18306. $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
  18307. } elseif ($h <= 0) {
  18308. $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
  18309. }
  18310. // fit the image on available space
  18311. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  18312. if ($this->rasterize_vector_images) {
  18313. // convert EPS to raster image using GD or ImageMagick libraries
  18314. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  18315. }
  18316. // set scaling factors
  18317. $scale_x = $w / (($x2 - $x1) / $k);
  18318. $scale_y = $h / (($y2 - $y1) / $k);
  18319. // set alignment
  18320. $this->img_rb_y = $y + $h;
  18321. // set alignment
  18322. if ($this->rtl) {
  18323. if ($palign == 'L') {
  18324. $ximg = $this->lMargin;
  18325. } elseif ($palign == 'C') {
  18326. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  18327. } elseif ($palign == 'R') {
  18328. $ximg = $this->w - $this->rMargin - $w;
  18329. } else {
  18330. $ximg = $x - $w;
  18331. }
  18332. $this->img_rb_x = $ximg;
  18333. } else {
  18334. if ($palign == 'L') {
  18335. $ximg = $this->lMargin;
  18336. } elseif ($palign == 'C') {
  18337. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  18338. } elseif ($palign == 'R') {
  18339. $ximg = $this->w - $this->rMargin - $w;
  18340. } else {
  18341. $ximg = $x;
  18342. }
  18343. $this->img_rb_x = $ximg + $w;
  18344. }
  18345. if ($useBoundingBox) {
  18346. $dx = $ximg * $k - $x1;
  18347. $dy = $y * $k - $y1;
  18348. } else {
  18349. $dx = $ximg * $k;
  18350. $dy = $y * $k;
  18351. }
  18352. // save the current graphic state
  18353. $this->_out('q'.$this->epsmarker);
  18354. // translate
  18355. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
  18356. // scale
  18357. if (isset($scale_x)) {
  18358. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
  18359. }
  18360. // handle pc/unix/mac line endings
  18361. $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
  18362. $u=0;
  18363. $cnt = count($lines);
  18364. for ($i=0; $i < $cnt; ++$i) {
  18365. $line = $lines[$i];
  18366. if (($line == '') OR ($line{0} == '%')) {
  18367. continue;
  18368. }
  18369. $len = strlen($line);
  18370. // check for spot color names
  18371. $color_name = '';
  18372. if (strcasecmp('x', substr(trim($line), -1)) == 0) {
  18373. if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
  18374. // extract spot color name
  18375. $color_name = $matches[0];
  18376. // remove color name from string
  18377. $line = str_replace(' '.$color_name, '', $line);
  18378. // remove pharentesis from color name
  18379. $color_name = substr($color_name, 1, -1);
  18380. }
  18381. }
  18382. $chunks = explode(' ', $line);
  18383. $cmd = trim(array_pop($chunks));
  18384. // RGB
  18385. if (($cmd == 'Xa') OR ($cmd == 'XA')) {
  18386. $b = array_pop($chunks);
  18387. $g = array_pop($chunks);
  18388. $r = array_pop($chunks);
  18389. $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!
  18390. continue;
  18391. }
  18392. $skip = false;
  18393. if ($fixoutvals) {
  18394. // check for values outside the bounding box
  18395. switch ($cmd) {
  18396. case 'm':
  18397. case 'l':
  18398. case 'L': {
  18399. // skip values outside bounding box
  18400. foreach ($chunks as $key => $val) {
  18401. if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
  18402. $skip = true;
  18403. } elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
  18404. $skip = true;
  18405. }
  18406. }
  18407. }
  18408. }
  18409. }
  18410. switch ($cmd) {
  18411. case 'm':
  18412. case 'l':
  18413. case 'v':
  18414. case 'y':
  18415. case 'c':
  18416. case 'k':
  18417. case 'K':
  18418. case 'g':
  18419. case 'G':
  18420. case 's':
  18421. case 'S':
  18422. case 'J':
  18423. case 'j':
  18424. case 'w':
  18425. case 'M':
  18426. case 'd':
  18427. case 'n': {
  18428. if ($skip) {
  18429. break;
  18430. }
  18431. $this->_out($line);
  18432. break;
  18433. }
  18434. case 'x': {// custom fill color
  18435. if (empty($color_name)) {
  18436. // CMYK color
  18437. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  18438. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
  18439. } else {
  18440. // Spot Color (CMYK + tint)
  18441. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  18442. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  18443. $color_cmd = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  18444. $this->_out($color_cmd);
  18445. }
  18446. break;
  18447. }
  18448. case 'X': { // custom stroke color
  18449. if (empty($color_name)) {
  18450. // CMYK color
  18451. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  18452. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
  18453. } else {
  18454. // Spot Color (CMYK + tint)
  18455. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  18456. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  18457. $color_cmd = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  18458. $this->_out($color_cmd);
  18459. }
  18460. break;
  18461. }
  18462. case 'Y':
  18463. case 'N':
  18464. case 'V':
  18465. case 'L':
  18466. case 'C': {
  18467. if ($skip) {
  18468. break;
  18469. }
  18470. $line[($len - 1)] = strtolower($cmd);
  18471. $this->_out($line);
  18472. break;
  18473. }
  18474. case 'b':
  18475. case 'B': {
  18476. $this->_out($cmd . '*');
  18477. break;
  18478. }
  18479. case 'f':
  18480. case 'F': {
  18481. if ($u > 0) {
  18482. $isU = false;
  18483. $max = min(($i + 5), $cnt);
  18484. for ($j = ($i + 1); $j < $max; ++$j) {
  18485. $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
  18486. }
  18487. if ($isU) {
  18488. $this->_out('f*');
  18489. }
  18490. } else {
  18491. $this->_out('f*');
  18492. }
  18493. break;
  18494. }
  18495. case '*u': {
  18496. ++$u;
  18497. break;
  18498. }
  18499. case '*U': {
  18500. --$u;
  18501. break;
  18502. }
  18503. }
  18504. }
  18505. // restore previous graphic state
  18506. $this->_out($this->epsmarker.'Q');
  18507. if (!empty($border)) {
  18508. $bx = $this->x;
  18509. $by = $this->y;
  18510. $this->x = $ximg;
  18511. if ($this->rtl) {
  18512. $this->x += $w;
  18513. }
  18514. $this->y = $y;
  18515. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  18516. $this->x = $bx;
  18517. $this->y = $by;
  18518. }
  18519. if ($link) {
  18520. $this->Link($ximg, $y, $w, $h, $link, 0);
  18521. }
  18522. // set pointer to align the next text/objects
  18523. switch($align) {
  18524. case 'T':{
  18525. $this->y = $y;
  18526. $this->x = $this->img_rb_x;
  18527. break;
  18528. }
  18529. case 'M':{
  18530. $this->y = $y + round($h/2);
  18531. $this->x = $this->img_rb_x;
  18532. break;
  18533. }
  18534. case 'B':{
  18535. $this->y = $this->img_rb_y;
  18536. $this->x = $this->img_rb_x;
  18537. break;
  18538. }
  18539. case 'N':{
  18540. $this->SetY($this->img_rb_y);
  18541. break;
  18542. }
  18543. default:{
  18544. break;
  18545. }
  18546. }
  18547. $this->endlinex = $this->img_rb_x;
  18548. }
  18549. /**
  18550. * Set document barcode.
  18551. * @param $bc (string) barcode
  18552. * @public
  18553. */
  18554. public function setBarcode($bc='') {
  18555. $this->barcode = $bc;
  18556. }
  18557. /**
  18558. * Get current barcode.
  18559. * @return string
  18560. * @public
  18561. * @since 4.0.012 (2008-07-24)
  18562. */
  18563. public function getBarcode() {
  18564. return $this->barcode;
  18565. }
  18566. /**
  18567. * Print a Linear Barcode.
  18568. * @param $code (string) code to print
  18569. * @param $type (string) type of barcode (see barcodes.php for supported formats).
  18570. * @param $x (int) x position in user units (empty string = current x position)
  18571. * @param $y (int) y position in user units (empty string = current y position)
  18572. * @param $w (int) width in user units (empty string = remaining page width)
  18573. * @param $h (int) height in user units (empty string = remaining page height)
  18574. * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
  18575. * @param $style (array) array of options:<ul>
  18576. * <li>boolean $style['border'] if true prints a border</li>
  18577. * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
  18578. * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
  18579. * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
  18580. * <li>array $style['fgcolor'] color array for bars and text</li>
  18581. * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
  18582. * <li>boolean $style['text'] if true prints text below the barcode</li>
  18583. * <li>string $style['label'] override default label</li>
  18584. * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
  18585. * <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>
  18586. * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
  18587. * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
  18588. * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
  18589. * <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>
  18590. * <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>
  18591. * @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>
  18592. * @author Nicola Asuni
  18593. * @since 3.1.000 (2008-06-09)
  18594. * @public
  18595. */
  18596. public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style='', $align='') {
  18597. if ($this->empty_string(trim($code))) {
  18598. return;
  18599. }
  18600. require_once(dirname(__FILE__).'/barcodes.php');
  18601. // save current graphic settings
  18602. $gvars = $this->getGraphicVars();
  18603. // create new barcode object
  18604. $barcodeobj = new TCPDFBarcode($code, $type);
  18605. $arrcode = $barcodeobj->getBarcodeArray();
  18606. if ($arrcode === false) {
  18607. $this->Error('Error in 1D barcode string');
  18608. }
  18609. // set default values
  18610. if (!isset($style['position'])) {
  18611. $style['position'] = '';
  18612. } elseif ($style['position'] == 'S') {
  18613. // keep this for backward compatibility
  18614. $style['position'] = '';
  18615. $style['stretch'] = true;
  18616. }
  18617. if (!isset($style['fitwidth'])) {
  18618. if (!isset($style['stretch'])) {
  18619. $style['fitwidth'] = true;
  18620. } else {
  18621. $style['fitwidth'] = false;
  18622. }
  18623. }
  18624. if ($style['fitwidth']) {
  18625. // disable stretch
  18626. $style['stretch'] = false;
  18627. }
  18628. if (!isset($style['stretch'])) {
  18629. if (($w === '') OR ($w <= 0)) {
  18630. $style['stretch'] = false;
  18631. } else {
  18632. $style['stretch'] = true;
  18633. }
  18634. }
  18635. if (!isset($style['fgcolor'])) {
  18636. $style['fgcolor'] = array(0,0,0); // default black
  18637. }
  18638. if (!isset($style['bgcolor'])) {
  18639. $style['bgcolor'] = false; // default transparent
  18640. }
  18641. if (!isset($style['border'])) {
  18642. $style['border'] = false;
  18643. }
  18644. $fontsize = 0;
  18645. if (!isset($style['text'])) {
  18646. $style['text'] = false;
  18647. }
  18648. if ($style['text'] AND isset($style['font'])) {
  18649. if (isset($style['fontsize'])) {
  18650. $fontsize = $style['fontsize'];
  18651. }
  18652. $this->SetFont($style['font'], '', $fontsize);
  18653. }
  18654. if (!isset($style['stretchtext'])) {
  18655. $style['stretchtext'] = 4;
  18656. }
  18657. if ($x === '') {
  18658. $x = $this->x;
  18659. }
  18660. if ($y === '') {
  18661. $y = $this->y;
  18662. }
  18663. // check page for no-write regions and adapt page margins if necessary
  18664. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  18665. if (($w === '') OR ($w <= 0)) {
  18666. if ($this->rtl) {
  18667. $w = $x - $this->lMargin;
  18668. } else {
  18669. $w = $this->w - $this->rMargin - $x;
  18670. }
  18671. }
  18672. // padding
  18673. if (!isset($style['padding'])) {
  18674. $padding = 0;
  18675. } elseif ($style['padding'] === 'auto') {
  18676. $padding = 10 * ($w / ($arrcode['maxw'] + 20));
  18677. } else {
  18678. $padding = floatval($style['padding']);
  18679. }
  18680. // horizontal padding
  18681. if (!isset($style['hpadding'])) {
  18682. $hpadding = $padding;
  18683. } elseif ($style['hpadding'] === 'auto') {
  18684. $hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
  18685. } else {
  18686. $hpadding = floatval($style['hpadding']);
  18687. }
  18688. // vertical padding
  18689. if (!isset($style['vpadding'])) {
  18690. $vpadding = $padding;
  18691. } elseif ($style['vpadding'] === 'auto') {
  18692. $vpadding = ($hpadding / 2);
  18693. } else {
  18694. $vpadding = floatval($style['vpadding']);
  18695. }
  18696. // calculate xres (single bar width)
  18697. $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
  18698. if ($style['stretch']) {
  18699. $xres = $max_xres;
  18700. } else {
  18701. if ($this->empty_string($xres)) {
  18702. $xres = (0.141 * $this->k); // default bar width = 0.4 mm
  18703. }
  18704. if ($xres > $max_xres) {
  18705. // correct xres to fit on $w
  18706. $xres = $max_xres;
  18707. }
  18708. if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
  18709. OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
  18710. $hpadding = 10 * $xres;
  18711. if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
  18712. $vpadding = ($hpadding / 2);
  18713. }
  18714. }
  18715. }
  18716. if ($style['fitwidth']) {
  18717. $wold = $w;
  18718. $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
  18719. if (isset($style['cellfitalign'])) {
  18720. switch ($style['cellfitalign']) {
  18721. case 'L': {
  18722. if ($this->rtl) {
  18723. $x -= ($wold - $w);
  18724. }
  18725. break;
  18726. }
  18727. case 'R': {
  18728. if (!$this->rtl) {
  18729. $x += ($wold - $w);
  18730. }
  18731. break;
  18732. }
  18733. case 'C': {
  18734. if ($this->rtl) {
  18735. $x -= (($wold - $w) / 2);
  18736. } else {
  18737. $x += (($wold - $w) / 2);
  18738. }
  18739. break;
  18740. }
  18741. default : {
  18742. break;
  18743. }
  18744. }
  18745. }
  18746. }
  18747. $text_height = ($this->cell_height_ratio * $fontsize / $this->k);
  18748. // height
  18749. if (($h === '') OR ($h <= 0)) {
  18750. // set default height
  18751. $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
  18752. }
  18753. $barh = $h - $text_height - (2 * $vpadding);
  18754. if ($barh <=0) {
  18755. // try to reduce font or padding to fit barcode on available height
  18756. if ($text_height > $h) {
  18757. $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
  18758. $text_height = ($this->cell_height_ratio * $fontsize / $this->k);
  18759. $this->SetFont($style['font'], '', $fontsize);
  18760. }
  18761. if ($vpadding > 0) {
  18762. $vpadding = (($h - $text_height) / 4);
  18763. }
  18764. $barh = $h - $text_height - (2 * $vpadding);
  18765. }
  18766. // fit the barcode on available space
  18767. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  18768. // set alignment
  18769. $this->img_rb_y = $y + $h;
  18770. // set alignment
  18771. if ($this->rtl) {
  18772. if ($style['position'] == 'L') {
  18773. $xpos = $this->lMargin;
  18774. } elseif ($style['position'] == 'C') {
  18775. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  18776. } elseif ($style['position'] == 'R') {
  18777. $xpos = $this->w - $this->rMargin - $w;
  18778. } else {
  18779. $xpos = $x - $w;
  18780. }
  18781. $this->img_rb_x = $xpos;
  18782. } else {
  18783. if ($style['position'] == 'L') {
  18784. $xpos = $this->lMargin;
  18785. } elseif ($style['position'] == 'C') {
  18786. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  18787. } elseif ($style['position'] == 'R') {
  18788. $xpos = $this->w - $this->rMargin - $w;
  18789. } else {
  18790. $xpos = $x;
  18791. }
  18792. $this->img_rb_x = $xpos + $w;
  18793. }
  18794. $xpos_rect = $xpos;
  18795. if (!isset($style['align'])) {
  18796. $style['align'] = 'C';
  18797. }
  18798. switch ($style['align']) {
  18799. case 'L': {
  18800. $xpos = $xpos_rect + $hpadding;
  18801. break;
  18802. }
  18803. case 'R': {
  18804. $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
  18805. break;
  18806. }
  18807. case 'C':
  18808. default : {
  18809. $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
  18810. break;
  18811. }
  18812. }
  18813. $xpos_text = $xpos;
  18814. // barcode is always printed in LTR direction
  18815. $tempRTL = $this->rtl;
  18816. $this->rtl = false;
  18817. // print background color
  18818. if ($style['bgcolor']) {
  18819. $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  18820. } elseif ($style['border']) {
  18821. $this->Rect($xpos_rect, $y, $w, $h, 'D');
  18822. }
  18823. // set foreground color
  18824. $this->SetDrawColorArray($style['fgcolor']);
  18825. $this->SetTextColorArray($style['fgcolor']);
  18826. // print bars
  18827. foreach ($arrcode['bcode'] as $k => $v) {
  18828. $bw = ($v['w'] * $xres);
  18829. if ($v['t']) {
  18830. // draw a vertical bar
  18831. $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
  18832. $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
  18833. }
  18834. $xpos += $bw;
  18835. }
  18836. // print text
  18837. if ($style['text']) {
  18838. if (isset($style['label']) AND !$this->empty_string($style['label'])) {
  18839. $label = $style['label'];
  18840. } else {
  18841. $label = $code;
  18842. }
  18843. $txtwidth = ($arrcode['maxw'] * $xres);
  18844. if ($this->GetStringWidth($label) > $txtwidth) {
  18845. $style['stretchtext'] = 2;
  18846. }
  18847. // print text
  18848. $this->x = $xpos_text;
  18849. $this->y = $y + $vpadding + $barh;
  18850. $cellpadding = $this->cell_padding;
  18851. $this->SetCellPadding(0);
  18852. $this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
  18853. $this->cell_padding = $cellpadding;
  18854. }
  18855. // restore original direction
  18856. $this->rtl = $tempRTL;
  18857. // restore previous settings
  18858. $this->setGraphicVars($gvars);
  18859. // set pointer to align the next text/objects
  18860. switch($align) {
  18861. case 'T':{
  18862. $this->y = $y;
  18863. $this->x = $this->img_rb_x;
  18864. break;
  18865. }
  18866. case 'M':{
  18867. $this->y = $y + round($h / 2);
  18868. $this->x = $this->img_rb_x;
  18869. break;
  18870. }
  18871. case 'B':{
  18872. $this->y = $this->img_rb_y;
  18873. $this->x = $this->img_rb_x;
  18874. break;
  18875. }
  18876. case 'N':{
  18877. $this->SetY($this->img_rb_y);
  18878. break;
  18879. }
  18880. default:{
  18881. break;
  18882. }
  18883. }
  18884. $this->endlinex = $this->img_rb_x;
  18885. }
  18886. /**
  18887. * This function is DEPRECATED, please use the new write1DBarcode() function.
  18888. * @param $x (int) x position in user units
  18889. * @param $y (int) y position in user units
  18890. * @param $w (int) width in user units
  18891. * @param $h (int) height position in user units
  18892. * @param $type (string) type of barcode
  18893. * @param $style (string) barcode style
  18894. * @param $font (string) font for text
  18895. * @param $xres (int) x resolution
  18896. * @param $code (string) code to print
  18897. * @deprecated deprecated since version 3.1.000 (2008-06-10)
  18898. * @public
  18899. * @see write1DBarcode()
  18900. */
  18901. public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
  18902. // convert old settings for the new write1DBarcode() function.
  18903. $xres = 1 / $xres;
  18904. $newstyle = array(
  18905. 'position' => '',
  18906. 'align' => '',
  18907. 'stretch' => false,
  18908. 'fitwidth' => false,
  18909. 'cellfitalign' => '',
  18910. 'border' => false,
  18911. 'padding' => 0,
  18912. 'fgcolor' => array(0,0,0),
  18913. 'bgcolor' => false,
  18914. 'text' => true,
  18915. 'font' => $font,
  18916. 'fontsize' => 8,
  18917. 'stretchtext' => 4
  18918. );
  18919. if ($style & 1) {
  18920. $newstyle['border'] = true;
  18921. }
  18922. if ($style & 2) {
  18923. $newstyle['bgcolor'] = false;
  18924. }
  18925. if ($style & 4) {
  18926. $newstyle['position'] = 'C';
  18927. } elseif ($style & 8) {
  18928. $newstyle['position'] = 'L';
  18929. } elseif ($style & 16) {
  18930. $newstyle['position'] = 'R';
  18931. }
  18932. if ($style & 128) {
  18933. $newstyle['text'] = true;
  18934. }
  18935. if ($style & 256) {
  18936. $newstyle['stretchtext'] = 4;
  18937. }
  18938. $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
  18939. }
  18940. /**
  18941. * Print 2D Barcode.
  18942. * @param $code (string) code to print
  18943. * @param $type (string) type of barcode (see 2dbarcodes.php for supported formats).
  18944. * @param $x (int) x position in user units
  18945. * @param $y (int) y position in user units
  18946. * @param $w (int) width in user units
  18947. * @param $h (int) height in user units
  18948. * @param $style (array) array of options:<ul>
  18949. * <li>boolean $style['border'] if true prints a border around the barcode</li>
  18950. * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
  18951. * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
  18952. * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
  18953. * <li>int $style['module_width'] width of a single module in points</li>
  18954. * <li>int $style['module_height'] height of a single module in points</li>
  18955. * <li>array $style['fgcolor'] color array for bars and text</li>
  18956. * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
  18957. * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li><li>$style['module_width'] width of a single module in points</li>
  18958. * <li>$style['module_height'] height of a single module in points</li></ul>
  18959. * @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>
  18960. * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
  18961. * @author Nicola Asuni
  18962. * @since 4.5.037 (2009-04-07)
  18963. * @public
  18964. */
  18965. public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='', $distort=false) {
  18966. if ($this->empty_string(trim($code))) {
  18967. return;
  18968. }
  18969. require_once(dirname(__FILE__).'/2dbarcodes.php');
  18970. // save current graphic settings
  18971. $gvars = $this->getGraphicVars();
  18972. // create new barcode object
  18973. $barcodeobj = new TCPDF2DBarcode($code, $type);
  18974. $arrcode = $barcodeobj->getBarcodeArray();
  18975. if (($arrcode === false) OR empty($arrcode)) {
  18976. $this->Error('Error in 2D barcode string');
  18977. }
  18978. // set default values
  18979. if (!isset($style['position'])) {
  18980. $style['position'] = '';
  18981. }
  18982. if (!isset($style['fgcolor'])) {
  18983. $style['fgcolor'] = array(0,0,0); // default black
  18984. }
  18985. if (!isset($style['bgcolor'])) {
  18986. $style['bgcolor'] = false; // default transparent
  18987. }
  18988. if (!isset($style['border'])) {
  18989. $style['border'] = false;
  18990. }
  18991. // padding
  18992. if (!isset($style['padding'])) {
  18993. $style['padding'] = 0;
  18994. } elseif ($style['padding'] === 'auto') {
  18995. $style['padding'] = 4;
  18996. }
  18997. if (!isset($style['hpadding'])) {
  18998. $style['hpadding'] = $style['padding'];
  18999. } elseif ($style['hpadding'] === 'auto') {
  19000. $style['hpadding'] = 4;
  19001. }
  19002. if (!isset($style['vpadding'])) {
  19003. $style['vpadding'] = $style['padding'];
  19004. } elseif ($style['vpadding'] === 'auto') {
  19005. $style['vpadding'] = 4;
  19006. }
  19007. $hpad = (2 * $style['hpadding']);
  19008. $vpad = (2 * $style['vpadding']);
  19009. // cell (module) dimension
  19010. if (!isset($style['module_width'])) {
  19011. $style['module_width'] = 1; // width of a single module in points
  19012. }
  19013. if (!isset($style['module_height'])) {
  19014. $style['module_height'] = 1; // height of a single module in points
  19015. }
  19016. if ($x === '') {
  19017. $x = $this->x;
  19018. }
  19019. if ($y === '') {
  19020. $y = $this->y;
  19021. }
  19022. // check page for no-write regions and adapt page margins if necessary
  19023. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  19024. // number of barcode columns and rows
  19025. $rows = $arrcode['num_rows'];
  19026. $cols = $arrcode['num_cols'];
  19027. // module width and height
  19028. $mw = $style['module_width'];
  19029. $mh = $style['module_height'];
  19030. // get max dimensions
  19031. if ($this->rtl) {
  19032. $maxw = $x - $this->lMargin;
  19033. } else {
  19034. $maxw = $this->w - $this->rMargin - $x;
  19035. }
  19036. $maxh = ($this->h - $this->tMargin - $this->bMargin);
  19037. $ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
  19038. $ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
  19039. if (!$distort) {
  19040. if (($maxw * $ratioHW) > $maxh) {
  19041. $maxw = $maxh * $ratioWH;
  19042. }
  19043. if (($maxh * $ratioWH) > $maxw) {
  19044. $maxh = $maxw * $ratioHW;
  19045. }
  19046. }
  19047. // set maximum dimesions
  19048. if ($w > $maxw) {
  19049. $w = $maxw;
  19050. }
  19051. if ($h > $maxh) {
  19052. $h = $maxh;
  19053. }
  19054. // set dimensions
  19055. if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
  19056. $w = ($cols + $hpad) * ($mw / $this->k);
  19057. $h = ($rows + $vpad) * ($mh / $this->k);
  19058. } elseif (($w === '') OR ($w <= 0)) {
  19059. $w = $h * $ratioWH;
  19060. } elseif (($h === '') OR ($h <= 0)) {
  19061. $h = $w * $ratioHW;
  19062. }
  19063. // barcode size (excluding padding)
  19064. $bw = ($w * $cols) / ($cols + $hpad);
  19065. $bh = ($h * $rows) / ($rows + $vpad);
  19066. // dimension of single barcode cell unit
  19067. $cw = $bw / $cols;
  19068. $ch = $bh / $rows;
  19069. if (!$distort) {
  19070. if (($cw / $ch) > ($mw / $mh)) {
  19071. // correct horizontal distortion
  19072. $cw = $ch * $mw / $mh;
  19073. $bw = $cw * $cols;
  19074. $style['hpadding'] = ($w - $bw) / (2 * $cw);
  19075. } else {
  19076. // correct vertical distortion
  19077. $ch = $cw * $mh / $mw;
  19078. $bh = $ch * $rows;
  19079. $style['vpadding'] = ($h - $bh) / (2 * $ch);
  19080. }
  19081. }
  19082. // fit the barcode on available space
  19083. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  19084. // set alignment
  19085. $this->img_rb_y = $y + $h;
  19086. // set alignment
  19087. if ($this->rtl) {
  19088. if ($style['position'] == 'L') {
  19089. $xpos = $this->lMargin;
  19090. } elseif ($style['position'] == 'C') {
  19091. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  19092. } elseif ($style['position'] == 'R') {
  19093. $xpos = $this->w - $this->rMargin - $w;
  19094. } else {
  19095. $xpos = $x - $w;
  19096. }
  19097. $this->img_rb_x = $xpos;
  19098. } else {
  19099. if ($style['position'] == 'L') {
  19100. $xpos = $this->lMargin;
  19101. } elseif ($style['position'] == 'C') {
  19102. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  19103. } elseif ($style['position'] == 'R') {
  19104. $xpos = $this->w - $this->rMargin - $w;
  19105. } else {
  19106. $xpos = $x;
  19107. }
  19108. $this->img_rb_x = $xpos + $w;
  19109. }
  19110. $xstart = $xpos + ($style['hpadding'] * $cw);
  19111. $ystart = $y + ($style['vpadding'] * $ch);
  19112. // barcode is always printed in LTR direction
  19113. $tempRTL = $this->rtl;
  19114. $this->rtl = false;
  19115. // print background color
  19116. if ($style['bgcolor']) {
  19117. $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  19118. } elseif ($style['border']) {
  19119. $this->Rect($xpos, $y, $w, $h, 'D');
  19120. }
  19121. // set foreground color
  19122. $this->SetDrawColorArray($style['fgcolor']);
  19123. // print barcode cells
  19124. // for each row
  19125. for ($r = 0; $r < $rows; ++$r) {
  19126. $xr = $xstart;
  19127. // for each column
  19128. for ($c = 0; $c < $cols; ++$c) {
  19129. if ($arrcode['bcode'][$r][$c] == 1) {
  19130. // draw a single barcode cell
  19131. $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
  19132. }
  19133. $xr += $cw;
  19134. }
  19135. $ystart += $ch;
  19136. }
  19137. // restore original direction
  19138. $this->rtl = $tempRTL;
  19139. // restore previous settings
  19140. $this->setGraphicVars($gvars);
  19141. // set pointer to align the next text/objects
  19142. switch($align) {
  19143. case 'T':{
  19144. $this->y = $y;
  19145. $this->x = $this->img_rb_x;
  19146. break;
  19147. }
  19148. case 'M':{
  19149. $this->y = $y + round($h/2);
  19150. $this->x = $this->img_rb_x;
  19151. break;
  19152. }
  19153. case 'B':{
  19154. $this->y = $this->img_rb_y;
  19155. $this->x = $this->img_rb_x;
  19156. break;
  19157. }
  19158. case 'N':{
  19159. $this->SetY($this->img_rb_y);
  19160. break;
  19161. }
  19162. default:{
  19163. break;
  19164. }
  19165. }
  19166. $this->endlinex = $this->img_rb_x;
  19167. }
  19168. /**
  19169. * Returns an array containing current margins:
  19170. * <ul>
  19171. <li>$ret['left'] = left margin</li>
  19172. <li>$ret['right'] = right margin</li>
  19173. <li>$ret['top'] = top margin</li>
  19174. <li>$ret['bottom'] = bottom margin</li>
  19175. <li>$ret['header'] = header margin</li>
  19176. <li>$ret['footer'] = footer margin</li>
  19177. <li>$ret['cell'] = cell padding array</li>
  19178. <li>$ret['padding_left'] = cell left padding</li>
  19179. <li>$ret['padding_top'] = cell top padding</li>
  19180. <li>$ret['padding_right'] = cell right padding</li>
  19181. <li>$ret['padding_bottom'] = cell bottom padding</li>
  19182. * </ul>
  19183. * @return array containing all margins measures
  19184. * @public
  19185. * @since 3.2.000 (2008-06-23)
  19186. */
  19187. public function getMargins() {
  19188. $ret = array(
  19189. 'left' => $this->lMargin,
  19190. 'right' => $this->rMargin,
  19191. 'top' => $this->tMargin,
  19192. 'bottom' => $this->bMargin,
  19193. 'header' => $this->header_margin,
  19194. 'footer' => $this->footer_margin,
  19195. 'cell' => $this->cell_padding,
  19196. 'padding_left' => $this->cell_padding['L'],
  19197. 'padding_top' => $this->cell_padding['T'],
  19198. 'padding_right' => $this->cell_padding['R'],
  19199. 'padding_bottom' => $this->cell_padding['B']
  19200. );
  19201. return $ret;
  19202. }
  19203. /**
  19204. * Returns an array containing original margins:
  19205. * <ul>
  19206. <li>$ret['left'] = left margin</li>
  19207. <li>$ret['right'] = right margin</li>
  19208. * </ul>
  19209. * @return array containing all margins measures
  19210. * @public
  19211. * @since 4.0.012 (2008-07-24)
  19212. */
  19213. public function getOriginalMargins() {
  19214. $ret = array(
  19215. 'left' => $this->original_lMargin,
  19216. 'right' => $this->original_rMargin
  19217. );
  19218. return $ret;
  19219. }
  19220. /**
  19221. * Returns the current font size.
  19222. * @return current font size
  19223. * @public
  19224. * @since 3.2.000 (2008-06-23)
  19225. */
  19226. public function getFontSize() {
  19227. return $this->FontSize;
  19228. }
  19229. /**
  19230. * Returns the current font size in points unit.
  19231. * @return current font size in points unit
  19232. * @public
  19233. * @since 3.2.000 (2008-06-23)
  19234. */
  19235. public function getFontSizePt() {
  19236. return $this->FontSizePt;
  19237. }
  19238. /**
  19239. * Returns the current font family name.
  19240. * @return string current font family name
  19241. * @public
  19242. * @since 4.3.008 (2008-12-05)
  19243. */
  19244. public function getFontFamily() {
  19245. return $this->FontFamily;
  19246. }
  19247. /**
  19248. * Returns the current font style.
  19249. * @return string current font style
  19250. * @public
  19251. * @since 4.3.008 (2008-12-05)
  19252. */
  19253. public function getFontStyle() {
  19254. return $this->FontStyle;
  19255. }
  19256. /**
  19257. * Cleanup HTML code (requires HTML Tidy library).
  19258. * @param $html (string) htmlcode to fix
  19259. * @param $default_css (string) CSS commands to add
  19260. * @param $tagvs (array) parameters for setHtmlVSpace method
  19261. * @param $tidy_options (array) options for tidy_parse_string function
  19262. * @return string XHTML code cleaned up
  19263. * @author Nicola Asuni
  19264. * @public
  19265. * @since 5.9.017 (2010-11-16)
  19266. * @see setHtmlVSpace()
  19267. */
  19268. public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
  19269. // configure parameters for HTML Tidy
  19270. if ($tidy_options === '') {
  19271. $tidy_options = array (
  19272. 'clean' => 1,
  19273. 'drop-empty-paras' => 0,
  19274. 'drop-proprietary-attributes' => 1,
  19275. 'fix-backslash' => 1,
  19276. 'hide-comments' => 1,
  19277. 'join-styles' => 1,
  19278. 'lower-literals' => 1,
  19279. 'merge-divs' => 1,
  19280. 'merge-spans' => 1,
  19281. 'output-xhtml' => 1,
  19282. 'word-2000' => 1,
  19283. 'wrap' => 0,
  19284. 'output-bom' => 0,
  19285. //'char-encoding' => 'utf8',
  19286. //'input-encoding' => 'utf8',
  19287. //'output-encoding' => 'utf8'
  19288. );
  19289. }
  19290. // clean up the HTML code
  19291. $tidy = tidy_parse_string($html, $tidy_options);
  19292. // fix the HTML
  19293. $tidy->cleanRepair();
  19294. // get the CSS part
  19295. $tidy_head = tidy_get_head($tidy);
  19296. $css = $tidy_head->value;
  19297. $css = preg_replace('/<style([^>]+)>/ims', '<style>', $css);
  19298. $css = preg_replace('/<\/style>(.*)<style>/ims', "\n", $css);
  19299. $css = str_replace('/*<![CDATA[*/', '', $css);
  19300. $css = str_replace('/*]]>*/', '', $css);
  19301. preg_match('/<style>(.*)<\/style>/ims', $css, $matches);
  19302. if (isset($matches[1])) {
  19303. $css = strtolower($matches[1]);
  19304. } else {
  19305. $css = '';
  19306. }
  19307. // include default css
  19308. $css = '<style>'.$default_css.$css.'</style>';
  19309. // get the body part
  19310. $tidy_body = tidy_get_body($tidy);
  19311. $html = $tidy_body->value;
  19312. // fix some self-closing tags
  19313. $html = str_replace('<br>', '<br />', $html);
  19314. // remove some empty tag blocks
  19315. $html = preg_replace('/<div([^\>]*)><\/div>/', '', $html);
  19316. $html = preg_replace('/<p([^\>]*)><\/p>/', '', $html);
  19317. if ($tagvs !== '') {
  19318. // set vertical space for some XHTML tags
  19319. $this->setHtmlVSpace($tagvs);
  19320. }
  19321. // return the cleaned XHTML code + CSS
  19322. return $css.$html;
  19323. }
  19324. /**
  19325. * Extracts the CSS properties from a CSS string.
  19326. * @param $cssdata (string) string containing CSS definitions.
  19327. * @return An array where the keys are the CSS selectors and the values are the CSS properties.
  19328. * @author Nicola Asuni
  19329. * @since 5.1.000 (2010-05-25)
  19330. * @protected
  19331. */
  19332. protected function extractCSSproperties($cssdata) {
  19333. if (empty($cssdata)) {
  19334. return array();
  19335. }
  19336. // remove comments
  19337. $cssdata = preg_replace('/\/\*[^\*]*\*\//', '', $cssdata);
  19338. // remove newlines and multiple spaces
  19339. $cssdata = preg_replace('/[\s]+/', ' ', $cssdata);
  19340. // remove some spaces
  19341. $cssdata = preg_replace('/[\s]*([;:\{\}]{1})[\s]*/', '\\1', $cssdata);
  19342. // remove empty blocks
  19343. $cssdata = preg_replace('/([^\}\{]+)\{\}/', '', $cssdata);
  19344. // replace media type parenthesis
  19345. $cssdata = preg_replace('/@media[\s]+([^\{]*)\{/i', '@media \\1§', $cssdata);
  19346. $cssdata = preg_replace('/\}\}/si', '}§', $cssdata);
  19347. // trim string
  19348. $cssdata = trim($cssdata);
  19349. // find media blocks (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  19350. $cssblocks = array();
  19351. $matches = array();
  19352. if (preg_match_all('/@media[\s]+([^\§]*)§([^§]*)§/i', $cssdata, $matches) > 0) {
  19353. foreach ($matches[1] as $key => $type) {
  19354. $cssblocks[$type] = $matches[2][$key];
  19355. }
  19356. // remove media blocks
  19357. $cssdata = preg_replace('/@media[\s]+([^\§]*)§([^§]*)§/i', '', $cssdata);
  19358. }
  19359. // keep 'all' and 'print' media, other media types are discarded
  19360. if (isset($cssblocks['all']) AND !empty($cssblocks['all'])) {
  19361. $cssdata .= $cssblocks['all'];
  19362. }
  19363. if (isset($cssblocks['print']) AND !empty($cssblocks['print'])) {
  19364. $cssdata .= $cssblocks['print'];
  19365. }
  19366. // reset css blocks array
  19367. $cssblocks = array();
  19368. $matches = array();
  19369. // explode css data string into array
  19370. if (substr($cssdata, -1) == '}') {
  19371. // remove last parethesis
  19372. $cssdata = substr($cssdata, 0, -1);
  19373. }
  19374. $matches = explode('}', $cssdata);
  19375. foreach ($matches as $key => $block) {
  19376. // index 0 contains the CSS selector, index 1 contains CSS properties
  19377. $cssblocks[$key] = explode('{', $block);
  19378. if (!isset($cssblocks[$key][1])) {
  19379. // remove empty definitions
  19380. unset($cssblocks[$key]);
  19381. }
  19382. }
  19383. // split groups of selectors (comma-separated list of selectors)
  19384. foreach ($cssblocks as $key => $block) {
  19385. if (strpos($block[0], ',') > 0) {
  19386. $selectors = explode(',', $block[0]);
  19387. foreach ($selectors as $sel) {
  19388. $cssblocks[] = array(0 => trim($sel), 1 => $block[1]);
  19389. }
  19390. unset($cssblocks[$key]);
  19391. }
  19392. }
  19393. // covert array to selector => properties
  19394. $cssdata = array();
  19395. foreach ($cssblocks as $block) {
  19396. $selector = $block[0];
  19397. // calculate selector's specificity
  19398. $matches = array();
  19399. $a = 0; // the declaration is not from is a 'style' attribute
  19400. $b = intval(preg_match_all('/[\#]/', $selector, $matches)); // number of ID attributes
  19401. $c = intval(preg_match_all('/[\[\.]/', $selector, $matches)); // number of other attributes
  19402. $c += intval(preg_match_all('/[\:]link|visited|hover|active|focus|target|lang|enabled|disabled|checked|indeterminate|root|nth|first|last|only|empty|contains|not/i', $selector, $matches)); // number of pseudo-classes
  19403. $d = intval(preg_match_all('/[\>\+\~\s]{1}[a-zA-Z0-9]+/', ' '.$selector, $matches)); // number of element names
  19404. $d += intval(preg_match_all('/[\:][\:]/', $selector, $matches)); // number of pseudo-elements
  19405. $specificity = $a.$b.$c.$d;
  19406. // add specificity to the beginning of the selector
  19407. $cssdata[$specificity.' '.$selector] = $block[1];
  19408. }
  19409. // sort selectors alphabetically to account for specificity
  19410. ksort($cssdata, SORT_STRING);
  19411. // return array
  19412. return $cssdata;
  19413. }
  19414. /**
  19415. * Returns true if the CSS selector is valid for the selected HTML tag
  19416. * @param $dom (array) array of HTML tags and properties
  19417. * @param $key (int) key of the current HTML tag
  19418. * @param $selector (string) CSS selector string
  19419. * @return true if the selector is valid, false otherwise
  19420. * @protected
  19421. * @since 5.1.000 (2010-05-25)
  19422. */
  19423. protected function isValidCSSSelectorForTag($dom, $key, $selector) {
  19424. $valid = false; // value to be returned
  19425. $tag = $dom[$key]['value'];
  19426. $class = array();
  19427. if (isset($dom[$key]['attribute']['class']) AND !empty($dom[$key]['attribute']['class'])) {
  19428. $class = explode(' ', strtolower($dom[$key]['attribute']['class']));
  19429. }
  19430. $id = '';
  19431. if (isset($dom[$key]['attribute']['id']) AND !empty($dom[$key]['attribute']['id'])) {
  19432. $id = strtolower($dom[$key]['attribute']['id']);
  19433. }
  19434. $selector = preg_replace('/([\>\+\~\s]{1})([\.]{1})([^\>\+\~\s]*)/si', '\\1*.\\3', $selector);
  19435. $matches = array();
  19436. if (preg_match_all('/([\>\+\~\s]{1})([a-zA-Z0-9\*]+)([^\>\+\~\s]*)/si', $selector, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE) > 0) {
  19437. $parentop = array_pop($matches[1]);
  19438. $operator = $parentop[0];
  19439. $offset = $parentop[1];
  19440. $lasttag = array_pop($matches[2]);
  19441. $lasttag = strtolower(trim($lasttag[0]));
  19442. if (($lasttag == '*') OR ($lasttag == $tag)) {
  19443. // the last element on selector is our tag or 'any tag'
  19444. $attrib = array_pop($matches[3]);
  19445. $attrib = strtolower(trim($attrib[0]));
  19446. if (!empty($attrib)) {
  19447. // check if matches class, id, attribute, pseudo-class or pseudo-element
  19448. switch ($attrib{0}) {
  19449. case '.': { // class
  19450. if (in_array(substr($attrib, 1), $class)) {
  19451. $valid = true;
  19452. }
  19453. break;
  19454. }
  19455. case '#': { // ID
  19456. if (substr($attrib, 1) == $id) {
  19457. $valid = true;
  19458. }
  19459. break;
  19460. }
  19461. case '[': { // attribute
  19462. $attrmatch = array();
  19463. if (preg_match('/\[([a-zA-Z0-9]*)[\s]*([\~\^\$\*\|\=]*)[\s]*["]?([^"\]]*)["]?\]/i', $attrib, $attrmatch) > 0) {
  19464. $att = strtolower($attrmatch[1]);
  19465. $val = $attrmatch[3];
  19466. if (isset($dom[$key]['attribute'][$att])) {
  19467. switch ($attrmatch[2]) {
  19468. case '=': {
  19469. if ($dom[$key]['attribute'][$att] == $val) {
  19470. $valid = true;
  19471. }
  19472. break;
  19473. }
  19474. case '~=': {
  19475. if (in_array($val, explode(' ', $dom[$key]['attribute'][$att]))) {
  19476. $valid = true;
  19477. }
  19478. break;
  19479. }
  19480. case '^=': {
  19481. if ($val == substr($dom[$key]['attribute'][$att], 0, strlen($val))) {
  19482. $valid = true;
  19483. }
  19484. break;
  19485. }
  19486. case '$=': {
  19487. if ($val == substr($dom[$key]['attribute'][$att], -strlen($val))) {
  19488. $valid = true;
  19489. }
  19490. break;
  19491. }
  19492. case '*=': {
  19493. if (strpos($dom[$key]['attribute'][$att], $val) !== false) {
  19494. $valid = true;
  19495. }
  19496. break;
  19497. }
  19498. case '|=': {
  19499. if ($dom[$key]['attribute'][$att] == $val) {
  19500. $valid = true;
  19501. } elseif (preg_match('/'.$val.'[\-]{1}/i', $dom[$key]['attribute'][$att]) > 0) {
  19502. $valid = true;
  19503. }
  19504. break;
  19505. }
  19506. default: {
  19507. $valid = true;
  19508. }
  19509. }
  19510. }
  19511. }
  19512. break;
  19513. }
  19514. case ':': { // pseudo-class or pseudo-element
  19515. if ($attrib{1} == ':') { // pseudo-element
  19516. // pseudo-elements are not supported!
  19517. // (::first-line, ::first-letter, ::before, ::after)
  19518. } else { // pseudo-class
  19519. // pseudo-classes are not supported!
  19520. // (:root, :nth-child(n), :nth-last-child(n), :nth-of-type(n), :nth-last-of-type(n), :first-child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty, :link, :visited, :active, :hover, :focus, :target, :lang(fr), :enabled, :disabled, :checked)
  19521. }
  19522. break;
  19523. }
  19524. } // end of switch
  19525. } else {
  19526. $valid = true;
  19527. }
  19528. if ($valid AND ($offset > 0)) {
  19529. $valid = false;
  19530. // check remaining selector part
  19531. $selector = substr($selector, 0, $offset);
  19532. switch ($operator) {
  19533. case ' ': { // descendant of an element
  19534. while ($dom[$key]['parent'] > 0) {
  19535. if ($this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector)) {
  19536. $valid = true;
  19537. break;
  19538. } else {
  19539. $key = $dom[$key]['parent'];
  19540. }
  19541. }
  19542. break;
  19543. }
  19544. case '>': { // child of an element
  19545. $valid = $this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector);
  19546. break;
  19547. }
  19548. case '+': { // immediately preceded by an element
  19549. for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
  19550. if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
  19551. $valid = $this->isValidCSSSelectorForTag($dom, $i, $selector);
  19552. break;
  19553. }
  19554. }
  19555. break;
  19556. }
  19557. case '~': { // preceded by an element
  19558. for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
  19559. if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
  19560. if ($this->isValidCSSSelectorForTag($dom, $i, $selector)) {
  19561. break;
  19562. }
  19563. }
  19564. }
  19565. break;
  19566. }
  19567. }
  19568. }
  19569. }
  19570. }
  19571. return $valid;
  19572. }
  19573. /**
  19574. * Returns the styles array that apply for the selected HTML tag.
  19575. * @param $dom (array) array of HTML tags and properties
  19576. * @param $key (int) key of the current HTML tag
  19577. * @param $css (array) array of CSS properties
  19578. * @return array containing CSS properties
  19579. * @protected
  19580. * @since 5.1.000 (2010-05-25)
  19581. */
  19582. protected function getCSSdataArray($dom, $key, $css) {
  19583. $cssarray = array(); // style to be returned
  19584. // get parent CSS selectors
  19585. $selectors = array();
  19586. if (isset($dom[($dom[$key]['parent'])]['csssel'])) {
  19587. $selectors = $dom[($dom[$key]['parent'])]['csssel'];
  19588. }
  19589. // get all styles that apply
  19590. foreach($css as $selector => $style) {
  19591. $pos = strpos($selector, ' ');
  19592. // get specificity
  19593. $specificity = substr($selector, 0, $pos);
  19594. // remove specificity
  19595. $selector = substr($selector, $pos);
  19596. // check if this selector apply to current tag
  19597. if ($this->isValidCSSSelectorForTag($dom, $key, $selector)) {
  19598. if (!in_array($selector, $selectors)) {
  19599. // add style if not already added on parent selector
  19600. $cssarray[] = array('k' => $selector, 's' => $specificity, 'c' => $style);
  19601. $selectors[] = $selector;
  19602. }
  19603. }
  19604. }
  19605. if (isset($dom[$key]['attribute']['style'])) {
  19606. // attach inline style (latest properties have high priority)
  19607. $cssarray[] = array('k' => '', 's' => '1000', 'c' => $dom[$key]['attribute']['style']);
  19608. }
  19609. // order the css array to account for specificity
  19610. $cssordered = array();
  19611. foreach ($cssarray as $key => $val) {
  19612. $skey = sprintf('%04d', $key);
  19613. $cssordered[$val['s'].'_'.$skey] = $val;
  19614. }
  19615. // sort selectors alphabetically to account for specificity
  19616. ksort($cssordered, SORT_STRING);
  19617. return array($selectors, $cssordered);
  19618. }
  19619. /**
  19620. * Compact CSS data array into single string.
  19621. * @param $css (array) array of CSS properties
  19622. * @return string containing merged CSS properties
  19623. * @protected
  19624. * @since 5.9.070 (2011-04-19)
  19625. */
  19626. protected function getTagStyleFromCSSarray($css) {
  19627. $tagstyle = ''; // value to be returned
  19628. foreach ($css as $style) {
  19629. // split single css commands
  19630. $csscmds = explode(';', $style['c']);
  19631. foreach ($csscmds as $cmd) {
  19632. if (!empty($cmd)) {
  19633. $pos = strpos($cmd, ':');
  19634. if ($pos !== false) {
  19635. $cmd = substr($cmd, 0, ($pos + 1));
  19636. if (strpos($tagstyle, $cmd) !== false) {
  19637. // remove duplicate commands (last commands have high priority)
  19638. $tagstyle = preg_replace('/'.$cmd.'[^;]+/i', '', $tagstyle);
  19639. }
  19640. }
  19641. }
  19642. }
  19643. $tagstyle .= ';'.$style['c'];
  19644. }
  19645. // remove multiple semicolons
  19646. $tagstyle = preg_replace('/[;]+/', ';', $tagstyle);
  19647. return $tagstyle;
  19648. }
  19649. /**
  19650. * Returns the border width from CSS property
  19651. * @param $width (string) border width
  19652. * @return int with in user units
  19653. * @protected
  19654. * @since 5.7.000 (2010-08-02)
  19655. */
  19656. protected function getCSSBorderWidth($width) {
  19657. if ($width == 'thin') {
  19658. $width = (2 / $this->k);
  19659. } elseif ($width == 'medium') {
  19660. $width = (4 / $this->k);
  19661. } elseif ($width == 'thick') {
  19662. $width = (6 / $this->k);
  19663. } else {
  19664. $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
  19665. }
  19666. return $width;
  19667. }
  19668. /**
  19669. * Returns the border dash style from CSS property
  19670. * @param $style (string) border style to convert
  19671. * @return int sash style (return -1 in case of none or hidden border)
  19672. * @protected
  19673. * @since 5.7.000 (2010-08-02)
  19674. */
  19675. protected function getCSSBorderDashStyle($style) {
  19676. switch (strtolower($style)) {
  19677. case 'none':
  19678. case 'hidden': {
  19679. $dash = -1;
  19680. break;
  19681. }
  19682. case 'dotted': {
  19683. $dash = 1;
  19684. break;
  19685. }
  19686. case 'dashed': {
  19687. $dash = 3;
  19688. break;
  19689. }
  19690. case 'double':
  19691. case 'groove':
  19692. case 'ridge':
  19693. case 'inset':
  19694. case 'outset':
  19695. case 'solid':
  19696. default: {
  19697. $dash = 0;
  19698. break;
  19699. }
  19700. }
  19701. return $dash;
  19702. }
  19703. /**
  19704. * Returns the border style array from CSS border properties
  19705. * @param $cssborder (string) border properties
  19706. * @return array containing border properties
  19707. * @protected
  19708. * @since 5.7.000 (2010-08-02)
  19709. */
  19710. protected function getCSSBorderStyle($cssborder) {
  19711. $bprop = preg_split('/[\s]+/', trim($cssborder));
  19712. $border = array(); // value to be returned
  19713. switch (count($bprop)) {
  19714. case 3: {
  19715. $width = $bprop[0];
  19716. $style = $bprop[1];
  19717. $color = $bprop[2];
  19718. break;
  19719. }
  19720. case 2: {
  19721. $width = 'medium';
  19722. $style = $bprop[0];
  19723. $color = $bprop[1];
  19724. break;
  19725. }
  19726. case 1: {
  19727. $width = 'medium';
  19728. $style = $bprop[0];
  19729. $color = 'black';
  19730. break;
  19731. }
  19732. default: {
  19733. $width = 'medium';
  19734. $style = 'solid';
  19735. $color = 'black';
  19736. break;
  19737. }
  19738. }
  19739. if ($style == 'none') {
  19740. return array();
  19741. }
  19742. $border['cap'] = 'square';
  19743. $border['join'] = 'miter';
  19744. $border['dash'] = $this->getCSSBorderDashStyle($style);
  19745. if ($border['dash'] < 0) {
  19746. return array();
  19747. }
  19748. $border['width'] = $this->getCSSBorderWidth($width);
  19749. $border['color'] = $this->convertHTMLColorToDec($color);
  19750. return $border;
  19751. }
  19752. /**
  19753. * Get the internal Cell padding from CSS attribute.
  19754. * @param $csspadding (string) padding properties
  19755. * @param $width (float) width of the containing element
  19756. * @return array of cell paddings
  19757. * @public
  19758. * @since 5.9.000 (2010-10-04)
  19759. */
  19760. public function getCSSPadding($csspadding, $width=0) {
  19761. $padding = preg_split('/[\s]+/', trim($csspadding));
  19762. $cell_padding = array(); // value to be returned
  19763. switch (count($padding)) {
  19764. case 4: {
  19765. $cell_padding['T'] = $padding[0];
  19766. $cell_padding['R'] = $padding[1];
  19767. $cell_padding['B'] = $padding[2];
  19768. $cell_padding['L'] = $padding[3];
  19769. break;
  19770. }
  19771. case 3: {
  19772. $cell_padding['T'] = $padding[0];
  19773. $cell_padding['R'] = $padding[1];
  19774. $cell_padding['B'] = $padding[2];
  19775. $cell_padding['L'] = $padding[1];
  19776. break;
  19777. }
  19778. case 2: {
  19779. $cell_padding['T'] = $padding[0];
  19780. $cell_padding['R'] = $padding[1];
  19781. $cell_padding['B'] = $padding[0];
  19782. $cell_padding['L'] = $padding[1];
  19783. break;
  19784. }
  19785. case 1: {
  19786. $cell_padding['T'] = $padding[0];
  19787. $cell_padding['R'] = $padding[0];
  19788. $cell_padding['B'] = $padding[0];
  19789. $cell_padding['L'] = $padding[0];
  19790. break;
  19791. }
  19792. default: {
  19793. return $this->cell_padding;
  19794. }
  19795. }
  19796. if ($width == 0) {
  19797. $width = $this->w - $this->lMargin - $this->rMargin;
  19798. }
  19799. $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
  19800. $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
  19801. $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
  19802. $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
  19803. return $cell_padding;
  19804. }
  19805. /**
  19806. * Get the internal Cell margin from CSS attribute.
  19807. * @param $cssmargin (string) margin properties
  19808. * @param $width (float) width of the containing element
  19809. * @return array of cell margins
  19810. * @public
  19811. * @since 5.9.000 (2010-10-04)
  19812. */
  19813. public function getCSSMargin($cssmargin, $width=0) {
  19814. $margin = preg_split('/[\s]+/', trim($cssmargin));
  19815. $cell_margin = array(); // value to be returned
  19816. switch (count($margin)) {
  19817. case 4: {
  19818. $cell_margin['T'] = $margin[0];
  19819. $cell_margin['R'] = $margin[1];
  19820. $cell_margin['B'] = $margin[2];
  19821. $cell_margin['L'] = $margin[3];
  19822. break;
  19823. }
  19824. case 3: {
  19825. $cell_margin['T'] = $margin[0];
  19826. $cell_margin['R'] = $margin[1];
  19827. $cell_margin['B'] = $margin[2];
  19828. $cell_margin['L'] = $margin[1];
  19829. break;
  19830. }
  19831. case 2: {
  19832. $cell_margin['T'] = $margin[0];
  19833. $cell_margin['R'] = $margin[1];
  19834. $cell_margin['B'] = $margin[0];
  19835. $cell_margin['L'] = $margin[1];
  19836. break;
  19837. }
  19838. case 1: {
  19839. $cell_margin['T'] = $margin[0];
  19840. $cell_margin['R'] = $margin[0];
  19841. $cell_margin['B'] = $margin[0];
  19842. $cell_margin['L'] = $margin[0];
  19843. break;
  19844. }
  19845. default: {
  19846. return $this->cell_margin;
  19847. }
  19848. }
  19849. if ($width == 0) {
  19850. $width = $this->w - $this->lMargin - $this->rMargin;
  19851. }
  19852. $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
  19853. $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
  19854. $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
  19855. $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
  19856. return $cell_margin;
  19857. }
  19858. /**
  19859. * Get the border-spacing from CSS attribute.
  19860. * @param $cssbspace (string) border-spacing CSS properties
  19861. * @param $width (float) width of the containing element
  19862. * @return array of border spacings
  19863. * @public
  19864. * @since 5.9.010 (2010-10-27)
  19865. */
  19866. public function getCSSBorderMargin($cssbspace, $width=0) {
  19867. $space = preg_split('/[\s]+/', trim($cssbspace));
  19868. $border_spacing = array(); // value to be returned
  19869. switch (count($space)) {
  19870. case 2: {
  19871. $border_spacing['H'] = $space[0];
  19872. $border_spacing['V'] = $space[1];
  19873. break;
  19874. }
  19875. case 1: {
  19876. $border_spacing['H'] = $space[0];
  19877. $border_spacing['V'] = $space[0];
  19878. break;
  19879. }
  19880. default: {
  19881. return array('H' => 0, 'V' => 0);
  19882. }
  19883. }
  19884. if ($width == 0) {
  19885. $width = $this->w - $this->lMargin - $this->rMargin;
  19886. }
  19887. $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
  19888. $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
  19889. return $border_spacing;
  19890. }
  19891. /**
  19892. * Returns the letter-spacing value from CSS value
  19893. * @param $spacing (string) letter-spacing value
  19894. * @param $parent (float) font spacing (tracking/kerning) value of the parent element
  19895. * @return float quantity to increases or decreases the space between characters in a text.
  19896. * @protected
  19897. * @since 5.9.000 (2010-10-02)
  19898. */
  19899. protected function getCSSFontSpacing($spacing, $parent=0) {
  19900. $val = 0; // value to be returned
  19901. $spacing = trim($spacing);
  19902. switch ($spacing) {
  19903. case 'normal': {
  19904. $val = 0;
  19905. break;
  19906. }
  19907. case 'inherit': {
  19908. if ($parent == 'normal') {
  19909. $val = 0;
  19910. } else {
  19911. $val = $parent;
  19912. }
  19913. break;
  19914. }
  19915. default: {
  19916. $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
  19917. }
  19918. }
  19919. return $val;
  19920. }
  19921. /**
  19922. * Returns the percentage of font stretching from CSS value
  19923. * @param $stretch (string) stretch mode
  19924. * @param $parent (float) stretch value of the parent element
  19925. * @return float font stretching percentage
  19926. * @protected
  19927. * @since 5.9.000 (2010-10-02)
  19928. */
  19929. protected function getCSSFontStretching($stretch, $parent=100) {
  19930. $val = 100; // value to be returned
  19931. $stretch = trim($stretch);
  19932. switch ($stretch) {
  19933. case 'ultra-condensed': {
  19934. $val = 40;
  19935. break;
  19936. }
  19937. case 'extra-condensed': {
  19938. $val = 55;
  19939. break;
  19940. }
  19941. case 'condensed': {
  19942. $val = 70;
  19943. break;
  19944. }
  19945. case 'semi-condensed': {
  19946. $val = 85;
  19947. break;
  19948. }
  19949. case 'normal': {
  19950. $val = 100;
  19951. break;
  19952. }
  19953. case 'semi-expanded': {
  19954. $val = 115;
  19955. break;
  19956. }
  19957. case 'expanded': {
  19958. $val = 130;
  19959. break;
  19960. }
  19961. case 'extra-expanded': {
  19962. $val = 145;
  19963. break;
  19964. }
  19965. case 'ultra-expanded': {
  19966. $val = 160;
  19967. break;
  19968. }
  19969. case 'wider': {
  19970. $val = $parent + 10;
  19971. break;
  19972. }
  19973. case 'narrower': {
  19974. $val = $parent - 10;
  19975. break;
  19976. }
  19977. case 'inherit': {
  19978. if ($parent == 'normal') {
  19979. $val = 100;
  19980. } else {
  19981. $val = $parent;
  19982. }
  19983. break;
  19984. }
  19985. default: {
  19986. $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
  19987. }
  19988. }
  19989. return $val;
  19990. }
  19991. /**
  19992. * Returns the HTML DOM array.
  19993. * @param $html (string) html code
  19994. * @return array
  19995. * @protected
  19996. * @since 3.2.000 (2008-06-20)
  19997. */
  19998. protected function getHtmlDomArray($html) {
  19999. // array of CSS styles ( selector => properties).
  20000. $css = array();
  20001. // get CSS array defined at previous call
  20002. $matches = array();
  20003. if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
  20004. if (isset($matches[1][0])) {
  20005. $css = array_merge($css, unserialize($this->unhtmlentities($matches[1][0])));
  20006. }
  20007. $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
  20008. }
  20009. // extract external CSS files
  20010. $matches = array();
  20011. if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
  20012. foreach ($matches[1] as $key => $link) {
  20013. $type = array();
  20014. if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
  20015. $type = array();
  20016. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
  20017. // get 'all' and 'print' media, other media types are discarded
  20018. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  20019. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  20020. $type = array();
  20021. if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
  20022. // read CSS data file
  20023. $cssdata = file_get_contents(trim($type[1]));
  20024. $css = array_merge($css, $this->extractCSSproperties($cssdata));
  20025. }
  20026. }
  20027. }
  20028. }
  20029. }
  20030. // extract style tags
  20031. $matches = array();
  20032. if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
  20033. foreach ($matches[1] as $key => $media) {
  20034. $type = array();
  20035. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
  20036. // get 'all' and 'print' media, other media types are discarded
  20037. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  20038. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  20039. $cssdata = $matches[2][$key];
  20040. $css = array_merge($css, $this->extractCSSproperties($cssdata));
  20041. }
  20042. }
  20043. }
  20044. // create a special tag to contain the CSS array (used for table content)
  20045. $csstagarray = '<cssarray>'.htmlentities(serialize($css)).'</cssarray>';
  20046. // remove head and style blocks
  20047. $html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
  20048. $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
  20049. // define block tags
  20050. $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
  20051. // define self-closing tags
  20052. $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
  20053. // remove all unsupported tags (the line below lists all supported tags)
  20054. $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>');
  20055. //replace some blank characters
  20056. $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
  20057. $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);
  20058. $html = preg_replace('@(\r\n|\r)@', "\n", $html);
  20059. $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
  20060. $html = strtr($html, $repTable);
  20061. $offset = 0;
  20062. while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
  20063. $html_a = substr($html, 0, $offset);
  20064. $html_b = substr($html, $offset, ($pos - $offset + 6));
  20065. while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
  20066. // preserve newlines on <pre> tag
  20067. $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
  20068. }
  20069. while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
  20070. // preserve spaces on <pre> tag
  20071. $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
  20072. }
  20073. $html = $html_a.$html_b.substr($html, $pos + 6);
  20074. $offset = strlen($html_a.$html_b);
  20075. }
  20076. $offset = 0;
  20077. while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
  20078. $html_a = substr($html, 0, $offset);
  20079. $html_b = substr($html, $offset, ($pos - $offset + 11));
  20080. while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
  20081. // preserve newlines on <textarea> tag
  20082. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
  20083. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
  20084. }
  20085. $html = $html_a.$html_b.substr($html, $pos + 11);
  20086. $offset = strlen($html_a.$html_b);
  20087. }
  20088. $html = preg_replace('/([\s]*)<option/si', '<option', $html);
  20089. $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
  20090. $offset = 0;
  20091. while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
  20092. $html_a = substr($html, 0, $offset);
  20093. $html_b = substr($html, $offset, ($pos - $offset + 9));
  20094. while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
  20095. $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
  20096. $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
  20097. }
  20098. $html = $html_a.$html_b.substr($html, $pos + 9);
  20099. $offset = strlen($html_a.$html_b);
  20100. }
  20101. if (preg_match("'</select'si", $html)) {
  20102. $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
  20103. $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
  20104. }
  20105. $html = str_replace("\n", ' ', $html);
  20106. // restore textarea newlines
  20107. $html = str_replace('<TBR>', "\n", $html);
  20108. // remove extra spaces from code
  20109. $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
  20110. $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
  20111. $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
  20112. $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
  20113. $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);
  20114. $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
  20115. $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
  20116. $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
  20117. $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
  20118. $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
  20119. $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
  20120. $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
  20121. $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
  20122. $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
  20123. $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
  20124. $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
  20125. $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
  20126. // trim string
  20127. $html = $this->stringTrim($html);
  20128. // fix first image tag alignment
  20129. $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
  20130. // pattern for generic tag
  20131. $tagpattern = '/(<[^>]+>)/';
  20132. // explodes the string
  20133. $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  20134. // count elements
  20135. $maxel = count($a);
  20136. $elkey = 0;
  20137. $key = 0;
  20138. // create an array of elements
  20139. $dom = array();
  20140. $dom[$key] = array();
  20141. // set inheritable properties fot the first void element
  20142. // 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
  20143. $dom[$key]['tag'] = false;
  20144. $dom[$key]['block'] = false;
  20145. $dom[$key]['value'] = '';
  20146. $dom[$key]['parent'] = 0;
  20147. $dom[$key]['hide'] = false;
  20148. $dom[$key]['fontname'] = $this->FontFamily;
  20149. $dom[$key]['fontstyle'] = $this->FontStyle;
  20150. $dom[$key]['fontsize'] = $this->FontSizePt;
  20151. $dom[$key]['font-stretch'] = $this->font_stretching;
  20152. $dom[$key]['letter-spacing'] = $this->font_spacing;
  20153. $dom[$key]['stroke'] = $this->textstrokewidth;
  20154. $dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
  20155. $dom[$key]['clip'] = ($this->textrendermode > 3);
  20156. $dom[$key]['line-height'] = $this->cell_height_ratio;
  20157. $dom[$key]['bgcolor'] = false;
  20158. $dom[$key]['fgcolor'] = $this->fgcolor; // color
  20159. $dom[$key]['strokecolor'] = $this->strokecolor;
  20160. $dom[$key]['align'] = '';
  20161. $dom[$key]['listtype'] = '';
  20162. $dom[$key]['text-indent'] = 0;
  20163. $dom[$key]['border'] = array();
  20164. $dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
  20165. $thead = false; // true when we are inside the THEAD tag
  20166. ++$key;
  20167. $level = array();
  20168. array_push($level, 0); // root
  20169. while ($elkey < $maxel) {
  20170. $dom[$key] = array();
  20171. $element = $a[$elkey];
  20172. $dom[$key]['elkey'] = $elkey;
  20173. if (preg_match($tagpattern, $element)) {
  20174. // html tag
  20175. $element = substr($element, 1, -1);
  20176. // get tag name
  20177. preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
  20178. $tagname = strtolower($tag[1]);
  20179. // check if we are inside a table header
  20180. if ($tagname == 'thead') {
  20181. if ($element{0} == '/') {
  20182. $thead = false;
  20183. } else {
  20184. $thead = true;
  20185. }
  20186. ++$elkey;
  20187. continue;
  20188. }
  20189. $dom[$key]['tag'] = true;
  20190. $dom[$key]['value'] = $tagname;
  20191. if (in_array($dom[$key]['value'], $blocktags)) {
  20192. $dom[$key]['block'] = true;
  20193. } else {
  20194. $dom[$key]['block'] = false;
  20195. }
  20196. if ($element{0} == '/') {
  20197. // *** closing html tag
  20198. $dom[$key]['opening'] = false;
  20199. $dom[$key]['parent'] = end($level);
  20200. array_pop($level);
  20201. $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
  20202. $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
  20203. $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
  20204. $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
  20205. $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
  20206. $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
  20207. $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
  20208. $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
  20209. $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
  20210. $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
  20211. $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
  20212. $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
  20213. $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
  20214. $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
  20215. $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
  20216. if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
  20217. $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
  20218. }
  20219. // set the number of columns in table tag
  20220. if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
  20221. $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
  20222. }
  20223. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  20224. $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
  20225. for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
  20226. $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
  20227. }
  20228. $key = $i;
  20229. // mark nested tables
  20230. $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
  20231. // remove thead sections from nested tables
  20232. $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
  20233. $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
  20234. }
  20235. // store header rows on a new table
  20236. if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
  20237. if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
  20238. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
  20239. }
  20240. for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
  20241. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
  20242. }
  20243. if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
  20244. $dom[($dom[$key]['parent'])]['attribute'] = array();
  20245. }
  20246. // header elements must be always contained in a single page
  20247. $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
  20248. }
  20249. if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
  20250. // remove the nobr attributes from the table header
  20251. $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
  20252. $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
  20253. }
  20254. } else {
  20255. // *** opening or self-closing html tag
  20256. $dom[$key]['opening'] = true;
  20257. $dom[$key]['parent'] = end($level);
  20258. if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
  20259. // self-closing tag
  20260. $dom[$key]['self'] = true;
  20261. } else {
  20262. // opening tag
  20263. array_push($level, $key);
  20264. $dom[$key]['self'] = false;
  20265. }
  20266. // copy some values from parent
  20267. $parentkey = 0;
  20268. if ($key > 0) {
  20269. $parentkey = $dom[$key]['parent'];
  20270. $dom[$key]['hide'] = $dom[$parentkey]['hide'];
  20271. $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
  20272. $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
  20273. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
  20274. $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
  20275. $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
  20276. $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
  20277. $dom[$key]['fill'] = $dom[$parentkey]['fill'];
  20278. $dom[$key]['clip'] = $dom[$parentkey]['clip'];
  20279. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  20280. $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
  20281. $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
  20282. $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
  20283. $dom[$key]['align'] = $dom[$parentkey]['align'];
  20284. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  20285. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  20286. $dom[$key]['border'] = array();
  20287. $dom[$key]['dir'] = $dom[$parentkey]['dir'];
  20288. }
  20289. // get attributes
  20290. preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
  20291. $dom[$key]['attribute'] = array(); // reset attribute array
  20292. while (list($id, $name) = each($attr_array[1])) {
  20293. $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
  20294. }
  20295. if (!empty($css)) {
  20296. // merge CSS style to current style
  20297. list($dom[$key]['csssel'], $dom[$key]['cssdata']) = $this->getCSSdataArray($dom, $key, $css);
  20298. $dom[$key]['attribute']['style'] = $this->getTagStyleFromCSSarray($dom[$key]['cssdata']);
  20299. }
  20300. // split style attributes
  20301. if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
  20302. // get style attributes
  20303. preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  20304. $dom[$key]['style'] = array(); // reset style attribute array
  20305. while (list($id, $name) = each($style_array[1])) {
  20306. // in case of duplicate attribute the last replace the previous
  20307. $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
  20308. }
  20309. // --- get some style attributes ---
  20310. // text direction
  20311. if (isset($dom[$key]['style']['direction'])) {
  20312. $dom[$key]['dir'] = $dom[$key]['style']['direction'];
  20313. }
  20314. // display
  20315. if (isset($dom[$key]['style']['display'])) {
  20316. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
  20317. }
  20318. // font family
  20319. if (isset($dom[$key]['style']['font-family'])) {
  20320. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
  20321. }
  20322. // list-style-type
  20323. if (isset($dom[$key]['style']['list-style-type'])) {
  20324. $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
  20325. if ($dom[$key]['listtype'] == 'inherit') {
  20326. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  20327. }
  20328. }
  20329. // text-indent
  20330. if (isset($dom[$key]['style']['text-indent'])) {
  20331. $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
  20332. if ($dom[$key]['text-indent'] == 'inherit') {
  20333. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  20334. }
  20335. }
  20336. // font size
  20337. if (isset($dom[$key]['style']['font-size'])) {
  20338. $fsize = trim($dom[$key]['style']['font-size']);
  20339. switch ($fsize) {
  20340. // absolute-size
  20341. case 'xx-small': {
  20342. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
  20343. break;
  20344. }
  20345. case 'x-small': {
  20346. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
  20347. break;
  20348. }
  20349. case 'small': {
  20350. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
  20351. break;
  20352. }
  20353. case 'medium': {
  20354. $dom[$key]['fontsize'] = $dom[0]['fontsize'];
  20355. break;
  20356. }
  20357. case 'large': {
  20358. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
  20359. break;
  20360. }
  20361. case 'x-large': {
  20362. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
  20363. break;
  20364. }
  20365. case 'xx-large': {
  20366. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
  20367. break;
  20368. }
  20369. // relative-size
  20370. case 'smaller': {
  20371. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
  20372. break;
  20373. }
  20374. case 'larger': {
  20375. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
  20376. break;
  20377. }
  20378. default: {
  20379. $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
  20380. }
  20381. }
  20382. }
  20383. // font-stretch
  20384. if (isset($dom[$key]['style']['font-stretch'])) {
  20385. $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
  20386. }
  20387. // letter-spacing
  20388. if (isset($dom[$key]['style']['letter-spacing'])) {
  20389. $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
  20390. }
  20391. // line-height
  20392. if (isset($dom[$key]['style']['line-height'])) {
  20393. $lineheight = trim($dom[$key]['style']['line-height']);
  20394. switch ($lineheight) {
  20395. // A normal line height. This is default
  20396. case 'normal': {
  20397. $dom[$key]['line-height'] = $dom[0]['line-height'];
  20398. break;
  20399. }
  20400. default: {
  20401. if (is_numeric($lineheight)) {
  20402. $lineheight = $lineheight * 100;
  20403. }
  20404. $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
  20405. }
  20406. }
  20407. }
  20408. // font style
  20409. if (isset($dom[$key]['style']['font-weight'])) {
  20410. if (strtolower($dom[$key]['style']['font-weight']{0}) == 'n') {
  20411. if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
  20412. $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
  20413. }
  20414. } elseif (strtolower($dom[$key]['style']['font-weight']{0}) == 'b') {
  20415. $dom[$key]['fontstyle'] .= 'B';
  20416. }
  20417. }
  20418. if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
  20419. $dom[$key]['fontstyle'] .= 'I';
  20420. }
  20421. // font color
  20422. if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
  20423. $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
  20424. } elseif ($dom[$key]['value'] == 'a') {
  20425. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  20426. }
  20427. // background color
  20428. if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
  20429. $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
  20430. }
  20431. // text-decoration
  20432. if (isset($dom[$key]['style']['text-decoration'])) {
  20433. $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
  20434. foreach ($decors as $dec) {
  20435. $dec = trim($dec);
  20436. if (!$this->empty_string($dec)) {
  20437. if ($dec{0} == 'u') {
  20438. // underline
  20439. $dom[$key]['fontstyle'] .= 'U';
  20440. } elseif ($dec{0} == 'l') {
  20441. // line-trough
  20442. $dom[$key]['fontstyle'] .= 'D';
  20443. } elseif ($dec{0} == 'o') {
  20444. // overline
  20445. $dom[$key]['fontstyle'] .= 'O';
  20446. }
  20447. }
  20448. }
  20449. } elseif ($dom[$key]['value'] == 'a') {
  20450. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  20451. }
  20452. // check for width attribute
  20453. if (isset($dom[$key]['style']['width'])) {
  20454. $dom[$key]['width'] = $dom[$key]['style']['width'];
  20455. }
  20456. // check for height attribute
  20457. if (isset($dom[$key]['style']['height'])) {
  20458. $dom[$key]['height'] = $dom[$key]['style']['height'];
  20459. }
  20460. // check for text alignment
  20461. if (isset($dom[$key]['style']['text-align'])) {
  20462. $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
  20463. }
  20464. // check for CSS border properties
  20465. if (isset($dom[$key]['style']['border'])) {
  20466. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
  20467. if (!empty($borderstyle)) {
  20468. $dom[$key]['border']['LTRB'] = $borderstyle;
  20469. }
  20470. }
  20471. if (isset($dom[$key]['style']['border-color'])) {
  20472. $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
  20473. if (isset($brd_colors[3])) {
  20474. $dom[$key]['border']['L']['color'] = $this->convertHTMLColorToDec($brd_colors[3]);
  20475. }
  20476. if (isset($brd_colors[1])) {
  20477. $dom[$key]['border']['R']['color'] = $this->convertHTMLColorToDec($brd_colors[1]);
  20478. }
  20479. if (isset($brd_colors[0])) {
  20480. $dom[$key]['border']['T']['color'] = $this->convertHTMLColorToDec($brd_colors[0]);
  20481. }
  20482. if (isset($brd_colors[2])) {
  20483. $dom[$key]['border']['B']['color'] = $this->convertHTMLColorToDec($brd_colors[2]);
  20484. }
  20485. }
  20486. if (isset($dom[$key]['style']['border-width'])) {
  20487. $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
  20488. if (isset($brd_widths[3])) {
  20489. $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
  20490. }
  20491. if (isset($brd_widths[1])) {
  20492. $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
  20493. }
  20494. if (isset($brd_widths[0])) {
  20495. $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
  20496. }
  20497. if (isset($brd_widths[2])) {
  20498. $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
  20499. }
  20500. }
  20501. if (isset($dom[$key]['style']['border-style'])) {
  20502. $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
  20503. if (isset($brd_styles[3])) {
  20504. $dom[$key]['border']['L']['cap'] = 'square';
  20505. $dom[$key]['border']['L']['join'] = 'miter';
  20506. $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
  20507. if ($dom[$key]['border']['L']['dash'] < 0) {
  20508. $dom[$key]['border']['L'] = array();
  20509. }
  20510. }
  20511. if (isset($brd_styles[1])) {
  20512. $dom[$key]['border']['R']['cap'] = 'square';
  20513. $dom[$key]['border']['R']['join'] = 'miter';
  20514. $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
  20515. if ($dom[$key]['border']['R']['dash'] < 0) {
  20516. $dom[$key]['border']['R'] = array();
  20517. }
  20518. }
  20519. if (isset($brd_styles[0])) {
  20520. $dom[$key]['border']['T']['cap'] = 'square';
  20521. $dom[$key]['border']['T']['join'] = 'miter';
  20522. $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
  20523. if ($dom[$key]['border']['T']['dash'] < 0) {
  20524. $dom[$key]['border']['T'] = array();
  20525. }
  20526. }
  20527. if (isset($brd_styles[2])) {
  20528. $dom[$key]['border']['B']['cap'] = 'square';
  20529. $dom[$key]['border']['B']['join'] = 'miter';
  20530. $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
  20531. if ($dom[$key]['border']['B']['dash'] < 0) {
  20532. $dom[$key]['border']['B'] = array();
  20533. }
  20534. }
  20535. }
  20536. $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
  20537. foreach ($cellside as $bsk => $bsv) {
  20538. if (isset($dom[$key]['style']['border-'.$bsv])) {
  20539. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
  20540. if (!empty($borderstyle)) {
  20541. $dom[$key]['border'][$bsk] = $borderstyle;
  20542. }
  20543. }
  20544. if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
  20545. $dom[$key]['border'][$bsk]['color'] = $this->convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color']);
  20546. }
  20547. if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
  20548. $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
  20549. }
  20550. if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
  20551. $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
  20552. if ($dom[$key]['border'][$bsk]['dash'] < 0) {
  20553. $dom[$key]['border'][$bsk] = array();
  20554. }
  20555. }
  20556. }
  20557. // check for CSS padding properties
  20558. if (isset($dom[$key]['style']['padding'])) {
  20559. $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
  20560. } else {
  20561. $dom[$key]['padding'] = $this->cell_padding;
  20562. }
  20563. foreach ($cellside as $psk => $psv) {
  20564. if (isset($dom[$key]['style']['padding-'.$psv])) {
  20565. $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
  20566. }
  20567. }
  20568. // check for CSS margin properties
  20569. if (isset($dom[$key]['style']['margin'])) {
  20570. $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
  20571. } else {
  20572. $dom[$key]['margin'] = $this->cell_margin;
  20573. }
  20574. foreach ($cellside as $psk => $psv) {
  20575. if (isset($dom[$key]['style']['margin-'.$psv])) {
  20576. $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
  20577. }
  20578. }
  20579. // check for CSS border-spacing properties
  20580. if (isset($dom[$key]['style']['border-spacing'])) {
  20581. $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
  20582. }
  20583. // page-break-inside
  20584. if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
  20585. $dom[$key]['attribute']['nobr'] = 'true';
  20586. }
  20587. // page-break-before
  20588. if (isset($dom[$key]['style']['page-break-before'])) {
  20589. if ($dom[$key]['style']['page-break-before'] == 'always') {
  20590. $dom[$key]['attribute']['pagebreak'] = 'true';
  20591. } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
  20592. $dom[$key]['attribute']['pagebreak'] = 'left';
  20593. } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
  20594. $dom[$key]['attribute']['pagebreak'] = 'right';
  20595. }
  20596. }
  20597. // page-break-after
  20598. if (isset($dom[$key]['style']['page-break-after'])) {
  20599. if ($dom[$key]['style']['page-break-after'] == 'always') {
  20600. $dom[$key]['attribute']['pagebreakafter'] = 'true';
  20601. } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
  20602. $dom[$key]['attribute']['pagebreakafter'] = 'left';
  20603. } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
  20604. $dom[$key]['attribute']['pagebreakafter'] = 'right';
  20605. }
  20606. }
  20607. }
  20608. if (isset($dom[$key]['attribute']['display'])) {
  20609. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
  20610. }
  20611. if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
  20612. $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
  20613. if (!empty($borderstyle)) {
  20614. $dom[$key]['border']['LTRB'] = $borderstyle;
  20615. }
  20616. }
  20617. // check for font tag
  20618. if ($dom[$key]['value'] == 'font') {
  20619. // font family
  20620. if (isset($dom[$key]['attribute']['face'])) {
  20621. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
  20622. }
  20623. // font size
  20624. if (isset($dom[$key]['attribute']['size'])) {
  20625. if ($key > 0) {
  20626. if ($dom[$key]['attribute']['size']{0} == '+') {
  20627. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
  20628. } elseif ($dom[$key]['attribute']['size']{0} == '-') {
  20629. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
  20630. } else {
  20631. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  20632. }
  20633. } else {
  20634. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  20635. }
  20636. }
  20637. }
  20638. // force natural alignment for lists
  20639. if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
  20640. AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
  20641. if ($this->rtl) {
  20642. $dom[$key]['align'] = 'R';
  20643. } else {
  20644. $dom[$key]['align'] = 'L';
  20645. }
  20646. }
  20647. if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
  20648. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  20649. $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
  20650. }
  20651. }
  20652. if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
  20653. $dom[$key]['fontstyle'] .= 'B';
  20654. }
  20655. if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
  20656. $dom[$key]['fontstyle'] .= 'I';
  20657. }
  20658. if ($dom[$key]['value'] == 'u') {
  20659. $dom[$key]['fontstyle'] .= 'U';
  20660. }
  20661. if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
  20662. $dom[$key]['fontstyle'] .= 'D';
  20663. }
  20664. if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
  20665. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  20666. }
  20667. if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
  20668. $dom[$key]['fontname'] = $this->default_monospaced_font;
  20669. }
  20670. if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
  20671. // headings h1, h2, h3, h4, h5, h6
  20672. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  20673. $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
  20674. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
  20675. }
  20676. if (!isset($dom[$key]['style']['font-weight'])) {
  20677. $dom[$key]['fontstyle'] .= 'B';
  20678. }
  20679. }
  20680. if (($dom[$key]['value'] == 'table')) {
  20681. $dom[$key]['rows'] = 0; // number of rows
  20682. $dom[$key]['trids'] = array(); // IDs of TR elements
  20683. $dom[$key]['thead'] = ''; // table header rows
  20684. }
  20685. if (($dom[$key]['value'] == 'tr')) {
  20686. $dom[$key]['cols'] = 0;
  20687. if ($thead) {
  20688. $dom[$key]['thead'] = true;
  20689. // rows on thead block are printed as a separate table
  20690. } else {
  20691. $dom[$key]['thead'] = false;
  20692. // store the number of rows on table element
  20693. ++$dom[($dom[$key]['parent'])]['rows'];
  20694. // store the TR elements IDs on table element
  20695. array_push($dom[($dom[$key]['parent'])]['trids'], $key);
  20696. }
  20697. }
  20698. if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
  20699. if (isset($dom[$key]['attribute']['colspan'])) {
  20700. $colspan = intval($dom[$key]['attribute']['colspan']);
  20701. } else {
  20702. $colspan = 1;
  20703. }
  20704. $dom[$key]['attribute']['colspan'] = $colspan;
  20705. $dom[($dom[$key]['parent'])]['cols'] += $colspan;
  20706. }
  20707. // text direction
  20708. if (isset($dom[$key]['attribute']['dir'])) {
  20709. $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
  20710. }
  20711. // set foreground color attribute
  20712. if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
  20713. $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
  20714. } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
  20715. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  20716. }
  20717. // set background color attribute
  20718. if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
  20719. $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
  20720. }
  20721. // set stroke color attribute
  20722. if (isset($dom[$key]['attribute']['strokecolor']) AND (!$this->empty_string($dom[$key]['attribute']['strokecolor']))) {
  20723. $dom[$key]['strokecolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['strokecolor']);
  20724. }
  20725. // check for width attribute
  20726. if (isset($dom[$key]['attribute']['width'])) {
  20727. $dom[$key]['width'] = $dom[$key]['attribute']['width'];
  20728. }
  20729. // check for height attribute
  20730. if (isset($dom[$key]['attribute']['height'])) {
  20731. $dom[$key]['height'] = $dom[$key]['attribute']['height'];
  20732. }
  20733. // check for text alignment
  20734. if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
  20735. $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
  20736. }
  20737. // check for text rendering mode (the following attributes do not exist in HTML)
  20738. if (isset($dom[$key]['attribute']['stroke'])) {
  20739. // font stroke width
  20740. $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
  20741. }
  20742. if (isset($dom[$key]['attribute']['fill'])) {
  20743. // font fill
  20744. if ($dom[$key]['attribute']['fill'] == 'true') {
  20745. $dom[$key]['fill'] = true;
  20746. } else {
  20747. $dom[$key]['fill'] = false;
  20748. }
  20749. }
  20750. if (isset($dom[$key]['attribute']['clip'])) {
  20751. // clipping mode
  20752. if ($dom[$key]['attribute']['clip'] == 'true') {
  20753. $dom[$key]['clip'] = true;
  20754. } else {
  20755. $dom[$key]['clip'] = false;
  20756. }
  20757. }
  20758. } // end opening tag
  20759. } else {
  20760. // text
  20761. $dom[$key]['tag'] = false;
  20762. $dom[$key]['block'] = false;
  20763. //$element = str_replace('&nbsp;', $this->unichr(160), $element);
  20764. $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
  20765. $dom[$key]['parent'] = end($level);
  20766. $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
  20767. }
  20768. ++$elkey;
  20769. ++$key;
  20770. }
  20771. return $dom;
  20772. }
  20773. /**
  20774. * Returns the string used to find spaces
  20775. * @return string
  20776. * @protected
  20777. * @author Nicola Asuni
  20778. * @since 4.8.024 (2010-01-15)
  20779. */
  20780. protected function getSpaceString() {
  20781. $spacestr = chr(32);
  20782. if ($this->isUnicodeFont()) {
  20783. $spacestr = chr(0).chr(32);
  20784. }
  20785. return $spacestr;
  20786. }
  20787. /**
  20788. * Prints a cell (rectangular area) with optional borders, background color and html text string.
  20789. * 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 />
  20790. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  20791. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  20792. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  20793. * @param $x (float) upper-left corner X coordinate
  20794. * @param $y (float) upper-left corner Y coordinate
  20795. * @param $html (string) html text to print. Default value: empty string.
  20796. * @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)))
  20797. * @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>
  20798. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  20799. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  20800. * @param $reseth (boolean) if true reset the last cell height (default true).
  20801. * @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>
  20802. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  20803. * @see Multicell(), writeHTML()
  20804. * @public
  20805. */
  20806. public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
  20807. return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
  20808. }
  20809. /**
  20810. * Allows to preserve some HTML formatting (limited support).<br />
  20811. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  20812. * 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
  20813. * @param $html (string) text to display
  20814. * @param $ln (boolean) if true add a new line after text (default = true)
  20815. * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
  20816. * @param $reseth (boolean) if true reset the last cell height (default false).
  20817. * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
  20818. * @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>
  20819. * @public
  20820. */
  20821. public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
  20822. $gvars = $this->getGraphicVars();
  20823. // store current values
  20824. $prev_cell_margin = $this->cell_margin;
  20825. $prev_cell_padding = $this->cell_padding;
  20826. $prevPage = $this->page;
  20827. $prevlMargin = $this->lMargin;
  20828. $prevrMargin = $this->rMargin;
  20829. $curfontname = $this->FontFamily;
  20830. $curfontstyle = $this->FontStyle;
  20831. $curfontsize = $this->FontSizePt;
  20832. $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
  20833. $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
  20834. $curfontstretcing = $this->font_stretching;
  20835. $curfontkerning = $this->font_spacing;
  20836. $this->newline = true;
  20837. $newline = true;
  20838. $startlinepage = $this->page;
  20839. $minstartliney = $this->y;
  20840. $maxbottomliney = 0;
  20841. $startlinex = $this->x;
  20842. $startliney = $this->y;
  20843. $yshift = 0;
  20844. $loop = 0;
  20845. $curpos = 0;
  20846. $this_method_vars = array();
  20847. $undo = false;
  20848. $fontaligned = false;
  20849. $reverse_dir = false; // true when the text direction is reversed
  20850. $this->premode = false;
  20851. if ($this->inxobj) {
  20852. // we are inside an XObject template
  20853. $pask = count($this->xobjects[$this->xobjid]['annotations']);
  20854. } elseif (isset($this->PageAnnots[$this->page])) {
  20855. $pask = count($this->PageAnnots[$this->page]);
  20856. } else {
  20857. $pask = 0;
  20858. }
  20859. if ($this->inxobj) {
  20860. // we are inside an XObject template
  20861. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  20862. } elseif (!$this->InFooter) {
  20863. if (isset($this->footerlen[$this->page])) {
  20864. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  20865. } else {
  20866. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  20867. }
  20868. $startlinepos = $this->footerpos[$this->page];
  20869. } else {
  20870. // we are inside the footer
  20871. $startlinepos = $this->pagelen[$this->page];
  20872. }
  20873. $lalign = $align;
  20874. $plalign = $align;
  20875. if ($this->rtl) {
  20876. $w = $this->x - $this->lMargin;
  20877. } else {
  20878. $w = $this->w - $this->rMargin - $this->x;
  20879. }
  20880. $w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  20881. if ($cell) {
  20882. if ($this->rtl) {
  20883. $this->x -= $this->cell_padding['R'];
  20884. $this->lMargin += $this->cell_padding['R'];
  20885. } else {
  20886. $this->x += $this->cell_padding['L'];
  20887. $this->rMargin += $this->cell_padding['L'];
  20888. }
  20889. }
  20890. if ($this->customlistindent >= 0) {
  20891. $this->listindent = $this->customlistindent;
  20892. } else {
  20893. $this->listindent = $this->GetStringWidth('000000');
  20894. }
  20895. $this->listindentlevel = 0;
  20896. // save previous states
  20897. $prev_cell_height_ratio = $this->cell_height_ratio;
  20898. $prev_listnum = $this->listnum;
  20899. $prev_listordered = $this->listordered;
  20900. $prev_listcount = $this->listcount;
  20901. $prev_lispacer = $this->lispacer;
  20902. $this->listnum = 0;
  20903. $this->listordered = array();
  20904. $this->listcount = array();
  20905. $this->lispacer = '';
  20906. if (($this->empty_string($this->lasth)) OR ($reseth)) {
  20907. // reset row height
  20908. $this->resetLastH();
  20909. }
  20910. $dom = $this->getHtmlDomArray($html);
  20911. $maxel = count($dom);
  20912. $key = 0;
  20913. $hidden_node_key = -1;
  20914. while ($key < $maxel) {
  20915. if ($dom[$key]['tag']) {
  20916. if ($dom[$key]['opening']) {
  20917. if (($hidden_node_key <= 0) AND $dom[$key]['hide']) {
  20918. // store the node key
  20919. $hidden_node_key = $key;
  20920. }
  20921. } elseif (($hidden_node_key > 0) AND ($dom[$key]['parent'] == $hidden_node_key)) {
  20922. // we have reached the closing tag of the hidden node
  20923. $hidden_node_key = 0;
  20924. }
  20925. }
  20926. if ($hidden_node_key >= 0) {
  20927. // skip this node
  20928. ++$key;
  20929. if ($hidden_node_key == 0) {
  20930. // reset hidden mode
  20931. $hidden_node_key = -1;
  20932. }
  20933. continue;
  20934. }
  20935. if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
  20936. // check for pagebreak
  20937. if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
  20938. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  20939. $this->checkPageBreak($this->PageBreakTrigger + 1);
  20940. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  20941. }
  20942. if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  20943. OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  20944. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  20945. $this->checkPageBreak($this->PageBreakTrigger + 1);
  20946. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  20947. }
  20948. }
  20949. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
  20950. if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
  20951. $dom[$key]['attribute']['nobr'] = false;
  20952. } else {
  20953. // store current object
  20954. $this->startTransaction();
  20955. // save this method vars
  20956. $this_method_vars['html'] = $html;
  20957. $this_method_vars['ln'] = $ln;
  20958. $this_method_vars['fill'] = $fill;
  20959. $this_method_vars['reseth'] = $reseth;
  20960. $this_method_vars['cell'] = $cell;
  20961. $this_method_vars['align'] = $align;
  20962. $this_method_vars['gvars'] = $gvars;
  20963. $this_method_vars['prevPage'] = $prevPage;
  20964. $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
  20965. $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
  20966. $this_method_vars['prevlMargin'] = $prevlMargin;
  20967. $this_method_vars['prevrMargin'] = $prevrMargin;
  20968. $this_method_vars['curfontname'] = $curfontname;
  20969. $this_method_vars['curfontstyle'] = $curfontstyle;
  20970. $this_method_vars['curfontsize'] = $curfontsize;
  20971. $this_method_vars['curfontascent'] = $curfontascent;
  20972. $this_method_vars['curfontdescent'] = $curfontdescent;
  20973. $this_method_vars['curfontstretcing'] = $curfontstretcing;
  20974. $this_method_vars['curfontkerning'] = $curfontkerning;
  20975. $this_method_vars['minstartliney'] = $minstartliney;
  20976. $this_method_vars['maxbottomliney'] = $maxbottomliney;
  20977. $this_method_vars['yshift'] = $yshift;
  20978. $this_method_vars['startlinepage'] = $startlinepage;
  20979. $this_method_vars['startlinepos'] = $startlinepos;
  20980. $this_method_vars['startlinex'] = $startlinex;
  20981. $this_method_vars['startliney'] = $startliney;
  20982. $this_method_vars['newline'] = $newline;
  20983. $this_method_vars['loop'] = $loop;
  20984. $this_method_vars['curpos'] = $curpos;
  20985. $this_method_vars['pask'] = $pask;
  20986. $this_method_vars['lalign'] = $lalign;
  20987. $this_method_vars['plalign'] = $plalign;
  20988. $this_method_vars['w'] = $w;
  20989. $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
  20990. $this_method_vars['prev_listnum'] = $prev_listnum;
  20991. $this_method_vars['prev_listordered'] = $prev_listordered;
  20992. $this_method_vars['prev_listcount'] = $prev_listcount;
  20993. $this_method_vars['prev_lispacer'] = $prev_lispacer;
  20994. $this_method_vars['fontaligned'] = $fontaligned;
  20995. $this_method_vars['key'] = $key;
  20996. $this_method_vars['dom'] = $dom;
  20997. }
  20998. }
  20999. // print THEAD block
  21000. if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
  21001. if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !$this->empty_string($dom[$dom[$key]['parent']]['thead'])) {
  21002. $this->inthead = true;
  21003. // print table header (thead)
  21004. $this->writeHTML($this->thead, false, false, false, false, '');
  21005. // check if we are on a new page or on a new column
  21006. if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
  21007. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  21008. // restore previous object
  21009. $this->rollbackTransaction(true);
  21010. // restore previous values
  21011. foreach ($this_method_vars as $vkey => $vval) {
  21012. $$vkey = $vval;
  21013. }
  21014. // disable table header
  21015. $tmp_thead = $this->thead;
  21016. $this->thead = '';
  21017. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  21018. $pre_y = $this->y;
  21019. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  21020. // fix for multicolumn mode
  21021. $startliney = $this->y;
  21022. }
  21023. $this->start_transaction_page = $this->page;
  21024. $this->start_transaction_y = $this->y;
  21025. // restore table header
  21026. $this->thead = $tmp_thead;
  21027. // fix table border properties
  21028. if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
  21029. $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
  21030. } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
  21031. $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
  21032. } else {
  21033. $tmp_cellspacing = 0;
  21034. }
  21035. $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
  21036. $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
  21037. $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
  21038. $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
  21039. $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
  21040. $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
  21041. // print table header (thead)
  21042. $this->writeHTML($this->thead, false, false, false, false, '');
  21043. }
  21044. }
  21045. // move $key index forward to skip THEAD block
  21046. while ( ($key < $maxel) AND (!(
  21047. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
  21048. OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
  21049. ++$key;
  21050. }
  21051. }
  21052. if ($dom[$key]['tag'] OR ($key == 0)) {
  21053. if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
  21054. $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
  21055. }
  21056. // vertically align image in line
  21057. if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
  21058. // get image height
  21059. $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], $this->lasth, 'px');
  21060. $autolinebreak = false;
  21061. if (isset($dom[$key]['width']) AND ($dom[$key]['width'] > 0)) {
  21062. $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], 1, 'px', false);
  21063. if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
  21064. AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
  21065. OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
  21066. // add automatic line break
  21067. $autolinebreak = true;
  21068. $this->Ln('', $cell);
  21069. if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
  21070. // go back to evaluate this line break
  21071. --$key;
  21072. }
  21073. }
  21074. }
  21075. if (!$autolinebreak) {
  21076. if ($this->inPageBody()) {
  21077. $pre_y = $this->y;
  21078. // check for page break
  21079. if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
  21080. // fix for multicolumn mode
  21081. $startliney = $this->y;
  21082. }
  21083. }
  21084. if ($this->page > $startlinepage) {
  21085. // fix line splitted over two pages
  21086. if (isset($this->footerlen[$startlinepage])) {
  21087. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21088. }
  21089. // line to be moved one page forward
  21090. $pagebuff = $this->getPageBuffer($startlinepage);
  21091. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  21092. $tstart = substr($pagebuff, 0, $startlinepos);
  21093. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  21094. // remove line from previous page
  21095. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  21096. $pagebuff = $this->getPageBuffer($this->page);
  21097. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  21098. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  21099. // add line start to current page
  21100. $yshift = ($minstartliney - $this->y);
  21101. if ($fontaligned) {
  21102. $yshift += ($curfontsize / $this->k);
  21103. }
  21104. $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
  21105. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  21106. // shift the annotations and links
  21107. if (isset($this->PageAnnots[$this->page])) {
  21108. $next_pask = count($this->PageAnnots[$this->page]);
  21109. } else {
  21110. $next_pask = 0;
  21111. }
  21112. if (isset($this->PageAnnots[$startlinepage])) {
  21113. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  21114. if ($pak >= $pask) {
  21115. $this->PageAnnots[$this->page][] = $pac;
  21116. unset($this->PageAnnots[$startlinepage][$pak]);
  21117. $npak = count($this->PageAnnots[$this->page]) - 1;
  21118. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  21119. }
  21120. }
  21121. }
  21122. $pask = $next_pask;
  21123. $startlinepos = $this->cntmrk[$this->page];
  21124. $startlinepage = $this->page;
  21125. $startliney = $this->y;
  21126. $this->newline = false;
  21127. }
  21128. $this->y += ((($curfontsize * $this->cell_height_ratio / $this->k) + $curfontascent - $curfontdescent) / 2) - $imgh;
  21129. $minstartliney = min($this->y, $minstartliney);
  21130. $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio));
  21131. }
  21132. } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
  21133. // account for different font size
  21134. $pfontname = $curfontname;
  21135. $pfontstyle = $curfontstyle;
  21136. $pfontsize = $curfontsize;
  21137. $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
  21138. $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
  21139. $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
  21140. $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
  21141. $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
  21142. if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
  21143. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  21144. OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
  21145. if (($key < ($maxel - 1)) AND (
  21146. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
  21147. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  21148. OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize) AND ($fontsize >= 0) AND ($curfontsize >= 0) AND ($fontsize != $curfontsize))
  21149. )) {
  21150. if ($this->page > $startlinepage) {
  21151. // fix lines splitted over two pages
  21152. if (isset($this->footerlen[$startlinepage])) {
  21153. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21154. }
  21155. // line to be moved one page forward
  21156. $pagebuff = $this->getPageBuffer($startlinepage);
  21157. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  21158. $tstart = substr($pagebuff, 0, $startlinepos);
  21159. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  21160. // remove line start from previous page
  21161. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  21162. $pagebuff = $this->getPageBuffer($this->page);
  21163. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  21164. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  21165. // add line start to current page
  21166. $yshift = ($minstartliney - $this->y);
  21167. $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
  21168. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  21169. // shift the annotations and links
  21170. if (isset($this->PageAnnots[$this->page])) {
  21171. $next_pask = count($this->PageAnnots[$this->page]);
  21172. } else {
  21173. $next_pask = 0;
  21174. }
  21175. if (isset($this->PageAnnots[$startlinepage])) {
  21176. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  21177. if ($pak >= $pask) {
  21178. $this->PageAnnots[$this->page][] = $pac;
  21179. unset($this->PageAnnots[$startlinepage][$pak]);
  21180. $npak = count($this->PageAnnots[$this->page]) - 1;
  21181. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  21182. }
  21183. }
  21184. }
  21185. $pask = $next_pask;
  21186. $startlinepos = $this->cntmrk[$this->page];
  21187. $startlinepage = $this->page;
  21188. $startliney = $this->y;
  21189. }
  21190. if (!isset($dom[$key]['line-height'])) {
  21191. $dom[$key]['line-height'] = $this->cell_height_ratio;
  21192. }
  21193. if (!$dom[$key]['block']) {
  21194. 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']))) {
  21195. $this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
  21196. }
  21197. if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
  21198. $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
  21199. 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)))) {
  21200. $minstartliney = min($this->y, $line_align_data[1]);
  21201. $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $line_align_data[2]);
  21202. } else {
  21203. $minstartliney = min($this->y, $minstartliney);
  21204. $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney);
  21205. }
  21206. $line_align_data = $current_line_align_data;
  21207. }
  21208. }
  21209. $this->cell_height_ratio = $dom[$key]['line-height'];
  21210. $fontaligned = true;
  21211. }
  21212. $this->SetFont($fontname, $fontstyle, $fontsize);
  21213. // reset row height
  21214. $this->resetLastH();
  21215. $curfontname = $fontname;
  21216. $curfontstyle = $fontstyle;
  21217. $curfontsize = $fontsize;
  21218. $curfontascent = $fontascent;
  21219. $curfontdescent = $fontdescent;
  21220. }
  21221. }
  21222. // set text rendering mode
  21223. $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
  21224. $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
  21225. $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
  21226. $this->setTextRenderingMode($textstroke, $textfill, $textclip);
  21227. if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
  21228. $this->setFontStretching($dom[$key]['font-stretch']);
  21229. }
  21230. if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
  21231. $this->setFontSpacing($dom[$key]['letter-spacing']);
  21232. }
  21233. if (($plalign == 'J') AND $dom[$key]['block']) {
  21234. $plalign = '';
  21235. }
  21236. // get current position on page buffer
  21237. $curpos = $this->pagelen[$startlinepage];
  21238. if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
  21239. $this->SetFillColorArray($dom[$key]['bgcolor']);
  21240. $wfill = true;
  21241. } else {
  21242. $wfill = $fill | false;
  21243. }
  21244. if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
  21245. $this->SetTextColorArray($dom[$key]['fgcolor']);
  21246. }
  21247. if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
  21248. $this->SetDrawColorArray($dom[$key]['strokecolor']);
  21249. }
  21250. if (isset($dom[$key]['align'])) {
  21251. $lalign = $dom[$key]['align'];
  21252. }
  21253. if ($this->empty_string($lalign)) {
  21254. $lalign = $align;
  21255. }
  21256. }
  21257. // align lines
  21258. if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
  21259. $newline = true;
  21260. $fontaligned = false;
  21261. // we are at the beginning of a new line
  21262. if (isset($startlinex)) {
  21263. $yshift = ($minstartliney - $startliney);
  21264. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  21265. $yshift = 0;
  21266. }
  21267. $t_x = 0;
  21268. // the last line must be shifted to be aligned as requested
  21269. $linew = abs($this->endlinex - $startlinex);
  21270. if ($this->inxobj) {
  21271. // we are inside an XObject template
  21272. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  21273. if (isset($opentagpos)) {
  21274. $midpos = $opentagpos;
  21275. } else {
  21276. $midpos = 0;
  21277. }
  21278. if ($midpos > 0) {
  21279. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  21280. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  21281. } else {
  21282. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  21283. $pend = '';
  21284. }
  21285. } else {
  21286. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  21287. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  21288. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21289. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  21290. } elseif (isset($opentagpos)) {
  21291. $midpos = $opentagpos;
  21292. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  21293. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21294. $midpos = $this->footerpos[$startlinepage];
  21295. } else {
  21296. $midpos = 0;
  21297. }
  21298. if ($midpos > 0) {
  21299. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  21300. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  21301. } else {
  21302. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  21303. $pend = '';
  21304. }
  21305. }
  21306. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  21307. // calculate shifting amount
  21308. $tw = $w;
  21309. if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
  21310. $tw += $this->cell_padding['R'];
  21311. }
  21312. if ($this->lMargin != $prevlMargin) {
  21313. $tw += ($prevlMargin - $this->lMargin);
  21314. }
  21315. if ($this->rMargin != $prevrMargin) {
  21316. $tw += ($prevrMargin - $this->rMargin);
  21317. }
  21318. $one_space_width = $this->GetStringWidth(chr(32));
  21319. $no = 0; // number of spaces on a line contained on a single block
  21320. if ($this->isRTLTextDir()) { // RTL
  21321. // remove left space if exist
  21322. $pos1 = $this->revstrpos($pmid, '[(');
  21323. if ($pos1 > 0) {
  21324. $pos1 = intval($pos1);
  21325. if ($this->isUnicodeFont()) {
  21326. $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32)));
  21327. $spacelen = 2;
  21328. } else {
  21329. $pos2 = intval($this->revstrpos($pmid, '[('.chr(32)));
  21330. $spacelen = 1;
  21331. }
  21332. if ($pos1 == $pos2) {
  21333. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  21334. if (substr($pmid, $pos1, 4) == '[()]') {
  21335. $linew -= $one_space_width;
  21336. } elseif ($pos1 == strpos($pmid, '[(')) {
  21337. $no = 1;
  21338. }
  21339. }
  21340. }
  21341. } else { // LTR
  21342. // remove right space if exist
  21343. $pos1 = $this->revstrpos($pmid, ')]');
  21344. if ($pos1 > 0) {
  21345. $pos1 = intval($pos1);
  21346. if ($this->isUnicodeFont()) {
  21347. $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  21348. $spacelen = 2;
  21349. } else {
  21350. $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1;
  21351. $spacelen = 1;
  21352. }
  21353. if ($pos1 == $pos2) {
  21354. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  21355. $linew -= $one_space_width;
  21356. }
  21357. }
  21358. }
  21359. $mdiff = ($tw - $linew);
  21360. if ($plalign == 'C') {
  21361. if ($this->rtl) {
  21362. $t_x = -($mdiff / 2);
  21363. } else {
  21364. $t_x = ($mdiff / 2);
  21365. }
  21366. } elseif ($plalign == 'R') {
  21367. // right alignment on LTR document
  21368. $t_x = $mdiff;
  21369. } elseif ($plalign == 'L') {
  21370. // left alignment on RTL document
  21371. $t_x = -$mdiff;
  21372. } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
  21373. // Justification
  21374. if ($this->isRTLTextDir()) {
  21375. // align text on the left
  21376. $t_x = -$mdiff;
  21377. }
  21378. $ns = 0; // number of spaces
  21379. $pmidtemp = $pmid;
  21380. // escape special characters
  21381. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  21382. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  21383. // search spaces
  21384. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
  21385. $spacestr = $this->getSpaceString();
  21386. $maxkk = count($lnstring[1]) - 1;
  21387. for ($kk=0; $kk <= $maxkk; ++$kk) {
  21388. // restore special characters
  21389. $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
  21390. $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
  21391. // store number of spaces on the strings
  21392. $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
  21393. // count total spaces on line
  21394. $ns += $lnstring[2][$kk];
  21395. $lnstring[3][$kk] = $ns;
  21396. }
  21397. if ($ns == 0) {
  21398. $ns = 1;
  21399. }
  21400. // calculate additional space to add to each existing space
  21401. $spacewidth = ($mdiff / ($ns - $no)) * $this->k;
  21402. $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
  21403. if ($this->font_spacing != 0) {
  21404. // fixed spacing mode
  21405. $osw = -1000 * $this->font_spacing / $this->FontSize;
  21406. $spacewidthu += $osw;
  21407. }
  21408. $nsmax = $ns;
  21409. $ns = 0;
  21410. reset($lnstring);
  21411. $offset = 0;
  21412. $strcount = 0;
  21413. $prev_epsposbeg = 0;
  21414. $textpos = 0;
  21415. if ($this->isRTLTextDir()) {
  21416. $textpos = $this->wPt;
  21417. }
  21418. global $spacew;
  21419. while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
  21420. // check if we are inside a string section '[( ... )]'
  21421. $stroffset = strpos($pmid, '[(', $offset);
  21422. if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
  21423. // set offset to the end of string section
  21424. $offset = strpos($pmid, ')]', $stroffset);
  21425. while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
  21426. $offset = strpos($pmid, ')]', ($offset + 1));
  21427. }
  21428. if ($offset === false) {
  21429. $this->Error('HTML Justification: malformed PDF code.');
  21430. }
  21431. continue;
  21432. }
  21433. if ($this->isRTLTextDir()) {
  21434. $spacew = ($spacewidth * ($nsmax - $ns));
  21435. } else {
  21436. $spacew = ($spacewidth * $ns);
  21437. }
  21438. $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
  21439. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
  21440. $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
  21441. if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
  21442. OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
  21443. // shift EPS images
  21444. $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
  21445. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
  21446. $pmid_b = substr($pmid, 0, $epsposbeg);
  21447. $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
  21448. $pmid_e = substr($pmid, $epsposend);
  21449. $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
  21450. $offset = $epsposend;
  21451. continue;
  21452. }
  21453. $prev_epsposbeg = $epsposbeg;
  21454. $currentxpos = 0;
  21455. // shift blocks of code
  21456. switch ($strpiece[2][0]) {
  21457. case 'Td':
  21458. case 'cm':
  21459. case 'm':
  21460. case 'l': {
  21461. // get current X position
  21462. preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  21463. $currentxpos = $xmatches[1];
  21464. $textpos = $currentxpos;
  21465. if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
  21466. $ns = $lnstring[3][$strcount];
  21467. if ($this->isRTLTextDir()) {
  21468. $spacew = ($spacewidth * ($nsmax - $ns));
  21469. }
  21470. ++$strcount;
  21471. }
  21472. // justify block
  21473. $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
  21474. create_function('$matches', 'global $spacew;
  21475. $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
  21476. return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
  21477. break;
  21478. }
  21479. case 're': {
  21480. // justify block
  21481. if (!$this->empty_string($this->lispacer)) {
  21482. $this->lispacer = '';
  21483. continue;
  21484. }
  21485. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
  21486. $currentxpos = $xmatches[1];
  21487. global $x_diff, $w_diff;
  21488. $x_diff = 0;
  21489. $w_diff = 0;
  21490. if ($this->isRTLTextDir()) { // RTL
  21491. if ($currentxpos < $textpos) {
  21492. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
  21493. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  21494. } else {
  21495. if ($strcount > 0) {
  21496. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
  21497. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  21498. }
  21499. }
  21500. } else { // LTR
  21501. if ($currentxpos > $textpos) {
  21502. if ($strcount > 0) {
  21503. $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
  21504. }
  21505. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  21506. } else {
  21507. if ($strcount > 1) {
  21508. $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
  21509. }
  21510. if ($strcount > 0) {
  21511. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  21512. }
  21513. }
  21514. }
  21515. $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x',
  21516. create_function('$matches', 'global $x_diff, $w_diff;
  21517. $newx = sprintf("%.2F",(floatval($matches[1]) + $x_diff));
  21518. $neww = sprintf("%.2F",(floatval($matches[3]) + $w_diff));
  21519. return "".$newx." ".$matches[2]." ".$neww." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
  21520. break;
  21521. }
  21522. case 'c': {
  21523. // get current X position
  21524. 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);
  21525. $currentxpos = $xmatches[1];
  21526. // justify block
  21527. $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$xmatches[4].')[\s]('.$xmatches[5].')[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x',
  21528. create_function('$matches', 'global $spacew;
  21529. $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
  21530. $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
  21531. $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
  21532. return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
  21533. break;
  21534. }
  21535. }
  21536. // shift the annotations and links
  21537. $cxpos = ($currentxpos / $this->k);
  21538. $lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
  21539. if ($this->inxobj) {
  21540. // we are inside an XObject template
  21541. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  21542. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  21543. if ($cxpos > $lmpos) {
  21544. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
  21545. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  21546. } else {
  21547. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  21548. }
  21549. break;
  21550. }
  21551. }
  21552. } elseif (isset($this->PageAnnots[$this->page])) {
  21553. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  21554. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  21555. if ($cxpos > $lmpos) {
  21556. $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
  21557. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  21558. } else {
  21559. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  21560. }
  21561. break;
  21562. }
  21563. }
  21564. }
  21565. } // end of while
  21566. // remove markers
  21567. $pmid = str_replace('x*#!#*x', '', $pmid);
  21568. if ($this->isUnicodeFont()) {
  21569. // multibyte characters
  21570. $spacew = $spacewidthu;
  21571. if ($this->font_stretching != 100) {
  21572. // word spacing is affected by stretching
  21573. $spacew /= ($this->font_stretching / 100);
  21574. }
  21575. $pmidtemp = $pmid;
  21576. // escape special characters
  21577. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  21578. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  21579. $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
  21580. create_function('$matches', 'global $spacew;
  21581. $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
  21582. $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
  21583. return "[(".str_replace(chr(0).chr(32), ") ".sprintf("%.3F", $spacew)." (", $matches[1]).")]";'), $pmidtemp);
  21584. if ($this->inxobj) {
  21585. // we are inside an XObject template
  21586. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
  21587. } else {
  21588. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
  21589. }
  21590. $endlinepos = strlen($pstart."\n".$pmid."\n");
  21591. } else {
  21592. // non-unicode (single-byte characters)
  21593. if ($this->font_stretching != 100) {
  21594. // word spacing (Tw) is affected by stretching
  21595. $spacewidth /= ($this->font_stretching / 100);
  21596. }
  21597. $rs = sprintf('%.3F Tw', $spacewidth);
  21598. $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
  21599. if ($this->inxobj) {
  21600. // we are inside an XObject template
  21601. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
  21602. } else {
  21603. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
  21604. }
  21605. $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
  21606. }
  21607. }
  21608. } // end of J
  21609. } // end if $startlinex
  21610. if (($t_x != 0) OR ($yshift < 0)) {
  21611. // shift the line
  21612. $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
  21613. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  21614. $endlinepos = strlen($pstart);
  21615. if ($this->inxobj) {
  21616. // we are inside an XObject template
  21617. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  21618. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  21619. if ($pak >= $pask) {
  21620. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  21621. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  21622. }
  21623. }
  21624. } else {
  21625. $this->setPageBuffer($startlinepage, $pstart.$pend);
  21626. // shift the annotations and links
  21627. if (isset($this->PageAnnots[$this->page])) {
  21628. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  21629. if ($pak >= $pask) {
  21630. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  21631. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  21632. }
  21633. }
  21634. }
  21635. }
  21636. $this->y -= $yshift;
  21637. }
  21638. }
  21639. $pbrk = $this->checkPageBreak($this->lasth);
  21640. $this->newline = false;
  21641. $startlinex = $this->x;
  21642. $startliney = $this->y;
  21643. if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
  21644. $startliney -= ((0.3 * $this->FontSizePt) / $this->k);
  21645. } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
  21646. $startliney -= (($this->FontSizePt / 0.7) / $this->k);
  21647. } else {
  21648. $minstartliney = $startliney;
  21649. $maxbottomliney = ($this->y + (($fontsize * $this->cell_height_ratio) / $this->k));
  21650. }
  21651. $startlinepage = $this->page;
  21652. if (isset($endlinepos) AND (!$pbrk)) {
  21653. $startlinepos = $endlinepos;
  21654. } else {
  21655. if ($this->inxobj) {
  21656. // we are inside an XObject template
  21657. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  21658. } elseif (!$this->InFooter) {
  21659. if (isset($this->footerlen[$this->page])) {
  21660. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  21661. } else {
  21662. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  21663. }
  21664. $startlinepos = $this->footerpos[$this->page];
  21665. } else {
  21666. $startlinepos = $this->pagelen[$this->page];
  21667. }
  21668. }
  21669. unset($endlinepos);
  21670. $plalign = $lalign;
  21671. if (isset($this->PageAnnots[$this->page])) {
  21672. $pask = count($this->PageAnnots[$this->page]);
  21673. } else {
  21674. $pask = 0;
  21675. }
  21676. if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
  21677. AND (isset($this->emptypagemrk[$this->page]))
  21678. AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
  21679. $this->SetFont($fontname, $fontstyle, $fontsize);
  21680. if ($wfill) {
  21681. $this->SetFillColorArray($this->bgcolor);
  21682. }
  21683. }
  21684. } // end newline
  21685. if (isset($opentagpos)) {
  21686. unset($opentagpos);
  21687. }
  21688. if ($dom[$key]['tag']) {
  21689. if ($dom[$key]['opening']) {
  21690. // get text indentation (if any)
  21691. if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
  21692. $this->textindent = $dom[$key]['text-indent'];
  21693. $this->newline = true;
  21694. }
  21695. // table
  21696. if ($dom[$key]['value'] == 'table') {
  21697. // available page width
  21698. if ($this->rtl) {
  21699. $wtmp = $this->x - $this->lMargin;
  21700. } else {
  21701. $wtmp = $this->w - $this->rMargin - $this->x;
  21702. }
  21703. // get cell spacing
  21704. if (isset($dom[$key]['attribute']['cellspacing'])) {
  21705. $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
  21706. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  21707. } elseif (isset($dom[$key]['border-spacing'])) {
  21708. $cellspacing = $dom[$key]['border-spacing'];
  21709. } else {
  21710. $cellspacing = array('H' => 0, 'V' => 0);
  21711. }
  21712. // table width
  21713. if (isset($dom[$key]['width'])) {
  21714. $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  21715. } else {
  21716. $table_width = $wtmp;
  21717. }
  21718. $table_width -= (2 * $cellspacing['H']);
  21719. if (!$this->inthead) {
  21720. $this->y += $cellspacing['V'];
  21721. }
  21722. if ($this->rtl) {
  21723. $cellspacingx = -$cellspacing['H'];
  21724. } else {
  21725. $cellspacingx = $cellspacing['H'];
  21726. }
  21727. // total table width without cellspaces
  21728. $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
  21729. // minimum column width
  21730. $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
  21731. // array of custom column widths
  21732. $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
  21733. }
  21734. // table row
  21735. if ($dom[$key]['value'] == 'tr') {
  21736. // reset column counter
  21737. $colid = 0;
  21738. }
  21739. // table cell
  21740. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  21741. $trid = $dom[$key]['parent'];
  21742. $table_el = $dom[$trid]['parent'];
  21743. if (!isset($dom[$table_el]['cols'])) {
  21744. $dom[$table_el]['cols'] = $dom[$trid]['cols'];
  21745. }
  21746. // store border info
  21747. $tdborder = 0;
  21748. if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
  21749. $tdborder = $dom[$key]['border'];
  21750. }
  21751. $colspan = $dom[$key]['attribute']['colspan'];
  21752. $old_cell_padding = $this->cell_padding;
  21753. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
  21754. $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
  21755. $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
  21756. } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
  21757. $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
  21758. } else {
  21759. $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
  21760. }
  21761. $this->cell_padding = $current_cell_padding;
  21762. if (isset($dom[$key]['height'])) {
  21763. // minimum cell height
  21764. $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
  21765. } else {
  21766. $cellh = 0;
  21767. }
  21768. if (isset($dom[$key]['content'])) {
  21769. $cell_content = stripslashes($dom[$key]['content']);
  21770. } else {
  21771. $cell_content = '&nbsp;';
  21772. }
  21773. $tagtype = $dom[$key]['value'];
  21774. $parentid = $key;
  21775. while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
  21776. // move $key index forward
  21777. ++$key;
  21778. }
  21779. if (!isset($dom[$trid]['startpage'])) {
  21780. $dom[$trid]['startpage'] = $this->page;
  21781. } else {
  21782. $this->setPage($dom[$trid]['startpage']);
  21783. }
  21784. if (!isset($dom[$trid]['startcolumn'])) {
  21785. $dom[$trid]['startcolumn'] = $this->current_column;
  21786. } elseif ($this->current_column != $dom[$trid]['startcolumn']) {
  21787. $tmpx = $this->x;
  21788. $this->selectColumn($dom[$trid]['startcolumn']);
  21789. $this->x = $tmpx;
  21790. }
  21791. if (!isset($dom[$trid]['starty'])) {
  21792. $dom[$trid]['starty'] = $this->y;
  21793. } else {
  21794. $this->y = $dom[$trid]['starty'];
  21795. }
  21796. if (!isset($dom[$trid]['startx'])) {
  21797. $dom[$trid]['startx'] = $this->x;
  21798. $this->x += $cellspacingx;
  21799. } else {
  21800. $this->x += ($cellspacingx / 2);
  21801. }
  21802. if (isset($dom[$parentid]['attribute']['rowspan'])) {
  21803. $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
  21804. } else {
  21805. $rowspan = 1;
  21806. }
  21807. // skip row-spanned cells started on the previous rows
  21808. if (isset($dom[$table_el]['rowspans'])) {
  21809. $rsk = 0;
  21810. $rskmax = count($dom[$table_el]['rowspans']);
  21811. while ($rsk < $rskmax) {
  21812. $trwsp = $dom[$table_el]['rowspans'][$rsk];
  21813. $rsstartx = $trwsp['startx'];
  21814. $rsendx = $trwsp['endx'];
  21815. // account for margin changes
  21816. if ($trwsp['startpage'] < $this->page) {
  21817. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
  21818. $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
  21819. $rsstartx -= $dl;
  21820. $rsendx -= $dl;
  21821. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
  21822. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
  21823. $rsstartx += $dl;
  21824. $rsendx += $dl;
  21825. }
  21826. }
  21827. if (($trwsp['rowspan'] > 0)
  21828. AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
  21829. AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
  21830. AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
  21831. // set the starting X position of the current cell
  21832. $this->x = $rsendx + $cellspacingx;
  21833. // increment column indicator
  21834. $colid += $trwsp['colspan'];
  21835. if (($trwsp['rowspan'] == 1)
  21836. AND (isset($dom[$trid]['endy']))
  21837. AND (isset($dom[$trid]['endpage']))
  21838. AND (isset($dom[$trid]['endcolumn']))
  21839. AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
  21840. AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  21841. // set ending Y position for row
  21842. $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  21843. $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
  21844. }
  21845. $rsk = 0;
  21846. } else {
  21847. ++$rsk;
  21848. }
  21849. }
  21850. }
  21851. if (isset($dom[$parentid]['width'])) {
  21852. // user specified width
  21853. $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
  21854. $tmpcw = ($cellw / $colspan);
  21855. for ($i = 0; $i < $colspan; ++$i) {
  21856. $table_colwidths[($colid + $i)] = $tmpcw;
  21857. }
  21858. } else {
  21859. // inherit column width
  21860. $cellw = 0;
  21861. for ($i = 0; $i < $colspan; ++$i) {
  21862. $cellw += $table_colwidths[($colid + $i)];
  21863. }
  21864. }
  21865. $cellw += (($colspan - 1) * $cellspacing['H']);
  21866. // increment column indicator
  21867. $colid += $colspan;
  21868. // add rowspan information to table element
  21869. if ($rowspan > 1) {
  21870. $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));
  21871. }
  21872. $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
  21873. if ($rowspan > 1) {
  21874. $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
  21875. }
  21876. // push background colors
  21877. if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
  21878. $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
  21879. }
  21880. // store border info
  21881. if (isset($tdborder) AND !empty($tdborder)) {
  21882. $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
  21883. }
  21884. $prevLastH = $this->lasth;
  21885. // store some info for multicolumn mode
  21886. if ($this->rtl) {
  21887. $this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
  21888. } else {
  21889. $this->colxshift['x'] = $this->x - $this->lMargin;
  21890. }
  21891. $this->colxshift['s'] = $cellspacing;
  21892. $this->colxshift['p'] = $current_cell_padding;
  21893. // ****** write the cell content ******
  21894. $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
  21895. // restore some values
  21896. $this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  21897. $this->lasth = $prevLastH;
  21898. $this->cell_padding = $old_cell_padding;
  21899. $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
  21900. // update the end of row position
  21901. if ($rowspan <= 1) {
  21902. if (isset($dom[$trid]['endy'])) {
  21903. if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
  21904. $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
  21905. } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
  21906. $dom[$trid]['endy'] = $this->y;
  21907. }
  21908. } else {
  21909. $dom[$trid]['endy'] = $this->y;
  21910. }
  21911. if (isset($dom[$trid]['endpage'])) {
  21912. $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
  21913. } else {
  21914. $dom[$trid]['endpage'] = $this->page;
  21915. }
  21916. if (isset($dom[$trid]['endcolumn'])) {
  21917. $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
  21918. } else {
  21919. $dom[$trid]['endcolumn'] = $this->current_column;
  21920. }
  21921. } else {
  21922. // account for row-spanned cells
  21923. $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
  21924. $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
  21925. $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
  21926. $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
  21927. }
  21928. if (isset($dom[$table_el]['rowspans'])) {
  21929. // update endy and endpage on rowspanned cells
  21930. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  21931. if ($trwsp['rowspan'] > 0) {
  21932. if (isset($dom[$trid]['endpage'])) {
  21933. if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  21934. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  21935. } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
  21936. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
  21937. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
  21938. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
  21939. } else {
  21940. $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
  21941. }
  21942. }
  21943. }
  21944. }
  21945. }
  21946. $this->x += ($cellspacingx / 2);
  21947. } else {
  21948. // opening tag (or self-closing tag)
  21949. if (!isset($opentagpos)) {
  21950. if ($this->inxobj) {
  21951. // we are inside an XObject template
  21952. $opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
  21953. } elseif (!$this->InFooter) {
  21954. if (isset($this->footerlen[$this->page])) {
  21955. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  21956. } else {
  21957. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  21958. }
  21959. $opentagpos = $this->footerpos[$this->page];
  21960. }
  21961. }
  21962. $dom = $this->openHTMLTagHandler($dom, $key, $cell);
  21963. }
  21964. } else { // closing tag
  21965. $prev_numpages = $this->numpages;
  21966. $old_bordermrk = $this->bordermrk[$this->page];
  21967. $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
  21968. if ($this->bordermrk[$this->page] > $old_bordermrk) {
  21969. $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
  21970. }
  21971. if ($prev_numpages > $this->numpages) {
  21972. $startlinepage = $this->page;
  21973. }
  21974. }
  21975. } elseif (strlen($dom[$key]['value']) > 0) {
  21976. // print list-item
  21977. if (!$this->empty_string($this->lispacer) AND ($this->lispacer != '^')) {
  21978. $this->SetFont($pfontname, $pfontstyle, $pfontsize);
  21979. $this->resetLastH();
  21980. $minstartliney = $this->y;
  21981. $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio));
  21982. $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
  21983. $this->SetFont($curfontname, $curfontstyle, $curfontsize);
  21984. $this->resetLastH();
  21985. if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
  21986. $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
  21987. $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
  21988. $this->y += ((($pfontsize - $curfontsize) * $this->cell_height_ratio / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
  21989. $minstartliney = min($this->y, $minstartliney);
  21990. $maxbottomliney = max(($this->y + (($pfontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney);
  21991. }
  21992. }
  21993. // text
  21994. $this->htmlvspace = 0;
  21995. if ((!$this->premode) AND $this->isRTLTextDir()) {
  21996. // reverse spaces order
  21997. $lsp = ''; // left spaces
  21998. $rsp = ''; // right spaces
  21999. if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  22000. $lsp = $matches[1];
  22001. }
  22002. if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  22003. $rsp = $matches[1];
  22004. }
  22005. $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
  22006. }
  22007. if ($newline) {
  22008. if (!$this->premode) {
  22009. $prelen = strlen($dom[$key]['value']);
  22010. if ($this->isRTLTextDir()) {
  22011. // right trim except non-breaking space
  22012. $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
  22013. } else {
  22014. // left trim except non-breaking space
  22015. $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
  22016. }
  22017. $postlen = strlen($dom[$key]['value']);
  22018. if (($postlen == 0) AND ($prelen > 0)) {
  22019. $dom[$key]['trimmed_space'] = true;
  22020. }
  22021. }
  22022. $newline = false;
  22023. $firstblock = true;
  22024. } else {
  22025. $firstblock = false;
  22026. // replace empty multiple spaces string with a single space
  22027. $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
  22028. }
  22029. $strrest = '';
  22030. if ($this->rtl) {
  22031. $this->x -= $this->textindent;
  22032. } else {
  22033. $this->x += $this->textindent;
  22034. }
  22035. if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
  22036. $strlinelen = $this->GetStringWidth($dom[$key]['value']);
  22037. if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
  22038. // HTML <a> Link
  22039. $hrefcolor = '';
  22040. if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
  22041. $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
  22042. }
  22043. $hrefstyle = -1;
  22044. if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
  22045. $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
  22046. }
  22047. $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
  22048. } else {
  22049. $wadj = 0; // space to leave for block continuity
  22050. if ($this->rtl) {
  22051. $cwa = $this->x - $this->lMargin;
  22052. } else {
  22053. $cwa = $this->w - $this->rMargin - $this->x;
  22054. }
  22055. if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
  22056. // check the next text blocks for continuity
  22057. $nkey = ($key + 1);
  22058. $write_block = true;
  22059. $same_textdir = true;
  22060. $tmp_fontname = $this->FontFamily;
  22061. $tmp_fontstyle = $this->FontStyle;
  22062. $tmp_fontsize = $this->FontSizePt;
  22063. while ($write_block AND isset($dom[$nkey])) {
  22064. if ($dom[$nkey]['tag']) {
  22065. if ($dom[$nkey]['block']) {
  22066. // end of block
  22067. $write_block = false;
  22068. }
  22069. $tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
  22070. $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
  22071. $tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
  22072. $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
  22073. } else {
  22074. $nextstr = preg_split('/'.$this->re_space['p'].'+/'.$this->re_space['m'], $dom[$nkey]['value']);
  22075. if (isset($nextstr[0]) AND $same_textdir) {
  22076. $wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
  22077. }
  22078. if (isset($nextstr[1])) {
  22079. $write_block = false;
  22080. }
  22081. }
  22082. ++$nkey;
  22083. }
  22084. }
  22085. if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
  22086. $wadj = 0;
  22087. $nextstr = preg_split('/'.$this->re_space['p'].'/'.$this->re_space['m'], $dom[$key]['value']);
  22088. $numblks = count($nextstr);
  22089. if ($numblks > 1) {
  22090. // try to split on blank spaces
  22091. $wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
  22092. }
  22093. }
  22094. // check for reversed text direction
  22095. if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
  22096. // LTR text on RTL direction or RTL text on LTR direction
  22097. $reverse_dir = true;
  22098. $this->rtl = !$this->rtl;
  22099. $revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
  22100. if ($this->rtl) {
  22101. $this->x += $revshift;
  22102. } else {
  22103. $this->x -= $revshift;
  22104. }
  22105. $xws = $this->x;
  22106. }
  22107. // ****** write only until the end of the line and get the rest ******
  22108. $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
  22109. // restore default direction
  22110. if ($reverse_dir AND ($wadj == 0)) {
  22111. $this->x = $xws;
  22112. $this->rtl = !$this->rtl;
  22113. $reverse_dir = false;
  22114. }
  22115. }
  22116. }
  22117. $this->textindent = 0;
  22118. if (strlen($strrest) > 0) {
  22119. // store the remaining string on the previous $key position
  22120. $this->newline = true;
  22121. if ($strrest == $dom[$key]['value']) {
  22122. // used to avoid infinite loop
  22123. ++$loop;
  22124. } else {
  22125. $loop = 0;
  22126. }
  22127. $dom[$key]['value'] = $strrest;
  22128. if ($cell) {
  22129. if ($this->rtl) {
  22130. $this->x -= $this->cell_padding['R'];
  22131. } else {
  22132. $this->x += $this->cell_padding['L'];
  22133. }
  22134. }
  22135. if ($loop < 3) {
  22136. --$key;
  22137. }
  22138. } else {
  22139. $loop = 0;
  22140. }
  22141. }
  22142. ++$key;
  22143. 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')) {
  22144. // check if we are on a new page or on a new column
  22145. if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
  22146. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  22147. // restore previous object
  22148. $this->rollbackTransaction(true);
  22149. // restore previous values
  22150. foreach ($this_method_vars as $vkey => $vval) {
  22151. $$vkey = $vval;
  22152. }
  22153. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  22154. $pre_y = $this->y;
  22155. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  22156. $startliney = $this->y;
  22157. }
  22158. $undo = true; // avoid infinite loop
  22159. } else {
  22160. $undo = false;
  22161. }
  22162. }
  22163. } // end for each $key
  22164. // align the last line
  22165. if (isset($startlinex)) {
  22166. $yshift = ($minstartliney - $startliney);
  22167. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  22168. $yshift = 0;
  22169. }
  22170. $t_x = 0;
  22171. // the last line must be shifted to be aligned as requested
  22172. $linew = abs($this->endlinex - $startlinex);
  22173. if ($this->inxobj) {
  22174. // we are inside an XObject template
  22175. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  22176. if (isset($opentagpos)) {
  22177. $midpos = $opentagpos;
  22178. } else {
  22179. $midpos = 0;
  22180. }
  22181. if ($midpos > 0) {
  22182. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  22183. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  22184. } else {
  22185. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  22186. $pend = '';
  22187. }
  22188. } else {
  22189. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  22190. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  22191. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  22192. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  22193. } elseif (isset($opentagpos)) {
  22194. $midpos = $opentagpos;
  22195. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  22196. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  22197. $midpos = $this->footerpos[$startlinepage];
  22198. } else {
  22199. $midpos = 0;
  22200. }
  22201. if ($midpos > 0) {
  22202. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  22203. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  22204. } else {
  22205. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  22206. $pend = '';
  22207. }
  22208. }
  22209. if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  22210. // calculate shifting amount
  22211. $tw = $w;
  22212. if ($this->lMargin != $prevlMargin) {
  22213. $tw += ($prevlMargin - $this->lMargin);
  22214. }
  22215. if ($this->rMargin != $prevrMargin) {
  22216. $tw += ($prevrMargin - $this->rMargin);
  22217. }
  22218. $one_space_width = $this->GetStringWidth(chr(32));
  22219. $no = 0; // number of spaces on a line contained on a single block
  22220. if ($this->isRTLTextDir()) { // RTL
  22221. // remove left space if exist
  22222. $pos1 = $this->revstrpos($pmid, '[(');
  22223. if ($pos1 > 0) {
  22224. $pos1 = intval($pos1);
  22225. if ($this->isUnicodeFont()) {
  22226. $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32)));
  22227. $spacelen = 2;
  22228. } else {
  22229. $pos2 = intval($this->revstrpos($pmid, '[('.chr(32)));
  22230. $spacelen = 1;
  22231. }
  22232. if ($pos1 == $pos2) {
  22233. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  22234. if (substr($pmid, $pos1, 4) == '[()]') {
  22235. $linew -= $one_space_width;
  22236. } elseif ($pos1 == strpos($pmid, '[(')) {
  22237. $no = 1;
  22238. }
  22239. }
  22240. }
  22241. } else { // LTR
  22242. // remove right space if exist
  22243. $pos1 = $this->revstrpos($pmid, ')]');
  22244. if ($pos1 > 0) {
  22245. $pos1 = intval($pos1);
  22246. if ($this->isUnicodeFont()) {
  22247. $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  22248. $spacelen = 2;
  22249. } else {
  22250. $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1;
  22251. $spacelen = 1;
  22252. }
  22253. if ($pos1 == $pos2) {
  22254. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  22255. $linew -= $one_space_width;
  22256. }
  22257. }
  22258. }
  22259. $mdiff = ($tw - $linew);
  22260. if ($plalign == 'C') {
  22261. if ($this->rtl) {
  22262. $t_x = -($mdiff / 2);
  22263. } else {
  22264. $t_x = ($mdiff / 2);
  22265. }
  22266. } elseif ($plalign == 'R') {
  22267. // right alignment on LTR document
  22268. $t_x = $mdiff;
  22269. } elseif ($plalign == 'L') {
  22270. // left alignment on RTL document
  22271. $t_x = -$mdiff;
  22272. }
  22273. } // end if startlinex
  22274. if (($t_x != 0) OR ($yshift < 0)) {
  22275. // shift the line
  22276. $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
  22277. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  22278. $endlinepos = strlen($pstart);
  22279. if ($this->inxobj) {
  22280. // we are inside an XObject template
  22281. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  22282. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  22283. if ($pak >= $pask) {
  22284. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  22285. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  22286. }
  22287. }
  22288. } else {
  22289. $this->setPageBuffer($startlinepage, $pstart.$pend);
  22290. // shift the annotations and links
  22291. if (isset($this->PageAnnots[$this->page])) {
  22292. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  22293. if ($pak >= $pask) {
  22294. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  22295. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  22296. }
  22297. }
  22298. }
  22299. }
  22300. $this->y -= $yshift;
  22301. $yshift = 0;
  22302. }
  22303. }
  22304. // restore previous values
  22305. $this->setGraphicVars($gvars);
  22306. if ($this->num_columns > 1) {
  22307. $this->selectColumn();
  22308. } elseif ($this->page > $prevPage) {
  22309. $this->lMargin = $this->pagedim[$this->page]['olm'];
  22310. $this->rMargin = $this->pagedim[$this->page]['orm'];
  22311. }
  22312. // restore previous list state
  22313. $this->cell_height_ratio = $prev_cell_height_ratio;
  22314. $this->listnum = $prev_listnum;
  22315. $this->listordered = $prev_listordered;
  22316. $this->listcount = $prev_listcount;
  22317. $this->lispacer = $prev_lispacer;
  22318. if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
  22319. $this->Ln($this->lasth);
  22320. if ($this->y < $maxbottomliney) {
  22321. $this->y = $maxbottomliney;
  22322. }
  22323. }
  22324. unset($dom);
  22325. }
  22326. /**
  22327. * Process opening tags.
  22328. * @param $dom (array) html dom array
  22329. * @param $key (int) current element id
  22330. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  22331. * @return $dom array
  22332. * @protected
  22333. */
  22334. protected function openHTMLTagHandler($dom, $key, $cell) {
  22335. $tag = $dom[$key];
  22336. $parent = $dom[($dom[$key]['parent'])];
  22337. $firsttag = ($key == 1);
  22338. // check for text direction attribute
  22339. if (isset($tag['dir'])) {
  22340. $this->setTempRTL($tag['dir']);
  22341. } else {
  22342. $this->tmprtl = false;
  22343. }
  22344. if ($tag['block']) {
  22345. $hbz = 0; // distance from y to line bottom
  22346. $hb = 0; // vertical space between block tags
  22347. // calculate vertical space for block tags
  22348. if (isset($this->tagvspaces[$tag['value']][0]['h']) AND ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
  22349. $cur_h = $this->tagvspaces[$tag['value']][0]['h'];
  22350. } elseif (isset($tag['fontsize'])) {
  22351. $cur_h = ($tag['fontsize'] / $this->k) * $this->cell_height_ratio;
  22352. } else {
  22353. $cur_h = $this->FontSize * $this->cell_height_ratio;
  22354. }
  22355. if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
  22356. $n = $this->tagvspaces[$tag['value']][0]['n'];
  22357. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  22358. $n = 0.6;
  22359. } else {
  22360. $n = 1;
  22361. }
  22362. if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br')))) {
  22363. $hb = 0;
  22364. } else {
  22365. $hb = ($n * $cur_h);
  22366. }
  22367. if (($this->htmlvspace <= 0) AND ($n > 0)) {
  22368. if (isset($parent['fontsize'])) {
  22369. $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  22370. } else {
  22371. $hbz = $this->FontSize * $this->cell_height_ratio;
  22372. }
  22373. }
  22374. }
  22375. // Opening tag
  22376. switch($tag['value']) {
  22377. case 'table': {
  22378. $cp = 0;
  22379. $cs = 0;
  22380. $dom[$key]['rowspans'] = array();
  22381. if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
  22382. // set table header
  22383. if (!$this->empty_string($dom[$key]['thead'])) {
  22384. // set table header
  22385. $this->thead = $dom[$key]['thead'];
  22386. if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
  22387. $this->theadMargins = array();
  22388. $this->theadMargins['cell_padding'] = $this->cell_padding;
  22389. $this->theadMargins['lmargin'] = $this->lMargin;
  22390. $this->theadMargins['rmargin'] = $this->rMargin;
  22391. $this->theadMargins['page'] = $this->page;
  22392. $this->theadMargins['cell'] = $cell;
  22393. }
  22394. }
  22395. }
  22396. // store current margins and page
  22397. $dom[$key]['old_cell_padding'] = $this->cell_padding;
  22398. if (isset($tag['attribute']['cellpadding'])) {
  22399. $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
  22400. $this->SetCellPadding($pad);
  22401. } elseif (isset($tag['padding'])) {
  22402. $this->cell_padding = $tag['padding'];
  22403. }
  22404. if (isset($tag['attribute']['cellspacing'])) {
  22405. $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  22406. } elseif (isset($tag['border-spacing'])) {
  22407. $cs = $tag['border-spacing']['V'];
  22408. }
  22409. $prev_y = $this->y;
  22410. if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
  22411. $this->inthead = true;
  22412. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  22413. $this->checkPageBreak($this->PageBreakTrigger + 1);
  22414. }
  22415. break;
  22416. }
  22417. case 'tr': {
  22418. // array of columns positions
  22419. $dom[$key]['cellpos'] = array();
  22420. break;
  22421. }
  22422. case 'hr': {
  22423. if ((isset($tag['height'])) AND ($tag['height'] != '')) {
  22424. $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
  22425. } else {
  22426. $hrHeight = $this->GetLineWidth();
  22427. }
  22428. $this->addHTMLVertSpace($hbz, ($hrHeight / 2), $cell, $firsttag);
  22429. $x = $this->GetX();
  22430. $y = $this->GetY();
  22431. $wtmp = $this->w - $this->lMargin - $this->rMargin;
  22432. if ($cell) {
  22433. $wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  22434. }
  22435. if ((isset($tag['width'])) AND ($tag['width'] != '')) {
  22436. $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
  22437. } else {
  22438. $hrWidth = $wtmp;
  22439. }
  22440. $prevlinewidth = $this->GetLineWidth();
  22441. $this->SetLineWidth($hrHeight);
  22442. $this->Line($x, $y, $x + $hrWidth, $y);
  22443. $this->SetLineWidth($prevlinewidth);
  22444. $this->addHTMLVertSpace(($hrHeight / 2), 0, $cell, !isset($dom[($key + 1)]));
  22445. break;
  22446. }
  22447. case 'a': {
  22448. if (array_key_exists('href', $tag['attribute'])) {
  22449. $this->HREF['url'] = $tag['attribute']['href'];
  22450. }
  22451. break;
  22452. }
  22453. case 'img': {
  22454. if (isset($tag['attribute']['src'])) {
  22455. if ($tag['attribute']['src']{0} === '@') {
  22456. // data stream
  22457. $tag['attribute']['src'] = '@'.base64_decode(substr($tag['attribute']['src'], 1));
  22458. $type = '';
  22459. } else {
  22460. // check for images without protocol
  22461. if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
  22462. $tag['attribute']['src'] = 'http:'.$tag['attribute']['src'];
  22463. }
  22464. // replace relative path with real server path
  22465. if (($tag['attribute']['src'][0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  22466. $findroot = strpos($tag['attribute']['src'], $_SERVER['DOCUMENT_ROOT']);
  22467. if (($findroot === false) OR ($findroot > 1)) {
  22468. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  22469. $tag['attribute']['src'] = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$tag['attribute']['src'];
  22470. } else {
  22471. $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
  22472. }
  22473. }
  22474. }
  22475. $tag['attribute']['src'] = htmlspecialchars_decode(urldecode($tag['attribute']['src']));
  22476. $type = $this->getImageFileType($tag['attribute']['src']);
  22477. $testscrtype = @parse_url($tag['attribute']['src']);
  22478. if (!isset($testscrtype['query']) OR empty($testscrtype['query'])) {
  22479. // convert URL to server path
  22480. $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
  22481. }
  22482. }
  22483. if (!isset($tag['width'])) {
  22484. $tag['width'] = 0;
  22485. }
  22486. if (!isset($tag['height'])) {
  22487. $tag['height'] = 0;
  22488. }
  22489. //if (!isset($tag['attribute']['align'])) {
  22490. // the only alignment supported is "bottom"
  22491. // further development is required for other modes.
  22492. $tag['attribute']['align'] = 'bottom';
  22493. //}
  22494. switch($tag['attribute']['align']) {
  22495. case 'top': {
  22496. $align = 'T';
  22497. break;
  22498. }
  22499. case 'middle': {
  22500. $align = 'M';
  22501. break;
  22502. }
  22503. case 'bottom': {
  22504. $align = 'B';
  22505. break;
  22506. }
  22507. default: {
  22508. $align = 'B';
  22509. break;
  22510. }
  22511. }
  22512. $prevy = $this->y;
  22513. $xpos = $this->x;
  22514. $imglink = '';
  22515. if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
  22516. $imglink = $this->HREF['url'];
  22517. if ($imglink{0} == '#') {
  22518. // convert url to internal link
  22519. $lnkdata = explode(',', $imglink);
  22520. if (isset($lnkdata[0])) {
  22521. $page = intval(substr($lnkdata[0], 1));
  22522. if (empty($page) OR ($page <= 0)) {
  22523. $page = $this->page;
  22524. }
  22525. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  22526. $lnky = floatval($lnkdata[1]);
  22527. } else {
  22528. $lnky = 0;
  22529. }
  22530. $imglink = $this->AddLink();
  22531. $this->SetLink($imglink, $lnky, $page);
  22532. }
  22533. }
  22534. }
  22535. $border = 0;
  22536. if (isset($tag['border']) AND !empty($tag['border'])) {
  22537. // currently only support 1 (frame) or a combination of 'LTRB'
  22538. $border = $tag['border'];
  22539. }
  22540. $iw = '';
  22541. if (isset($tag['width'])) {
  22542. $iw = $this->getHTMLUnitToUnits($tag['width'], 1, 'px', false);
  22543. }
  22544. $ih = '';
  22545. if (isset($tag['height'])) {
  22546. $ih = $this->getHTMLUnitToUnits($tag['height'], 1, 'px', false);
  22547. }
  22548. if (($type == 'eps') OR ($type == 'ai')) {
  22549. $this->ImageEps($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
  22550. } elseif ($type == 'svg') {
  22551. $this->ImageSVG($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
  22552. } else {
  22553. $this->Image($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
  22554. }
  22555. switch($align) {
  22556. case 'T': {
  22557. $this->y = $prevy;
  22558. break;
  22559. }
  22560. case 'M': {
  22561. $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
  22562. break;
  22563. }
  22564. case 'B': {
  22565. $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
  22566. break;
  22567. }
  22568. }
  22569. }
  22570. break;
  22571. }
  22572. case 'dl': {
  22573. ++$this->listnum;
  22574. if ($this->listnum == 1) {
  22575. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22576. } else {
  22577. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  22578. }
  22579. break;
  22580. }
  22581. case 'dt': {
  22582. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22583. break;
  22584. }
  22585. case 'dd': {
  22586. if ($this->rtl) {
  22587. $this->rMargin += $this->listindent;
  22588. } else {
  22589. $this->lMargin += $this->listindent;
  22590. }
  22591. ++$this->listindentlevel;
  22592. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22593. break;
  22594. }
  22595. case 'ul':
  22596. case 'ol': {
  22597. ++$this->listnum;
  22598. if ($tag['value'] == 'ol') {
  22599. $this->listordered[$this->listnum] = true;
  22600. } else {
  22601. $this->listordered[$this->listnum] = false;
  22602. }
  22603. if (isset($tag['attribute']['start'])) {
  22604. $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
  22605. } else {
  22606. $this->listcount[$this->listnum] = 0;
  22607. }
  22608. if ($this->rtl) {
  22609. $this->rMargin += $this->listindent;
  22610. $this->x -= $this->listindent;
  22611. } else {
  22612. $this->lMargin += $this->listindent;
  22613. $this->x += $this->listindent;
  22614. }
  22615. ++$this->listindentlevel;
  22616. if ($this->listnum == 1) {
  22617. if ($key > 1) {
  22618. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22619. }
  22620. } else {
  22621. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  22622. }
  22623. break;
  22624. }
  22625. case 'li': {
  22626. if ($key > 2) {
  22627. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22628. }
  22629. if ($this->listordered[$this->listnum]) {
  22630. // ordered item
  22631. if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
  22632. $this->lispacer = $parent['attribute']['type'];
  22633. } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
  22634. $this->lispacer = $parent['listtype'];
  22635. } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
  22636. $this->lispacer = $this->lisymbol;
  22637. } else {
  22638. $this->lispacer = '#';
  22639. }
  22640. ++$this->listcount[$this->listnum];
  22641. if (isset($tag['attribute']['value'])) {
  22642. $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
  22643. }
  22644. } else {
  22645. // unordered item
  22646. if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
  22647. $this->lispacer = $parent['attribute']['type'];
  22648. } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
  22649. $this->lispacer = $parent['listtype'];
  22650. } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
  22651. $this->lispacer = $this->lisymbol;
  22652. } else {
  22653. $this->lispacer = '!';
  22654. }
  22655. }
  22656. break;
  22657. }
  22658. case 'blockquote': {
  22659. if ($this->rtl) {
  22660. $this->rMargin += $this->listindent;
  22661. } else {
  22662. $this->lMargin += $this->listindent;
  22663. }
  22664. ++$this->listindentlevel;
  22665. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22666. break;
  22667. }
  22668. case 'br': {
  22669. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22670. break;
  22671. }
  22672. case 'div': {
  22673. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22674. break;
  22675. }
  22676. case 'p': {
  22677. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22678. break;
  22679. }
  22680. case 'pre': {
  22681. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22682. $this->premode = true;
  22683. break;
  22684. }
  22685. case 'sup': {
  22686. $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
  22687. break;
  22688. }
  22689. case 'sub': {
  22690. $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
  22691. break;
  22692. }
  22693. case 'h1':
  22694. case 'h2':
  22695. case 'h3':
  22696. case 'h4':
  22697. case 'h5':
  22698. case 'h6': {
  22699. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  22700. break;
  22701. }
  22702. // Form fields (since 4.8.000 - 2009-09-07)
  22703. case 'form': {
  22704. if (isset($tag['attribute']['action'])) {
  22705. $this->form_action = $tag['attribute']['action'];
  22706. } else {
  22707. $this->form_action = K_PATH_URL.$_SERVER['SCRIPT_NAME'];
  22708. }
  22709. if (isset($tag['attribute']['enctype'])) {
  22710. $this->form_enctype = $tag['attribute']['enctype'];
  22711. } else {
  22712. $this->form_enctype = 'application/x-www-form-urlencoded';
  22713. }
  22714. if (isset($tag['attribute']['method'])) {
  22715. $this->form_mode = $tag['attribute']['method'];
  22716. } else {
  22717. $this->form_mode = 'post';
  22718. }
  22719. break;
  22720. }
  22721. case 'input': {
  22722. if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
  22723. $name = $tag['attribute']['name'];
  22724. } else {
  22725. break;
  22726. }
  22727. $prop = array();
  22728. $opt = array();
  22729. if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) {
  22730. $prop['readonly'] = true;
  22731. }
  22732. if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) {
  22733. $value = $tag['attribute']['value'];
  22734. }
  22735. if (isset($tag['attribute']['maxlength']) AND !$this->empty_string($tag['attribute']['maxlength'])) {
  22736. $opt['maxlen'] = intval($tag['attribute']['value']);
  22737. }
  22738. $h = $this->FontSize * $this->cell_height_ratio;
  22739. if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) {
  22740. $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
  22741. } else {
  22742. $w = $h;
  22743. }
  22744. if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
  22745. $checked = true;
  22746. } else {
  22747. $checked = false;
  22748. }
  22749. if (isset($tag['align'])) {
  22750. switch ($tag['align']) {
  22751. case 'C': {
  22752. $opt['q'] = 1;
  22753. break;
  22754. }
  22755. case 'R': {
  22756. $opt['q'] = 2;
  22757. break;
  22758. }
  22759. case 'L':
  22760. default: {
  22761. break;
  22762. }
  22763. }
  22764. }
  22765. switch ($tag['attribute']['type']) {
  22766. case 'text': {
  22767. if (isset($value)) {
  22768. $opt['v'] = $value;
  22769. }
  22770. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  22771. break;
  22772. }
  22773. case 'password': {
  22774. if (isset($value)) {
  22775. $opt['v'] = $value;
  22776. }
  22777. $prop['password'] = 'true';
  22778. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  22779. break;
  22780. }
  22781. case 'checkbox': {
  22782. $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
  22783. break;
  22784. }
  22785. case 'radio': {
  22786. $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
  22787. break;
  22788. }
  22789. case 'submit': {
  22790. $w = $this->GetStringWidth($value) * 1.5;
  22791. $h *= 1.6;
  22792. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  22793. $action = array();
  22794. $action['S'] = 'SubmitForm';
  22795. $action['F'] = $this->form_action;
  22796. if ($this->form_enctype != 'FDF') {
  22797. $action['Flags'] = array('ExportFormat');
  22798. }
  22799. if ($this->form_mode == 'get') {
  22800. $action['Flags'] = array('GetMethod');
  22801. }
  22802. $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
  22803. break;
  22804. }
  22805. case 'reset': {
  22806. $w = $this->GetStringWidth($value) * 1.5;
  22807. $h *= 1.6;
  22808. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  22809. $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
  22810. break;
  22811. }
  22812. case 'file': {
  22813. $prop['fileSelect'] = 'true';
  22814. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  22815. if (!isset($value)) {
  22816. $value = '*';
  22817. }
  22818. $w = $this->GetStringWidth($value) * 2;
  22819. $h *= 1.2;
  22820. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  22821. $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
  22822. $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  22823. break;
  22824. }
  22825. case 'hidden': {
  22826. if (isset($value)) {
  22827. $opt['v'] = $value;
  22828. }
  22829. $opt['f'] = array('invisible', 'hidden');
  22830. $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
  22831. break;
  22832. }
  22833. case 'image': {
  22834. // THIS TYPE MUST BE FIXED
  22835. if (isset($tag['attribute']['src']) AND !$this->empty_string($tag['attribute']['src'])) {
  22836. $img = $tag['attribute']['src'];
  22837. } else {
  22838. break;
  22839. }
  22840. $value = 'img';
  22841. //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
  22842. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  22843. $jsaction = $tag['attribute']['onclick'];
  22844. } else {
  22845. $jsaction = '';
  22846. }
  22847. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  22848. break;
  22849. }
  22850. case 'button': {
  22851. $w = $this->GetStringWidth($value) * 1.5;
  22852. $h *= 1.6;
  22853. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  22854. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  22855. $jsaction = $tag['attribute']['onclick'];
  22856. } else {
  22857. $jsaction = '';
  22858. }
  22859. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  22860. break;
  22861. }
  22862. }
  22863. break;
  22864. }
  22865. case 'textarea': {
  22866. $prop = array();
  22867. $opt = array();
  22868. if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) {
  22869. $prop['readonly'] = true;
  22870. }
  22871. if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
  22872. $name = $tag['attribute']['name'];
  22873. } else {
  22874. break;
  22875. }
  22876. if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) {
  22877. $opt['v'] = $tag['attribute']['value'];
  22878. }
  22879. if (isset($tag['attribute']['cols']) AND !$this->empty_string($tag['attribute']['cols'])) {
  22880. $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
  22881. } else {
  22882. $w = 40;
  22883. }
  22884. if (isset($tag['attribute']['rows']) AND !$this->empty_string($tag['attribute']['rows'])) {
  22885. $h = intval($tag['attribute']['rows']) * $this->FontSize * $this->cell_height_ratio;
  22886. } else {
  22887. $h = 10;
  22888. }
  22889. $prop['multiline'] = 'true';
  22890. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  22891. break;
  22892. }
  22893. case 'select': {
  22894. $h = $this->FontSize * $this->cell_height_ratio;
  22895. if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) {
  22896. $h *= ($tag['attribute']['size'] + 1);
  22897. }
  22898. $prop = array();
  22899. $opt = array();
  22900. if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
  22901. $name = $tag['attribute']['name'];
  22902. } else {
  22903. break;
  22904. }
  22905. $w = 0;
  22906. if (isset($tag['attribute']['opt']) AND !$this->empty_string($tag['attribute']['opt'])) {
  22907. $options = explode('#!NwL!#', $tag['attribute']['opt']);
  22908. $values = array();
  22909. foreach ($options as $val) {
  22910. if (strpos($val, '#!TaB!#') !== false) {
  22911. $opts = explode('#!TaB!#', $val);
  22912. $values[] = $opts;
  22913. $w = max($w, $this->GetStringWidth($opts[1]));
  22914. } else {
  22915. $values[] = $val;
  22916. $w = max($w, $this->GetStringWidth($val));
  22917. }
  22918. }
  22919. } else {
  22920. break;
  22921. }
  22922. $w *= 2;
  22923. if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
  22924. $prop['multipleSelection'] = 'true';
  22925. $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  22926. } else {
  22927. $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  22928. }
  22929. break;
  22930. }
  22931. case 'tcpdf': {
  22932. if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
  22933. // Special tag used to call TCPDF methods
  22934. if (isset($tag['attribute']['method'])) {
  22935. $tcpdf_method = $tag['attribute']['method'];
  22936. if (method_exists($this, $tcpdf_method)) {
  22937. if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
  22938. $params = unserialize(urldecode($tag['attribute']['params']));
  22939. call_user_func_array(array($this, $tcpdf_method), $params);
  22940. } else {
  22941. $this->$tcpdf_method();
  22942. }
  22943. $this->newline = true;
  22944. }
  22945. }
  22946. }
  22947. break;
  22948. }
  22949. default: {
  22950. break;
  22951. }
  22952. }
  22953. // define tags that support borders and background colors
  22954. $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
  22955. if (in_array($tag['value'], $bordertags)) {
  22956. // set border
  22957. $dom[$key]['borderposition'] = $this->getBorderStartPosition();
  22958. }
  22959. if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
  22960. $pba = $dom[$key]['attribute']['pagebreakafter'];
  22961. // check for pagebreak
  22962. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  22963. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  22964. $this->checkPageBreak($this->PageBreakTrigger + 1);
  22965. }
  22966. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  22967. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  22968. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  22969. $this->checkPageBreak($this->PageBreakTrigger + 1);
  22970. }
  22971. }
  22972. return $dom;
  22973. }
  22974. /**
  22975. * Process closing tags.
  22976. * @param $dom (array) html dom array
  22977. * @param $key (int) current element id
  22978. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  22979. * @param $maxbottomliney (int) maximum y value of current line
  22980. * @return $dom array
  22981. * @protected
  22982. */
  22983. protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
  22984. $tag = $dom[$key];
  22985. $parent = $dom[($dom[$key]['parent'])];
  22986. $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
  22987. $in_table_head = false;
  22988. // maximum x position (used to draw borders)
  22989. if ($this->rtl) {
  22990. $xmax = $this->w;
  22991. } else {
  22992. $xmax = 0;
  22993. }
  22994. if ($tag['block']) {
  22995. $hbz = 0; // distance from y to line bottom
  22996. $hb = 0; // vertical space between block tags
  22997. // calculate vertical space for block tags
  22998. if (isset($this->tagvspaces[$tag['value']][1]['h']) AND ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  22999. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  23000. } elseif (isset($parent['fontsize'])) {
  23001. $pre_h = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  23002. } else {
  23003. $pre_h = $this->FontSize * $this->cell_height_ratio;
  23004. }
  23005. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  23006. $n = $this->tagvspaces[$tag['value']][1]['n'];
  23007. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  23008. $n = 0.6;
  23009. } else {
  23010. $n = 1;
  23011. }
  23012. if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
  23013. $hb = 0;
  23014. } else {
  23015. $hb = ($n * $pre_h);
  23016. }
  23017. if ($maxbottomliney > $this->PageBreakTrigger) {
  23018. $hbz = ($this->FontSize * $this->cell_height_ratio);
  23019. } elseif ($this->y < $maxbottomliney) {
  23020. $hbz = ($maxbottomliney - $this->y);
  23021. }
  23022. }
  23023. // Closing tag
  23024. switch($tag['value']) {
  23025. case 'tr': {
  23026. $table_el = $dom[($dom[$key]['parent'])]['parent'];
  23027. if (!isset($parent['endy'])) {
  23028. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  23029. $parent['endy'] = $this->y;
  23030. }
  23031. if (!isset($parent['endpage'])) {
  23032. $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
  23033. $parent['endpage'] = $this->page;
  23034. }
  23035. if (!isset($parent['endcolumn'])) {
  23036. $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
  23037. $parent['endcolumn'] = $this->current_column;
  23038. }
  23039. // update row-spanned cells
  23040. if (isset($dom[$table_el]['rowspans'])) {
  23041. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  23042. $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
  23043. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  23044. if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
  23045. $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
  23046. } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
  23047. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  23048. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  23049. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  23050. }
  23051. }
  23052. }
  23053. // report new endy and endpage to the rowspanned cells
  23054. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  23055. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  23056. $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
  23057. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  23058. $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
  23059. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  23060. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
  23061. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  23062. }
  23063. }
  23064. // update remaining rowspanned cells
  23065. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  23066. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  23067. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
  23068. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
  23069. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
  23070. }
  23071. }
  23072. }
  23073. $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
  23074. if ($this->num_columns > 1) {
  23075. $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
  23076. }
  23077. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  23078. if (isset($dom[$table_el]['attribute']['cellspacing'])) {
  23079. $this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
  23080. } elseif (isset($dom[$table_el]['border-spacing'])) {
  23081. $this->y += $dom[$table_el]['border-spacing']['V'];
  23082. }
  23083. $this->Ln(0, $cell);
  23084. if ($this->current_column == $parent['startcolumn']) {
  23085. $this->x = $parent['startx'];
  23086. }
  23087. // account for booklet mode
  23088. if ($this->page > $parent['startpage']) {
  23089. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
  23090. $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
  23091. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
  23092. $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
  23093. }
  23094. }
  23095. break;
  23096. }
  23097. case 'tablehead':
  23098. // closing tag used for the thead part
  23099. $in_table_head = true;
  23100. $this->inthead = false;
  23101. case 'table': {
  23102. $table_el = $parent;
  23103. // set default border
  23104. if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
  23105. // set default border
  23106. $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
  23107. } else {
  23108. $border = 0;
  23109. }
  23110. $default_border = $border;
  23111. // fix bottom line alignment of last line before page break
  23112. foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
  23113. // update row-spanned cells
  23114. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  23115. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  23116. if ($trwsp['trid'] == $trkey) {
  23117. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
  23118. }
  23119. if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
  23120. $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
  23121. }
  23122. }
  23123. }
  23124. if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
  23125. $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
  23126. $dom[$prevtrkey]['endy'] = $pgendy;
  23127. // update row-spanned cells
  23128. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  23129. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  23130. if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] > 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
  23131. $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
  23132. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
  23133. }
  23134. }
  23135. }
  23136. }
  23137. $prevtrkey = $trkey;
  23138. $table_el = $dom[($dom[$key]['parent'])];
  23139. }
  23140. // for each row
  23141. if (count($table_el['trids']) > 0) {
  23142. unset($xmax);
  23143. }
  23144. foreach ($table_el['trids'] as $j => $trkey) {
  23145. $parent = $dom[$trkey];
  23146. if (!isset($xmax)) {
  23147. $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
  23148. }
  23149. // for each cell on the row
  23150. foreach ($parent['cellpos'] as $k => $cellpos) {
  23151. if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
  23152. $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
  23153. $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
  23154. $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
  23155. $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
  23156. $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
  23157. $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
  23158. $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
  23159. } else {
  23160. $endy = $parent['endy'];
  23161. $startpage = $parent['startpage'];
  23162. $endpage = $parent['endpage'];
  23163. $startcolumn = $parent['startcolumn'];
  23164. $endcolumn = $parent['endcolumn'];
  23165. }
  23166. if ($this->num_columns == 0) {
  23167. $this->num_columns = 1;
  23168. }
  23169. if (isset($cellpos['border'])) {
  23170. $border = $cellpos['border'];
  23171. }
  23172. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  23173. $this->SetFillColorArray($cellpos['bgcolor']);
  23174. $fill = true;
  23175. } else {
  23176. $fill = false;
  23177. }
  23178. $x = $cellpos['startx'];
  23179. $y = $parent['starty'];
  23180. $starty = $y;
  23181. $w = abs($cellpos['endx'] - $cellpos['startx']);
  23182. // get border modes
  23183. $border_start = $this->getBorderMode($border, $position='start');
  23184. $border_end = $this->getBorderMode($border, $position='end');
  23185. $border_middle = $this->getBorderMode($border, $position='middle');
  23186. // design borders around HTML cells.
  23187. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  23188. $ccode = '';
  23189. $this->setPage($page);
  23190. if ($this->num_columns < 2) {
  23191. // single-column mode
  23192. $this->x = $x;
  23193. $this->y = $this->tMargin;
  23194. }
  23195. // account for margin changes
  23196. if ($page > $startpage) {
  23197. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  23198. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  23199. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  23200. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  23201. }
  23202. }
  23203. if ($startpage == $endpage) { // single page
  23204. $deltacol = 0;
  23205. $deltath = 0;
  23206. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  23207. $this->selectColumn($column);
  23208. if ($startcolumn == $endcolumn) { // single column
  23209. $cborder = $border;
  23210. $h = $endy - $parent['starty'];
  23211. $this->y = $y;
  23212. $this->x = $x;
  23213. } elseif ($column == $startcolumn) { // first column
  23214. $cborder = $border_start;
  23215. $this->y = $starty;
  23216. $this->x = $x;
  23217. $h = $this->h - $this->y - $this->bMargin;
  23218. if ($this->rtl) {
  23219. $deltacol = $this->x + $this->rMargin - $this->w;
  23220. } else {
  23221. $deltacol = $this->x - $this->lMargin;
  23222. }
  23223. } elseif ($column == $endcolumn) { // end column
  23224. $cborder = $border_end;
  23225. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23226. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23227. }
  23228. $this->x += $deltacol;
  23229. $h = $endy - $this->y;
  23230. } else { // middle column
  23231. $cborder = $border_middle;
  23232. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23233. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23234. }
  23235. $this->x += $deltacol;
  23236. $h = $this->h - $this->y - $this->bMargin;
  23237. }
  23238. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23239. } // end for each column
  23240. } elseif ($page == $startpage) { // first page
  23241. $deltacol = 0;
  23242. $deltath = 0;
  23243. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  23244. $this->selectColumn($column);
  23245. if ($column == $startcolumn) { // first column
  23246. $cborder = $border_start;
  23247. $this->y = $starty;
  23248. $this->x = $x;
  23249. $h = $this->h - $this->y - $this->bMargin;
  23250. if ($this->rtl) {
  23251. $deltacol = $this->x + $this->rMargin - $this->w;
  23252. } else {
  23253. $deltacol = $this->x - $this->lMargin;
  23254. }
  23255. } else { // middle column
  23256. $cborder = $border_middle;
  23257. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23258. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23259. }
  23260. $this->x += $deltacol;
  23261. $h = $this->h - $this->y - $this->bMargin;
  23262. }
  23263. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23264. } // end for each column
  23265. } elseif ($page == $endpage) { // last page
  23266. $deltacol = 0;
  23267. $deltath = 0;
  23268. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  23269. $this->selectColumn($column);
  23270. if ($column == $endcolumn) { // end column
  23271. $cborder = $border_end;
  23272. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23273. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23274. }
  23275. $this->x += $deltacol;
  23276. $h = $endy - $this->y;
  23277. } else { // middle column
  23278. $cborder = $border_middle;
  23279. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23280. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23281. }
  23282. $this->x += $deltacol;
  23283. $h = $this->h - $this->y - $this->bMargin;
  23284. }
  23285. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23286. } // end for each column
  23287. } else { // middle page
  23288. $deltacol = 0;
  23289. $deltath = 0;
  23290. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  23291. $this->selectColumn($column);
  23292. $cborder = $border_middle;
  23293. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23294. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23295. }
  23296. $this->x += $deltacol;
  23297. $h = $this->h - $this->y - $this->bMargin;
  23298. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23299. } // end for each column
  23300. }
  23301. if ($cborder OR $fill) {
  23302. $offsetlen = strlen($ccode);
  23303. // draw border and fill
  23304. if ($this->inxobj) {
  23305. // we are inside an XObject template
  23306. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  23307. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  23308. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  23309. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  23310. } else {
  23311. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  23312. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  23313. }
  23314. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  23315. $pstart = substr($pagebuff, 0, $pagemark);
  23316. $pend = substr($pagebuff, $pagemark);
  23317. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  23318. } else {
  23319. // draw border and fill
  23320. if (end($this->transfmrk[$this->page]) !== false) {
  23321. $pagemarkkey = key($this->transfmrk[$this->page]);
  23322. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  23323. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  23324. } elseif ($this->InFooter) {
  23325. $pagemark = $this->footerpos[$this->page];
  23326. $this->footerpos[$this->page] += $offsetlen;
  23327. } else {
  23328. $pagemark = $this->intmrk[$this->page];
  23329. $this->intmrk[$this->page] += $offsetlen;
  23330. }
  23331. $pagebuff = $this->getPageBuffer($this->page);
  23332. $pstart = substr($pagebuff, 0, $pagemark);
  23333. $pend = substr($pagebuff, $pagemark);
  23334. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  23335. }
  23336. }
  23337. } // end for each page
  23338. // restore default border
  23339. $border = $default_border;
  23340. } // end for each cell on the row
  23341. if (isset($table_el['attribute']['cellspacing'])) {
  23342. $this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
  23343. } elseif (isset($table_el['border-spacing'])) {
  23344. $this->y += $table_el['border-spacing']['V'];
  23345. }
  23346. $this->Ln(0, $cell);
  23347. $this->x = $parent['startx'];
  23348. if ($endpage > $startpage) {
  23349. if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
  23350. $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
  23351. } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
  23352. $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
  23353. }
  23354. }
  23355. }
  23356. if (!$in_table_head) { // we are not inside a thead section
  23357. $this->cell_padding = $table_el['old_cell_padding'];
  23358. // reset row height
  23359. $this->resetLastH();
  23360. if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
  23361. $plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
  23362. if (($plendiff > 0) AND ($plendiff < 60)) {
  23363. $pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
  23364. if (substr($pagediff, 0, 5) == 'BT /F') {
  23365. // the difference is only a font setting
  23366. $plendiff = 0;
  23367. }
  23368. }
  23369. if ($plendiff == 0) {
  23370. // remove last blank page
  23371. $this->deletePage($this->numpages);
  23372. }
  23373. }
  23374. if (isset($this->theadMargins['top'])) {
  23375. // restore top margin
  23376. $this->tMargin = $this->theadMargins['top'];
  23377. }
  23378. if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
  23379. // reset main table header
  23380. $this->thead = '';
  23381. $this->theadMargins = array();
  23382. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  23383. }
  23384. }
  23385. $parent = $table_el;
  23386. break;
  23387. }
  23388. case 'a': {
  23389. $this->HREF = '';
  23390. break;
  23391. }
  23392. case 'sup': {
  23393. $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
  23394. break;
  23395. }
  23396. case 'sub': {
  23397. $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
  23398. break;
  23399. }
  23400. case 'div': {
  23401. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23402. break;
  23403. }
  23404. case 'blockquote': {
  23405. if ($this->rtl) {
  23406. $this->rMargin -= $this->listindent;
  23407. } else {
  23408. $this->lMargin -= $this->listindent;
  23409. }
  23410. --$this->listindentlevel;
  23411. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23412. break;
  23413. }
  23414. case 'p': {
  23415. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23416. break;
  23417. }
  23418. case 'pre': {
  23419. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23420. $this->premode = false;
  23421. break;
  23422. }
  23423. case 'dl': {
  23424. --$this->listnum;
  23425. if ($this->listnum <= 0) {
  23426. $this->listnum = 0;
  23427. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23428. } else {
  23429. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  23430. }
  23431. $this->resetLastH();
  23432. break;
  23433. }
  23434. case 'dt': {
  23435. $this->lispacer = '';
  23436. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  23437. break;
  23438. }
  23439. case 'dd': {
  23440. $this->lispacer = '';
  23441. if ($this->rtl) {
  23442. $this->rMargin -= $this->listindent;
  23443. } else {
  23444. $this->lMargin -= $this->listindent;
  23445. }
  23446. --$this->listindentlevel;
  23447. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  23448. break;
  23449. }
  23450. case 'ul':
  23451. case 'ol': {
  23452. --$this->listnum;
  23453. $this->lispacer = '';
  23454. if ($this->rtl) {
  23455. $this->rMargin -= $this->listindent;
  23456. } else {
  23457. $this->lMargin -= $this->listindent;
  23458. }
  23459. --$this->listindentlevel;
  23460. if ($this->listnum <= 0) {
  23461. $this->listnum = 0;
  23462. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23463. } else {
  23464. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  23465. }
  23466. $this->resetLastH();
  23467. break;
  23468. }
  23469. case 'li': {
  23470. $this->lispacer = '';
  23471. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  23472. break;
  23473. }
  23474. case 'h1':
  23475. case 'h2':
  23476. case 'h3':
  23477. case 'h4':
  23478. case 'h5':
  23479. case 'h6': {
  23480. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23481. break;
  23482. }
  23483. // Form fields (since 4.8.000 - 2009-09-07)
  23484. case 'form': {
  23485. $this->form_action = '';
  23486. $this->form_enctype = 'application/x-www-form-urlencoded';
  23487. break;
  23488. }
  23489. default : {
  23490. break;
  23491. }
  23492. }
  23493. // draw border and background (if any)
  23494. $this->drawHTMLTagBorder($parent, $xmax);
  23495. if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
  23496. $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
  23497. // check for pagebreak
  23498. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  23499. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  23500. $this->checkPageBreak($this->PageBreakTrigger + 1);
  23501. }
  23502. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  23503. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  23504. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  23505. $this->checkPageBreak($this->PageBreakTrigger + 1);
  23506. }
  23507. }
  23508. $this->tmprtl = false;
  23509. return $dom;
  23510. }
  23511. /**
  23512. * Add vertical spaces if needed.
  23513. * @param $hbz (string) Distance between current y and line bottom.
  23514. * @param $hb (string) The height of the break.
  23515. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  23516. * @param $firsttag (boolean) set to true when the tag is the first.
  23517. * @param $lasttag (boolean) set to true when the tag is the last.
  23518. * @protected
  23519. */
  23520. protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
  23521. if ($firsttag) {
  23522. $this->Ln(0, $cell);
  23523. $this->htmlvspace = 0;
  23524. return;
  23525. }
  23526. if ($lasttag) {
  23527. $this->Ln($hbz, $cell);
  23528. $this->htmlvspace = 0;
  23529. return;
  23530. }
  23531. if ($hb < $this->htmlvspace) {
  23532. $hd = 0;
  23533. } else {
  23534. $hd = $hb - $this->htmlvspace;
  23535. $this->htmlvspace = $hb;
  23536. }
  23537. $this->Ln(($hbz + $hd), $cell);
  23538. }
  23539. /**
  23540. * Return the starting coordinates to draw an html border
  23541. * @return array containing top-left border coordinates
  23542. * @protected
  23543. * @since 5.7.000 (2010-08-03)
  23544. */
  23545. protected function getBorderStartPosition() {
  23546. if ($this->rtl) {
  23547. $xmax = $this->lMargin;
  23548. } else {
  23549. $xmax = $this->w - $this->rMargin;
  23550. }
  23551. return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
  23552. }
  23553. /**
  23554. * Draw an HTML block border and fill
  23555. * @param $tag (array) array of tag properties.
  23556. * @param $xmax (int) end X coordinate for border.
  23557. * @protected
  23558. * @since 5.7.000 (2010-08-03)
  23559. */
  23560. protected function drawHTMLTagBorder($tag, $xmax) {
  23561. if (!isset($tag['borderposition'])) {
  23562. // nothing to draw
  23563. return;
  23564. }
  23565. $prev_x = $this->x;
  23566. $prev_y = $this->y;
  23567. $prev_lasth = $this->lasth;
  23568. $border = 0;
  23569. $fill = false;
  23570. $this->lasth = 0;
  23571. if (isset($tag['border']) AND !empty($tag['border'])) {
  23572. // get border style
  23573. $border = $tag['border'];
  23574. if (!$this->empty_string($this->thead) AND (!$this->inthead)) {
  23575. // border for table header
  23576. $border = $this->getBorderMode($border, $position='middle');
  23577. }
  23578. }
  23579. if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
  23580. // get background color
  23581. $old_bgcolor = $this->bgcolor;
  23582. $this->SetFillColorArray($tag['bgcolor']);
  23583. $fill = true;
  23584. }
  23585. if (!$border AND !$fill) {
  23586. // nothing to draw
  23587. return;
  23588. }
  23589. if (isset($tag['attribute']['cellspacing'])) {
  23590. $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  23591. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  23592. } elseif (isset($tag['border-spacing'])) {
  23593. $cellspacing = $tag['border-spacing'];
  23594. } else {
  23595. $cellspacing = array('H' => 0, 'V' => 0);
  23596. }
  23597. if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
  23598. // draw the border externally respect the sqare edge.
  23599. $border['mode'] = 'ext';
  23600. }
  23601. if ($this->rtl) {
  23602. if ($xmax >= $tag['borderposition']['x']) {
  23603. $xmax = $tag['borderposition']['xmax'];
  23604. }
  23605. $w = ($tag['borderposition']['x'] - $xmax);
  23606. } else {
  23607. if ($xmax <= $tag['borderposition']['x']) {
  23608. $xmax = $tag['borderposition']['xmax'];
  23609. }
  23610. $w = ($xmax - $tag['borderposition']['x']);
  23611. }
  23612. if ($w <= 0) {
  23613. return;
  23614. }
  23615. $w += $cellspacing['H'];
  23616. $startpage = $tag['borderposition']['page'];
  23617. $startcolumn = $tag['borderposition']['column'];
  23618. $x = $tag['borderposition']['x'];
  23619. $y = $tag['borderposition']['y'];
  23620. $endpage = $this->page;
  23621. $starty = $tag['borderposition']['y'] - $cellspacing['V'];
  23622. $currentY = $this->y;
  23623. $this->x = $x;
  23624. // get latest column
  23625. $endcolumn = $this->current_column;
  23626. if ($this->num_columns == 0) {
  23627. $this->num_columns = 1;
  23628. }
  23629. // get border modes
  23630. $border_start = $this->getBorderMode($border, $position='start');
  23631. $border_end = $this->getBorderMode($border, $position='end');
  23632. $border_middle = $this->getBorderMode($border, $position='middle');
  23633. // temporary disable page regions
  23634. $temp_page_regions = $this->page_regions;
  23635. $this->page_regions = array();
  23636. // design borders around HTML cells.
  23637. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  23638. $ccode = '';
  23639. $this->setPage($page);
  23640. if ($this->num_columns < 2) {
  23641. // single-column mode
  23642. $this->x = $x;
  23643. $this->y = $this->tMargin;
  23644. }
  23645. // account for margin changes
  23646. if ($page > $startpage) {
  23647. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  23648. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  23649. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  23650. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  23651. }
  23652. }
  23653. if ($startpage == $endpage) {
  23654. // single page
  23655. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  23656. $this->selectColumn($column);
  23657. if ($startcolumn == $endcolumn) { // single column
  23658. $cborder = $border;
  23659. $h = ($currentY - $y) + $cellspacing['V'];
  23660. $this->y = $starty;
  23661. } elseif ($column == $startcolumn) { // first column
  23662. $cborder = $border_start;
  23663. $this->y = $starty;
  23664. $h = $this->h - $this->y - $this->bMargin;
  23665. } elseif ($column == $endcolumn) { // end column
  23666. $cborder = $border_end;
  23667. $h = $currentY - $this->y;
  23668. } else { // middle column
  23669. $cborder = $border_middle;
  23670. $h = $this->h - $this->y - $this->bMargin;
  23671. }
  23672. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23673. } // end for each column
  23674. } elseif ($page == $startpage) { // first page
  23675. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  23676. $this->selectColumn($column);
  23677. if ($column == $startcolumn) { // first column
  23678. $cborder = $border_start;
  23679. $this->y = $starty;
  23680. $h = $this->h - $this->y - $this->bMargin;
  23681. } else { // middle column
  23682. $cborder = $border_middle;
  23683. $h = $this->h - $this->y - $this->bMargin;
  23684. }
  23685. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23686. } // end for each column
  23687. } elseif ($page == $endpage) { // last page
  23688. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  23689. $this->selectColumn($column);
  23690. if ($column == $endcolumn) {
  23691. // end column
  23692. $cborder = $border_end;
  23693. $h = $currentY - $this->y;
  23694. } else {
  23695. // middle column
  23696. $cborder = $border_middle;
  23697. $h = $this->h - $this->y - $this->bMargin;
  23698. }
  23699. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23700. } // end for each column
  23701. } else { // middle page
  23702. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  23703. $this->selectColumn($column);
  23704. $cborder = $border_middle;
  23705. $h = $this->h - $this->y - $this->bMargin;
  23706. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23707. } // end for each column
  23708. }
  23709. if ($cborder OR $fill) {
  23710. $offsetlen = strlen($ccode);
  23711. // draw border and fill
  23712. if ($this->inxobj) {
  23713. // we are inside an XObject template
  23714. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  23715. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  23716. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  23717. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  23718. } else {
  23719. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  23720. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  23721. }
  23722. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  23723. $pstart = substr($pagebuff, 0, $pagemark);
  23724. $pend = substr($pagebuff, $pagemark);
  23725. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  23726. } else {
  23727. if (end($this->transfmrk[$this->page]) !== false) {
  23728. $pagemarkkey = key($this->transfmrk[$this->page]);
  23729. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  23730. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  23731. } elseif ($this->InFooter) {
  23732. $pagemark = $this->footerpos[$this->page];
  23733. $this->footerpos[$this->page] += $offsetlen;
  23734. } else {
  23735. $pagemark = $this->intmrk[$this->page];
  23736. $this->intmrk[$this->page] += $offsetlen;
  23737. }
  23738. $pagebuff = $this->getPageBuffer($this->page);
  23739. $pstart = substr($pagebuff, 0, $this->bordermrk[$this->page]);
  23740. $pend = substr($pagebuff, $this->bordermrk[$this->page]);
  23741. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  23742. $this->bordermrk[$this->page] += $offsetlen;
  23743. $this->cntmrk[$this->page] += $offsetlen;
  23744. }
  23745. }
  23746. } // end for each page
  23747. // restore page regions
  23748. $this->page_regions = $temp_page_regions;
  23749. if (isset($old_bgcolor)) {
  23750. // restore background color
  23751. $this->SetFillColorArray($old_bgcolor);
  23752. }
  23753. // restore pointer position
  23754. $this->x = $prev_x;
  23755. $this->y = $prev_y;
  23756. $this->lasth = $prev_lasth;
  23757. }
  23758. /**
  23759. * Set the default bullet to be used as LI bullet symbol
  23760. * @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')
  23761. * @public
  23762. * @since 4.0.028 (2008-09-26)
  23763. */
  23764. public function setLIsymbol($symbol='!') {
  23765. // check for custom image symbol
  23766. if (substr($symbol, 0, 4) == 'img|') {
  23767. $this->lisymbol = $symbol;
  23768. return;
  23769. }
  23770. $symbol = strtolower($symbol);
  23771. switch ($symbol) {
  23772. case '!' :
  23773. case '#' :
  23774. case 'disc' :
  23775. case 'circle' :
  23776. case 'square' :
  23777. case '1':
  23778. case 'decimal':
  23779. case 'decimal-leading-zero':
  23780. case 'i':
  23781. case 'lower-roman':
  23782. case 'I':
  23783. case 'upper-roman':
  23784. case 'a':
  23785. case 'lower-alpha':
  23786. case 'lower-latin':
  23787. case 'A':
  23788. case 'upper-alpha':
  23789. case 'upper-latin':
  23790. case 'lower-greek': {
  23791. $this->lisymbol = $symbol;
  23792. break;
  23793. }
  23794. default : {
  23795. $this->lisymbol = '';
  23796. }
  23797. }
  23798. }
  23799. /**
  23800. * Set the booklet mode for double-sided pages.
  23801. * @param $booklet (boolean) true set the booklet mode on, false otherwise.
  23802. * @param $inner (float) Inner page margin.
  23803. * @param $outer (float) Outer page margin.
  23804. * @public
  23805. * @since 4.2.000 (2008-10-29)
  23806. */
  23807. public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
  23808. $this->booklet = $booklet;
  23809. if ($inner >= 0) {
  23810. $this->lMargin = $inner;
  23811. }
  23812. if ($outer >= 0) {
  23813. $this->rMargin = $outer;
  23814. }
  23815. }
  23816. /**
  23817. * Swap the left and right margins.
  23818. * @param $reverse (boolean) if true swap left and right margins.
  23819. * @protected
  23820. * @since 4.2.000 (2008-10-29)
  23821. */
  23822. protected function swapMargins($reverse=true) {
  23823. if ($reverse) {
  23824. // swap left and right margins
  23825. $mtemp = $this->original_lMargin;
  23826. $this->original_lMargin = $this->original_rMargin;
  23827. $this->original_rMargin = $mtemp;
  23828. $deltam = $this->original_lMargin - $this->original_rMargin;
  23829. $this->lMargin += $deltam;
  23830. $this->rMargin -= $deltam;
  23831. }
  23832. }
  23833. /**
  23834. * Set the vertical spaces for HTML tags.
  23835. * The array must have the following structure (example):
  23836. * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
  23837. * The first array level contains the tag names,
  23838. * the second level contains 0 for opening tags or 1 for closing tags,
  23839. * the third level contains the vertical space unit (h) and the number spaces to add (n).
  23840. * If the h parameter is not specified, default values are used.
  23841. * @param $tagvs (array) array of tags and relative vertical spaces.
  23842. * @public
  23843. * @since 4.2.001 (2008-10-30)
  23844. */
  23845. public function setHtmlVSpace($tagvs) {
  23846. $this->tagvspaces = $tagvs;
  23847. }
  23848. /**
  23849. * Set custom width for list indentation.
  23850. * @param $width (float) width of the indentation. Use negative value to disable it.
  23851. * @public
  23852. * @since 4.2.007 (2008-11-12)
  23853. */
  23854. public function setListIndentWidth($width) {
  23855. return $this->customlistindent = floatval($width);
  23856. }
  23857. /**
  23858. * Set the top/bottom cell sides to be open or closed when the cell cross the page.
  23859. * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
  23860. * @public
  23861. * @since 4.2.010 (2008-11-14)
  23862. */
  23863. public function setOpenCell($isopen) {
  23864. $this->opencell = $isopen;
  23865. }
  23866. /**
  23867. * Set the color and font style for HTML links.
  23868. * @param $color (array) RGB array of colors
  23869. * @param $fontstyle (string) additional font styles to add
  23870. * @public
  23871. * @since 4.4.003 (2008-12-09)
  23872. */
  23873. public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
  23874. $this->htmlLinkColorArray = $color;
  23875. $this->htmlLinkFontStyle = $fontstyle;
  23876. }
  23877. /**
  23878. * Convert HTML string containing value and unit of measure to user's units or points.
  23879. * @param $htmlval (string) string containing values and unit
  23880. * @param $refsize (string) reference value in points
  23881. * @param $defaultunit (string) default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  23882. * @param $points (boolean) if true returns points, otherwise returns value in user's units
  23883. * @return float value in user's unit or point if $points=true
  23884. * @public
  23885. * @since 4.4.004 (2008-12-10)
  23886. */
  23887. public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
  23888. $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
  23889. $retval = 0;
  23890. $value = 0;
  23891. $unit = 'px';
  23892. $k = $this->k;
  23893. if ($points) {
  23894. $k = 1;
  23895. }
  23896. if (in_array($defaultunit, $supportedunits)) {
  23897. $unit = $defaultunit;
  23898. }
  23899. if (is_numeric($htmlval)) {
  23900. $value = floatval($htmlval);
  23901. } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
  23902. $value = floatval($mnum[1]);
  23903. if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
  23904. if (in_array($munit[1], $supportedunits)) {
  23905. $unit = $munit[1];
  23906. }
  23907. }
  23908. }
  23909. switch ($unit) {
  23910. // percentage
  23911. case '%': {
  23912. $retval = (($value * $refsize) / 100);
  23913. break;
  23914. }
  23915. // relative-size
  23916. case 'em': {
  23917. $retval = ($value * $refsize);
  23918. break;
  23919. }
  23920. // height of lower case 'x' (about half the font-size)
  23921. case 'ex': {
  23922. $retval = $value * ($refsize / 2);
  23923. break;
  23924. }
  23925. // absolute-size
  23926. case 'in': {
  23927. $retval = ($value * $this->dpi) / $k;
  23928. break;
  23929. }
  23930. // centimeters
  23931. case 'cm': {
  23932. $retval = ($value / 2.54 * $this->dpi) / $k;
  23933. break;
  23934. }
  23935. // millimeters
  23936. case 'mm': {
  23937. $retval = ($value / 25.4 * $this->dpi) / $k;
  23938. break;
  23939. }
  23940. // one pica is 12 points
  23941. case 'pc': {
  23942. $retval = ($value * 12) / $k;
  23943. break;
  23944. }
  23945. // points
  23946. case 'pt': {
  23947. $retval = $value / $k;
  23948. break;
  23949. }
  23950. // pixels
  23951. case 'px': {
  23952. $retval = $this->pixelsToUnits($value);
  23953. break;
  23954. }
  23955. }
  23956. return $retval;
  23957. }
  23958. /**
  23959. * Returns the Roman representation of an integer number
  23960. * @param $number (int) number to convert
  23961. * @return string roman representation of the specified number
  23962. * @since 4.4.004 (2008-12-10)
  23963. * @public
  23964. */
  23965. public function intToRoman($number) {
  23966. $roman = '';
  23967. while ($number >= 1000) {
  23968. $roman .= 'M';
  23969. $number -= 1000;
  23970. }
  23971. while ($number >= 900) {
  23972. $roman .= 'CM';
  23973. $number -= 900;
  23974. }
  23975. while ($number >= 500) {
  23976. $roman .= 'D';
  23977. $number -= 500;
  23978. }
  23979. while ($number >= 400) {
  23980. $roman .= 'CD';
  23981. $number -= 400;
  23982. }
  23983. while ($number >= 100) {
  23984. $roman .= 'C';
  23985. $number -= 100;
  23986. }
  23987. while ($number >= 90) {
  23988. $roman .= 'XC';
  23989. $number -= 90;
  23990. }
  23991. while ($number >= 50) {
  23992. $roman .= 'L';
  23993. $number -= 50;
  23994. }
  23995. while ($number >= 40) {
  23996. $roman .= 'XL';
  23997. $number -= 40;
  23998. }
  23999. while ($number >= 10) {
  24000. $roman .= 'X';
  24001. $number -= 10;
  24002. }
  24003. while ($number >= 9) {
  24004. $roman .= 'IX';
  24005. $number -= 9;
  24006. }
  24007. while ($number >= 5) {
  24008. $roman .= 'V';
  24009. $number -= 5;
  24010. }
  24011. while ($number >= 4) {
  24012. $roman .= 'IV';
  24013. $number -= 4;
  24014. }
  24015. while ($number >= 1) {
  24016. $roman .= 'I';
  24017. --$number;
  24018. }
  24019. return $roman;
  24020. }
  24021. /**
  24022. * Output an HTML list bullet or ordered item symbol
  24023. * @param $listdepth (int) list nesting level
  24024. * @param $listtype (string) type of list
  24025. * @param $size (float) current font size
  24026. * @protected
  24027. * @since 4.4.004 (2008-12-10)
  24028. */
  24029. protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
  24030. $size /= $this->k;
  24031. $fill = '';
  24032. $bgcolor = $this->bgcolor;
  24033. $color = $this->fgcolor;
  24034. $strokecolor = $this->strokecolor;
  24035. $width = 0;
  24036. $textitem = '';
  24037. $tmpx = $this->x;
  24038. $lspace = $this->GetStringWidth(' ');
  24039. if ($listtype == '^') {
  24040. // special symbol used for avoid justification of rect bullet
  24041. $this->lispacer = '';
  24042. return;
  24043. } elseif ($listtype == '!') {
  24044. // set default list type for unordered list
  24045. $deftypes = array('disc', 'circle', 'square');
  24046. $listtype = $deftypes[($listdepth - 1) % 3];
  24047. } elseif ($listtype == '#') {
  24048. // set default list type for ordered list
  24049. $listtype = 'decimal';
  24050. } elseif (substr($listtype, 0, 4) == 'img|') {
  24051. // custom image type ('img|type|width|height|image.ext')
  24052. $img = explode('|', $listtype);
  24053. $listtype = 'img';
  24054. }
  24055. switch ($listtype) {
  24056. // unordered types
  24057. case 'none': {
  24058. break;
  24059. }
  24060. case 'disc': {
  24061. $r = $size / 6;
  24062. $lspace += (2 * $r);
  24063. if ($this->rtl) {
  24064. $this->x += $lspace;
  24065. } else {
  24066. $this->x -= $lspace;
  24067. }
  24068. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
  24069. break;
  24070. }
  24071. case 'circle': {
  24072. $r = $size / 6;
  24073. $lspace += (2 * $r);
  24074. if ($this->rtl) {
  24075. $this->x += $lspace;
  24076. } else {
  24077. $this->x -= $lspace;
  24078. }
  24079. $prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
  24080. $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
  24081. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
  24082. $this->_out($prev_line_style); // restore line settings
  24083. break;
  24084. }
  24085. case 'square': {
  24086. $l = $size / 3;
  24087. $lspace += $l;
  24088. if ($this->rtl) {;
  24089. $this->x += $lspace;
  24090. } else {
  24091. $this->x -= $lspace;
  24092. }
  24093. $this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
  24094. break;
  24095. }
  24096. case 'img': {
  24097. // 1=>type, 2=>width, 3=>height, 4=>image.ext
  24098. $lspace += $img[2];
  24099. if ($this->rtl) {;
  24100. $this->x += $lspace;
  24101. } else {
  24102. $this->x -= $lspace;
  24103. }
  24104. $imgtype = strtolower($img[1]);
  24105. $prev_y = $this->y;
  24106. switch ($imgtype) {
  24107. case 'svg': {
  24108. $this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
  24109. break;
  24110. }
  24111. case 'ai':
  24112. case 'eps': {
  24113. $this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
  24114. break;
  24115. }
  24116. default: {
  24117. $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);
  24118. break;
  24119. }
  24120. }
  24121. $this->y = $prev_y;
  24122. break;
  24123. }
  24124. // ordered types
  24125. // $this->listcount[$this->listnum];
  24126. // $textitem
  24127. case '1':
  24128. case 'decimal': {
  24129. $textitem = $this->listcount[$this->listnum];
  24130. break;
  24131. }
  24132. case 'decimal-leading-zero': {
  24133. $textitem = sprintf('%02d', $this->listcount[$this->listnum]);
  24134. break;
  24135. }
  24136. case 'i':
  24137. case 'lower-roman': {
  24138. $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
  24139. break;
  24140. }
  24141. case 'I':
  24142. case 'upper-roman': {
  24143. $textitem = $this->intToRoman($this->listcount[$this->listnum]);
  24144. break;
  24145. }
  24146. case 'a':
  24147. case 'lower-alpha':
  24148. case 'lower-latin': {
  24149. $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
  24150. break;
  24151. }
  24152. case 'A':
  24153. case 'upper-alpha':
  24154. case 'upper-latin': {
  24155. $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
  24156. break;
  24157. }
  24158. case 'lower-greek': {
  24159. $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
  24160. break;
  24161. }
  24162. /*
  24163. // Types to be implemented (special handling)
  24164. case 'hebrew': {
  24165. break;
  24166. }
  24167. case 'armenian': {
  24168. break;
  24169. }
  24170. case 'georgian': {
  24171. break;
  24172. }
  24173. case 'cjk-ideographic': {
  24174. break;
  24175. }
  24176. case 'hiragana': {
  24177. break;
  24178. }
  24179. case 'katakana': {
  24180. break;
  24181. }
  24182. case 'hiragana-iroha': {
  24183. break;
  24184. }
  24185. case 'katakana-iroha': {
  24186. break;
  24187. }
  24188. */
  24189. default: {
  24190. $textitem = $this->listcount[$this->listnum];
  24191. }
  24192. }
  24193. if (!$this->empty_string($textitem)) {
  24194. // Check whether we need a new page or new column
  24195. $prev_y = $this->y;
  24196. $h = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  24197. if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
  24198. $tmpx = $this->x;
  24199. }
  24200. // print ordered item
  24201. if ($this->rtl) {
  24202. $textitem = '.'.$textitem;
  24203. } else {
  24204. $textitem = $textitem.'.';
  24205. }
  24206. $lspace += $this->GetStringWidth($textitem);
  24207. if ($this->rtl) {
  24208. $this->x += $lspace;
  24209. } else {
  24210. $this->x -= $lspace;
  24211. }
  24212. $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
  24213. }
  24214. $this->x = $tmpx;
  24215. $this->lispacer = '^';
  24216. // restore colors
  24217. $this->SetFillColorArray($bgcolor);
  24218. $this->SetDrawColorArray($strokecolor);
  24219. $this->SettextColorArray($color);
  24220. }
  24221. /**
  24222. * Returns current graphic variables as array.
  24223. * @return array of graphic variables
  24224. * @protected
  24225. * @since 4.2.010 (2008-11-14)
  24226. */
  24227. protected function getGraphicVars() {
  24228. $grapvars = array(
  24229. 'FontFamily' => $this->FontFamily,
  24230. 'FontStyle' => $this->FontStyle,
  24231. 'FontSizePt' => $this->FontSizePt,
  24232. 'rMargin' => $this->rMargin,
  24233. 'lMargin' => $this->lMargin,
  24234. 'cell_padding' => $this->cell_padding,
  24235. 'cell_margin' => $this->cell_margin,
  24236. 'LineWidth' => $this->LineWidth,
  24237. 'linestyleWidth' => $this->linestyleWidth,
  24238. 'linestyleCap' => $this->linestyleCap,
  24239. 'linestyleJoin' => $this->linestyleJoin,
  24240. 'linestyleDash' => $this->linestyleDash,
  24241. 'textrendermode' => $this->textrendermode,
  24242. 'textstrokewidth' => $this->textstrokewidth,
  24243. 'DrawColor' => $this->DrawColor,
  24244. 'FillColor' => $this->FillColor,
  24245. 'TextColor' => $this->TextColor,
  24246. 'ColorFlag' => $this->ColorFlag,
  24247. 'bgcolor' => $this->bgcolor,
  24248. 'fgcolor' => $this->fgcolor,
  24249. 'htmlvspace' => $this->htmlvspace,
  24250. 'listindent' => $this->listindent,
  24251. 'listindentlevel' => $this->listindentlevel,
  24252. 'listnum' => $this->listnum,
  24253. 'listordered' => $this->listordered,
  24254. 'listcount' => $this->listcount,
  24255. 'lispacer' => $this->lispacer,
  24256. 'cell_height_ratio' => $this->cell_height_ratio,
  24257. 'font_stretching' => $this->font_stretching,
  24258. 'font_spacing' => $this->font_spacing,
  24259. // extended
  24260. 'lasth' => $this->lasth,
  24261. 'tMargin' => $this->tMargin,
  24262. 'bMargin' => $this->bMargin,
  24263. 'AutoPageBreak' => $this->AutoPageBreak,
  24264. 'PageBreakTrigger' => $this->PageBreakTrigger,
  24265. 'x' => $this->x,
  24266. 'y' => $this->y,
  24267. 'w' => $this->w,
  24268. 'h' => $this->h,
  24269. 'wPt' => $this->wPt,
  24270. 'hPt' => $this->hPt,
  24271. 'fwPt' => $this->fwPt,
  24272. 'fhPt' => $this->fhPt,
  24273. 'page' => $this->page,
  24274. 'current_column' => $this->current_column,
  24275. 'num_columns' => $this->num_columns
  24276. );
  24277. return $grapvars;
  24278. }
  24279. /**
  24280. * Set graphic variables.
  24281. * @param $gvars (array) array of graphic variablesto restore
  24282. * @param $extended (boolean) if true restore extended graphic variables
  24283. * @protected
  24284. * @since 4.2.010 (2008-11-14)
  24285. */
  24286. protected function setGraphicVars($gvars, $extended=false) {
  24287. $this->FontFamily = $gvars['FontFamily'];
  24288. $this->FontStyle = $gvars['FontStyle'];
  24289. $this->FontSizePt = $gvars['FontSizePt'];
  24290. $this->rMargin = $gvars['rMargin'];
  24291. $this->lMargin = $gvars['lMargin'];
  24292. $this->cell_padding = $gvars['cell_padding'];
  24293. $this->cell_margin = $gvars['cell_margin'];
  24294. $this->LineWidth = $gvars['LineWidth'];
  24295. $this->linestyleWidth = $gvars['linestyleWidth'];
  24296. $this->linestyleCap = $gvars['linestyleCap'];
  24297. $this->linestyleJoin = $gvars['linestyleJoin'];
  24298. $this->linestyleDash = $gvars['linestyleDash'];
  24299. $this->textrendermode = $gvars['textrendermode'];
  24300. $this->textstrokewidth = $gvars['textstrokewidth'];
  24301. $this->DrawColor = $gvars['DrawColor'];
  24302. $this->FillColor = $gvars['FillColor'];
  24303. $this->TextColor = $gvars['TextColor'];
  24304. $this->ColorFlag = $gvars['ColorFlag'];
  24305. $this->bgcolor = $gvars['bgcolor'];
  24306. $this->fgcolor = $gvars['fgcolor'];
  24307. $this->htmlvspace = $gvars['htmlvspace'];
  24308. $this->listindent = $gvars['listindent'];
  24309. $this->listindentlevel = $gvars['listindentlevel'];
  24310. $this->listnum = $gvars['listnum'];
  24311. $this->listordered = $gvars['listordered'];
  24312. $this->listcount = $gvars['listcount'];
  24313. $this->lispacer = $gvars['lispacer'];
  24314. $this->cell_height_ratio = $gvars['cell_height_ratio'];
  24315. $this->font_stretching = $gvars['font_stretching'];
  24316. $this->font_spacing = $gvars['font_spacing'];
  24317. if ($extended) {
  24318. // restore extended values
  24319. $this->lasth = $gvars['lasth'];
  24320. $this->tMargin = $gvars['tMargin'];
  24321. $this->bMargin = $gvars['bMargin'];
  24322. $this->AutoPageBreak = $gvars['AutoPageBreak'];
  24323. $this->PageBreakTrigger = $gvars['PageBreakTrigger'];
  24324. $this->x = $gvars['x'];
  24325. $this->y = $gvars['y'];
  24326. $this->w = $gvars['w'];
  24327. $this->h = $gvars['h'];
  24328. $this->wPt = $gvars['wPt'];
  24329. $this->hPt = $gvars['hPt'];
  24330. $this->fwPt = $gvars['fwPt'];
  24331. $this->fhPt = $gvars['fhPt'];
  24332. $this->page = $gvars['page'];
  24333. $this->current_column = $gvars['current_column'];
  24334. $this->num_columns = $gvars['num_columns'];
  24335. }
  24336. $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
  24337. if (!$this->empty_string($this->FontFamily)) {
  24338. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  24339. }
  24340. }
  24341. /**
  24342. * Returns a temporary filename for caching object on filesystem.
  24343. * @param $name (string) prefix to add to filename
  24344. * @return string filename.
  24345. * @since 4.5.000 (2008-12-31)
  24346. * @protected
  24347. */
  24348. protected function getObjFilename($name) {
  24349. return tempnam(K_PATH_CACHE, $name.'_');
  24350. }
  24351. /**
  24352. * Writes data to a temporary file on filesystem.
  24353. * @param $filename (string) file name
  24354. * @param $data (mixed) data to write on file
  24355. * @param $append (boolean) if true append data, false replace.
  24356. * @since 4.5.000 (2008-12-31)
  24357. * @protected
  24358. */
  24359. protected function writeDiskCache($filename, $data, $append=false) {
  24360. if ($append) {
  24361. $fmode = 'ab+';
  24362. } else {
  24363. $fmode = 'wb+';
  24364. }
  24365. $f = @fopen($filename, $fmode);
  24366. if (!$f) {
  24367. $this->Error('Unable to write cache file: '.$filename);
  24368. } else {
  24369. fwrite($f, $data);
  24370. fclose($f);
  24371. }
  24372. // update file length (needed for transactions)
  24373. if (!isset($this->cache_file_length['_'.$filename])) {
  24374. $this->cache_file_length['_'.$filename] = strlen($data);
  24375. } else {
  24376. $this->cache_file_length['_'.$filename] += strlen($data);
  24377. }
  24378. }
  24379. /**
  24380. * Read data from a temporary file on filesystem.
  24381. * @param $filename (string) file name
  24382. * @return mixed retrieved data
  24383. * @since 4.5.000 (2008-12-31)
  24384. * @protected
  24385. */
  24386. protected function readDiskCache($filename) {
  24387. return file_get_contents($filename);
  24388. }
  24389. /**
  24390. * Set buffer content (always append data).
  24391. * @param $data (string) data
  24392. * @protected
  24393. * @since 4.5.000 (2009-01-02)
  24394. */
  24395. protected function setBuffer($data) {
  24396. $this->bufferlen += strlen($data);
  24397. if ($this->diskcache) {
  24398. if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
  24399. $this->buffer = $this->getObjFilename('buffer');
  24400. }
  24401. $this->writeDiskCache($this->buffer, $data, true);
  24402. } else {
  24403. $this->buffer .= $data;
  24404. }
  24405. }
  24406. /**
  24407. * Replace the buffer content
  24408. * @param $data (string) data
  24409. * @protected
  24410. * @since 5.5.000 (2010-06-22)
  24411. */
  24412. protected function replaceBuffer($data) {
  24413. $this->bufferlen = strlen($data);
  24414. if ($this->diskcache) {
  24415. if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
  24416. $this->buffer = $this->getObjFilename('buffer');
  24417. }
  24418. $this->writeDiskCache($this->buffer, $data, false);
  24419. } else {
  24420. $this->buffer = $data;
  24421. }
  24422. }
  24423. /**
  24424. * Get buffer content.
  24425. * @return string buffer content
  24426. * @protected
  24427. * @since 4.5.000 (2009-01-02)
  24428. */
  24429. protected function getBuffer() {
  24430. if ($this->diskcache) {
  24431. return $this->readDiskCache($this->buffer);
  24432. } else {
  24433. return $this->buffer;
  24434. }
  24435. }
  24436. /**
  24437. * Set page buffer content.
  24438. * @param $page (int) page number
  24439. * @param $data (string) page data
  24440. * @param $append (boolean) if true append data, false replace.
  24441. * @protected
  24442. * @since 4.5.000 (2008-12-31)
  24443. */
  24444. protected function setPageBuffer($page, $data, $append=false) {
  24445. if ($this->diskcache) {
  24446. if (!isset($this->pages[$page])) {
  24447. $this->pages[$page] = $this->getObjFilename('page'.$page);
  24448. }
  24449. $this->writeDiskCache($this->pages[$page], $data, $append);
  24450. } else {
  24451. if ($append) {
  24452. $this->pages[$page] .= $data;
  24453. } else {
  24454. $this->pages[$page] = $data;
  24455. }
  24456. }
  24457. if ($append AND isset($this->pagelen[$page])) {
  24458. $this->pagelen[$page] += strlen($data);
  24459. } else {
  24460. $this->pagelen[$page] = strlen($data);
  24461. }
  24462. }
  24463. /**
  24464. * Get page buffer content.
  24465. * @param $page (int) page number
  24466. * @return string page buffer content or false in case of error
  24467. * @protected
  24468. * @since 4.5.000 (2008-12-31)
  24469. */
  24470. protected function getPageBuffer($page) {
  24471. if ($this->diskcache) {
  24472. return $this->readDiskCache($this->pages[$page]);
  24473. } elseif (isset($this->pages[$page])) {
  24474. return $this->pages[$page];
  24475. }
  24476. return false;
  24477. }
  24478. /**
  24479. * Set image buffer content.
  24480. * @param $image (string) image key
  24481. * @param $data (array) image data
  24482. * @protected
  24483. * @since 4.5.000 (2008-12-31)
  24484. */
  24485. protected function setImageBuffer($image, $data) {
  24486. if ($this->diskcache) {
  24487. if (!isset($this->images[$image])) {
  24488. $this->images[$image] = $this->getObjFilename('image'.$image);
  24489. }
  24490. $this->writeDiskCache($this->images[$image], serialize($data));
  24491. } else {
  24492. $this->images[$image] = $data;
  24493. }
  24494. if (!in_array($image, $this->imagekeys)) {
  24495. $this->imagekeys[] = $image;
  24496. ++$this->numimages;
  24497. }
  24498. }
  24499. /**
  24500. * Set image buffer content for a specified sub-key.
  24501. * @param $image (string) image key
  24502. * @param $key (string) image sub-key
  24503. * @param $data (array) image data
  24504. * @protected
  24505. * @since 4.5.000 (2008-12-31)
  24506. */
  24507. protected function setImageSubBuffer($image, $key, $data) {
  24508. if (!isset($this->images[$image])) {
  24509. $this->setImageBuffer($image, array());
  24510. }
  24511. if ($this->diskcache) {
  24512. $tmpimg = $this->getImageBuffer($image);
  24513. $tmpimg[$key] = $data;
  24514. $this->writeDiskCache($this->images[$image], serialize($tmpimg));
  24515. } else {
  24516. $this->images[$image][$key] = $data;
  24517. }
  24518. }
  24519. /**
  24520. * Get image buffer content.
  24521. * @param $image (string) image key
  24522. * @return string image buffer content or false in case of error
  24523. * @protected
  24524. * @since 4.5.000 (2008-12-31)
  24525. */
  24526. protected function getImageBuffer($image) {
  24527. if ($this->diskcache AND isset($this->images[$image])) {
  24528. return unserialize($this->readDiskCache($this->images[$image]));
  24529. } elseif (isset($this->images[$image])) {
  24530. return $this->images[$image];
  24531. }
  24532. return false;
  24533. }
  24534. /**
  24535. * Set font buffer content.
  24536. * @param $font (string) font key
  24537. * @param $data (array) font data
  24538. * @protected
  24539. * @since 4.5.000 (2009-01-02)
  24540. */
  24541. protected function setFontBuffer($font, $data) {
  24542. if ($this->diskcache) {
  24543. if (!isset($this->fonts[$font])) {
  24544. $this->fonts[$font] = $this->getObjFilename('font');
  24545. }
  24546. $this->writeDiskCache($this->fonts[$font], serialize($data));
  24547. } else {
  24548. $this->fonts[$font] = $data;
  24549. }
  24550. if (!in_array($font, $this->fontkeys)) {
  24551. $this->fontkeys[] = $font;
  24552. // store object ID for current font
  24553. ++$this->n;
  24554. $this->font_obj_ids[$font] = $this->n;
  24555. $this->setFontSubBuffer($font, 'n', $this->n);
  24556. }
  24557. }
  24558. /**
  24559. * Set font buffer content.
  24560. * @param $font (string) font key
  24561. * @param $key (string) font sub-key
  24562. * @param $data (array) font data
  24563. * @protected
  24564. * @since 4.5.000 (2009-01-02)
  24565. */
  24566. protected function setFontSubBuffer($font, $key, $data) {
  24567. if (!isset($this->fonts[$font])) {
  24568. $this->setFontBuffer($font, array());
  24569. }
  24570. if ($this->diskcache) {
  24571. $tmpfont = $this->getFontBuffer($font);
  24572. $tmpfont[$key] = $data;
  24573. $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
  24574. } else {
  24575. $this->fonts[$font][$key] = $data;
  24576. }
  24577. }
  24578. /**
  24579. * Get font buffer content.
  24580. * @param $font (string) font key
  24581. * @return string font buffer content or false in case of error
  24582. * @protected
  24583. * @since 4.5.000 (2009-01-02)
  24584. */
  24585. protected function getFontBuffer($font) {
  24586. if ($this->diskcache AND isset($this->fonts[$font])) {
  24587. return unserialize($this->readDiskCache($this->fonts[$font]));
  24588. } elseif (isset($this->fonts[$font])) {
  24589. return $this->fonts[$font];
  24590. }
  24591. return false;
  24592. }
  24593. /**
  24594. * Move a page to a previous position.
  24595. * @param $frompage (int) number of the source page
  24596. * @param $topage (int) number of the destination page (must be less than $frompage)
  24597. * @return true in case of success, false in case of error.
  24598. * @public
  24599. * @since 4.5.000 (2009-01-02)
  24600. */
  24601. public function movePage($frompage, $topage) {
  24602. if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
  24603. return false;
  24604. }
  24605. if ($frompage == $this->page) {
  24606. // close the page before moving it
  24607. $this->endPage();
  24608. }
  24609. // move all page-related states
  24610. $tmppage = $this->getPageBuffer($frompage);
  24611. $tmppagedim = $this->pagedim[$frompage];
  24612. $tmppagelen = $this->pagelen[$frompage];
  24613. $tmpintmrk = $this->intmrk[$frompage];
  24614. $tmpbordermrk = $this->bordermrk[$frompage];
  24615. $tmpcntmrk = $this->cntmrk[$frompage];
  24616. if (isset($this->footerpos[$frompage])) {
  24617. $tmpfooterpos = $this->footerpos[$frompage];
  24618. }
  24619. if (isset($this->footerlen[$frompage])) {
  24620. $tmpfooterlen = $this->footerlen[$frompage];
  24621. }
  24622. if (isset($this->transfmrk[$frompage])) {
  24623. $tmptransfmrk = $this->transfmrk[$frompage];
  24624. }
  24625. if (isset($this->PageAnnots[$frompage])) {
  24626. $tmpannots = $this->PageAnnots[$frompage];
  24627. }
  24628. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  24629. for ($i = $frompage; $i > $topage; --$i) {
  24630. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
  24631. --$this->pagegroups[$this->newpagegroup[$i]];
  24632. break;
  24633. }
  24634. }
  24635. for ($i = $topage; $i > 0; --$i) {
  24636. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
  24637. ++$this->pagegroups[$this->newpagegroup[$i]];
  24638. break;
  24639. }
  24640. }
  24641. }
  24642. for ($i = $frompage; $i > $topage; --$i) {
  24643. $j = $i - 1;
  24644. // shift pages down
  24645. $this->setPageBuffer($i, $this->getPageBuffer($j));
  24646. $this->pagedim[$i] = $this->pagedim[$j];
  24647. $this->pagelen[$i] = $this->pagelen[$j];
  24648. $this->intmrk[$i] = $this->intmrk[$j];
  24649. $this->bordermrk[$i] = $this->bordermrk[$j];
  24650. $this->cntmrk[$i] = $this->cntmrk[$j];
  24651. if (isset($this->footerpos[$j])) {
  24652. $this->footerpos[$i] = $this->footerpos[$j];
  24653. } elseif (isset($this->footerpos[$i])) {
  24654. unset($this->footerpos[$i]);
  24655. }
  24656. if (isset($this->footerlen[$j])) {
  24657. $this->footerlen[$i] = $this->footerlen[$j];
  24658. } elseif (isset($this->footerlen[$i])) {
  24659. unset($this->footerlen[$i]);
  24660. }
  24661. if (isset($this->transfmrk[$j])) {
  24662. $this->transfmrk[$i] = $this->transfmrk[$j];
  24663. } elseif (isset($this->transfmrk[$i])) {
  24664. unset($this->transfmrk[$i]);
  24665. }
  24666. if (isset($this->PageAnnots[$j])) {
  24667. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  24668. } elseif (isset($this->PageAnnots[$i])) {
  24669. unset($this->PageAnnots[$i]);
  24670. }
  24671. if (isset($this->newpagegroup[$j])) {
  24672. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  24673. unset($this->newpagegroup[$j]);
  24674. }
  24675. if ($this->currpagegroup == $j) {
  24676. $this->currpagegroup = $i;
  24677. }
  24678. }
  24679. $this->setPageBuffer($topage, $tmppage);
  24680. $this->pagedim[$topage] = $tmppagedim;
  24681. $this->pagelen[$topage] = $tmppagelen;
  24682. $this->intmrk[$topage] = $tmpintmrk;
  24683. $this->bordermrk[$topage] = $tmpbordermrk;
  24684. $this->cntmrk[$topage] = $tmpcntmrk;
  24685. if (isset($tmpfooterpos)) {
  24686. $this->footerpos[$topage] = $tmpfooterpos;
  24687. } elseif (isset($this->footerpos[$topage])) {
  24688. unset($this->footerpos[$topage]);
  24689. }
  24690. if (isset($tmpfooterlen)) {
  24691. $this->footerlen[$topage] = $tmpfooterlen;
  24692. } elseif (isset($this->footerlen[$topage])) {
  24693. unset($this->footerlen[$topage]);
  24694. }
  24695. if (isset($tmptransfmrk)) {
  24696. $this->transfmrk[$topage] = $tmptransfmrk;
  24697. } elseif (isset($this->transfmrk[$topage])) {
  24698. unset($this->transfmrk[$topage]);
  24699. }
  24700. if (isset($tmpannots)) {
  24701. $this->PageAnnots[$topage] = $tmpannots;
  24702. } elseif (isset($this->PageAnnots[$topage])) {
  24703. unset($this->PageAnnots[$topage]);
  24704. }
  24705. // adjust outlines
  24706. $tmpoutlines = $this->outlines;
  24707. foreach ($tmpoutlines as $key => $outline) {
  24708. if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
  24709. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  24710. } elseif ($outline['p'] == $frompage) {
  24711. $this->outlines[$key]['p'] = $topage;
  24712. }
  24713. }
  24714. // adjust dests
  24715. $tmpdests = $this->dests;
  24716. foreach ($tmpdests as $key => $dest) {
  24717. if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
  24718. $this->dests[$key]['p'] = ($dest['p'] + 1);
  24719. } elseif ($dest['p'] == $frompage) {
  24720. $this->dests[$key]['p'] = $topage;
  24721. }
  24722. }
  24723. // adjust links
  24724. $tmplinks = $this->links;
  24725. foreach ($tmplinks as $key => $link) {
  24726. if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
  24727. $this->links[$key][0] = ($link[0] + 1);
  24728. } elseif ($link[0] == $frompage) {
  24729. $this->links[$key][0] = $topage;
  24730. }
  24731. }
  24732. // adjust javascript
  24733. $tmpjavascript = $this->javascript;
  24734. global $jfrompage, $jtopage;
  24735. $jfrompage = $frompage;
  24736. $jtopage = $topage;
  24737. $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
  24738. create_function('$matches', 'global $jfrompage, $jtopage;
  24739. $pagenum = intval($matches[3]) + 1;
  24740. if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
  24741. $newpage = ($pagenum + 1);
  24742. } elseif ($pagenum == $jfrompage) {
  24743. $newpage = $jtopage;
  24744. } else {
  24745. $newpage = $pagenum;
  24746. }
  24747. --$newpage;
  24748. return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
  24749. // return to last page
  24750. $this->lastPage(true);
  24751. return true;
  24752. }
  24753. /**
  24754. * Remove the specified page.
  24755. * @param $page (int) page to remove
  24756. * @return true in case of success, false in case of error.
  24757. * @public
  24758. * @since 4.6.004 (2009-04-23)
  24759. */
  24760. public function deletePage($page) {
  24761. if (($page < 1) OR ($page > $this->numpages)) {
  24762. return false;
  24763. }
  24764. // delete current page
  24765. unset($this->pages[$page]);
  24766. unset($this->pagedim[$page]);
  24767. unset($this->pagelen[$page]);
  24768. unset($this->intmrk[$page]);
  24769. unset($this->bordermrk[$page]);
  24770. unset($this->cntmrk[$page]);
  24771. if (isset($this->footerpos[$page])) {
  24772. unset($this->footerpos[$page]);
  24773. }
  24774. if (isset($this->footerlen[$page])) {
  24775. unset($this->footerlen[$page]);
  24776. }
  24777. if (isset($this->transfmrk[$page])) {
  24778. unset($this->transfmrk[$page]);
  24779. }
  24780. if (isset($this->PageAnnots[$page])) {
  24781. unset($this->PageAnnots[$page]);
  24782. }
  24783. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  24784. for ($i = $page; $i > 0; --$i) {
  24785. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
  24786. --$this->pagegroups[$this->newpagegroup[$i]];
  24787. break;
  24788. }
  24789. }
  24790. }
  24791. if (isset($this->pageopen[$page])) {
  24792. unset($this->pageopen[$page]);
  24793. }
  24794. if ($page < $this->numpages) {
  24795. // update remaining pages
  24796. for ($i = $page; $i < $this->numpages; ++$i) {
  24797. $j = $i + 1;
  24798. // shift pages
  24799. $this->setPageBuffer($i, $this->getPageBuffer($j));
  24800. $this->pagedim[$i] = $this->pagedim[$j];
  24801. $this->pagelen[$i] = $this->pagelen[$j];
  24802. $this->intmrk[$i] = $this->intmrk[$j];
  24803. $this->bordermrk[$i] = $this->bordermrk[$j];
  24804. $this->cntmrk[$i] = $this->cntmrk[$j];
  24805. if (isset($this->footerpos[$j])) {
  24806. $this->footerpos[$i] = $this->footerpos[$j];
  24807. } elseif (isset($this->footerpos[$i])) {
  24808. unset($this->footerpos[$i]);
  24809. }
  24810. if (isset($this->footerlen[$j])) {
  24811. $this->footerlen[$i] = $this->footerlen[$j];
  24812. } elseif (isset($this->footerlen[$i])) {
  24813. unset($this->footerlen[$i]);
  24814. }
  24815. if (isset($this->transfmrk[$j])) {
  24816. $this->transfmrk[$i] = $this->transfmrk[$j];
  24817. } elseif (isset($this->transfmrk[$i])) {
  24818. unset($this->transfmrk[$i]);
  24819. }
  24820. if (isset($this->PageAnnots[$j])) {
  24821. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  24822. } elseif (isset($this->PageAnnots[$i])) {
  24823. unset($this->PageAnnots[$i]);
  24824. }
  24825. if (isset($this->newpagegroup[$j])) {
  24826. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  24827. unset($this->newpagegroup[$j]);
  24828. }
  24829. if ($this->currpagegroup == $j) {
  24830. $this->currpagegroup = $i;
  24831. }
  24832. if (isset($this->pageopen[$j])) {
  24833. $this->pageopen[$i] = $this->pageopen[$j];
  24834. } elseif (isset($this->pageopen[$i])) {
  24835. unset($this->pageopen[$i]);
  24836. }
  24837. }
  24838. // remove last page
  24839. unset($this->pages[$this->numpages]);
  24840. unset($this->pagedim[$this->numpages]);
  24841. unset($this->pagelen[$this->numpages]);
  24842. unset($this->intmrk[$this->numpages]);
  24843. unset($this->bordermrk[$this->numpages]);
  24844. unset($this->cntmrk[$this->numpages]);
  24845. if (isset($this->footerpos[$this->numpages])) {
  24846. unset($this->footerpos[$this->numpages]);
  24847. }
  24848. if (isset($this->footerlen[$this->numpages])) {
  24849. unset($this->footerlen[$this->numpages]);
  24850. }
  24851. if (isset($this->transfmrk[$this->numpages])) {
  24852. unset($this->transfmrk[$this->numpages]);
  24853. }
  24854. if (isset($this->PageAnnots[$this->numpages])) {
  24855. unset($this->PageAnnots[$this->numpages]);
  24856. }
  24857. if (isset($this->newpagegroup[$this->numpages])) {
  24858. unset($this->newpagegroup[$this->numpages]);
  24859. }
  24860. if ($this->currpagegroup == $this->numpages) {
  24861. $this->currpagegroup = ($this->numpages - 1);
  24862. }
  24863. if (isset($this->pagegroups[$this->numpages])) {
  24864. unset($this->pagegroups[$this->numpages]);
  24865. }
  24866. if (isset($this->pageopen[$this->numpages])) {
  24867. unset($this->pageopen[$this->numpages]);
  24868. }
  24869. }
  24870. --$this->numpages;
  24871. $this->page = $this->numpages;
  24872. // adjust outlines
  24873. $tmpoutlines = $this->outlines;
  24874. foreach ($tmpoutlines as $key => $outline) {
  24875. if ($outline['p'] > $page) {
  24876. $this->outlines[$key]['p'] = $outline['p'] - 1;
  24877. } elseif ($outline['p'] == $page) {
  24878. unset($this->outlines[$key]);
  24879. }
  24880. }
  24881. // adjust dests
  24882. $tmpdests = $this->dests;
  24883. foreach ($tmpdests as $key => $dest) {
  24884. if ($dest['p'] > $page) {
  24885. $this->dests[$key]['p'] = $dest['p'] - 1;
  24886. } elseif ($dest['p'] == $page) {
  24887. unset($this->dests[$key]);
  24888. }
  24889. }
  24890. // adjust links
  24891. $tmplinks = $this->links;
  24892. foreach ($tmplinks as $key => $link) {
  24893. if ($link[0] > $page) {
  24894. $this->links[$key][0] = $link[0] - 1;
  24895. } elseif ($link[0] == $page) {
  24896. unset($this->links[$key]);
  24897. }
  24898. }
  24899. // adjust javascript
  24900. $tmpjavascript = $this->javascript;
  24901. global $jpage;
  24902. $jpage = $page;
  24903. $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
  24904. create_function('$matches', 'global $jpage;
  24905. $pagenum = intval($matches[3]) + 1;
  24906. if ($pagenum >= $jpage) {
  24907. $newpage = ($pagenum - 1);
  24908. } elseif ($pagenum == $jpage) {
  24909. $newpage = 1;
  24910. } else {
  24911. $newpage = $pagenum;
  24912. }
  24913. --$newpage;
  24914. return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
  24915. // return to last page
  24916. $this->lastPage(true);
  24917. return true;
  24918. }
  24919. /**
  24920. * Clone the specified page to a new page.
  24921. * @param $page (int) number of page to copy (0 = current page)
  24922. * @return true in case of success, false in case of error.
  24923. * @public
  24924. * @since 4.9.015 (2010-04-20)
  24925. */
  24926. public function copyPage($page=0) {
  24927. if ($page == 0) {
  24928. // default value
  24929. $page = $this->page;
  24930. }
  24931. if (($page < 1) OR ($page > $this->numpages)) {
  24932. return false;
  24933. }
  24934. // close the last page
  24935. $this->endPage();
  24936. // copy all page-related states
  24937. ++$this->numpages;
  24938. $this->page = $this->numpages;
  24939. $this->setPageBuffer($this->page, $this->getPageBuffer($page));
  24940. $this->pagedim[$this->page] = $this->pagedim[$page];
  24941. $this->pagelen[$this->page] = $this->pagelen[$page];
  24942. $this->intmrk[$this->page] = $this->intmrk[$page];
  24943. $this->bordermrk[$this->page] = $this->bordermrk[$page];
  24944. $this->cntmrk[$this->page] = $this->cntmrk[$page];
  24945. $this->pageopen[$this->page] = false;
  24946. if (isset($this->footerpos[$page])) {
  24947. $this->footerpos[$this->page] = $this->footerpos[$page];
  24948. }
  24949. if (isset($this->footerlen[$page])) {
  24950. $this->footerlen[$this->page] = $this->footerlen[$page];
  24951. }
  24952. if (isset($this->transfmrk[$page])) {
  24953. $this->transfmrk[$this->page] = $this->transfmrk[$page];
  24954. }
  24955. if (isset($this->PageAnnots[$page])) {
  24956. $this->PageAnnots[$this->page] = $this->PageAnnots[$page];
  24957. }
  24958. if (isset($this->newpagegroup[$page])) {
  24959. // start a new group
  24960. $this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
  24961. $this->currpagegroup = $this->newpagegroup[$this->page];
  24962. $this->pagegroups[$this->currpagegroup] = 1;
  24963. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  24964. ++$this->pagegroups[$this->currpagegroup];
  24965. }
  24966. // copy outlines
  24967. $tmpoutlines = $this->outlines;
  24968. foreach ($tmpoutlines as $key => $outline) {
  24969. if ($outline['p'] == $page) {
  24970. $this->outlines[] = array('t' => $outline['t'], 'l' => $outline['l'], 'y' => $outline['y'], 'p' => $this->page, 's' => $outline['s'], 'c' => $outline['c']);
  24971. }
  24972. }
  24973. // copy links
  24974. $tmplinks = $this->links;
  24975. foreach ($tmplinks as $key => $link) {
  24976. if ($link[0] == $page) {
  24977. $this->links[] = array($this->page, $link[1]);
  24978. }
  24979. }
  24980. // return to last page
  24981. $this->lastPage(true);
  24982. return true;
  24983. }
  24984. /**
  24985. * Output a Table of Content Index (TOC).
  24986. * This method must be called after all Bookmarks were set.
  24987. * Before calling this method you have to open the page using the addTOCPage() method.
  24988. * After calling this method you have to call endTOCPage() to close the TOC page.
  24989. * You can override this method to achieve different styles.
  24990. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  24991. * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
  24992. * @param $filler (string) string used to fill the space between text and page number.
  24993. * @param $toc_name (string) name to use for TOC bookmark.
  24994. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  24995. * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
  24996. * @public
  24997. * @author Nicola Asuni
  24998. * @since 4.5.000 (2009-01-02)
  24999. * @see addTOCPage(), endTOCPage(), addHTMLTOC()
  25000. */
  25001. public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
  25002. $fontsize = $this->FontSizePt;
  25003. $fontfamily = $this->FontFamily;
  25004. $fontstyle = $this->FontStyle;
  25005. $w = $this->w - $this->lMargin - $this->rMargin;
  25006. $spacer = $this->GetStringWidth(chr(32)) * 4;
  25007. $page_first = $this->getPage();
  25008. $lmargin = $this->lMargin;
  25009. $rmargin = $this->rMargin;
  25010. $x_start = $this->GetX();
  25011. $current_page = $this->page;
  25012. $current_column = $this->current_column;
  25013. if ($this->empty_string($numbersfont)) {
  25014. $numbersfont = $this->default_monospaced_font;
  25015. }
  25016. if ($this->empty_string($filler)) {
  25017. $filler = ' ';
  25018. }
  25019. if ($this->empty_string($page)) {
  25020. $gap = ' ';
  25021. } else {
  25022. $gap = '';
  25023. if ($page < 1) {
  25024. $page = 1;
  25025. }
  25026. }
  25027. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  25028. $numwidth = $this->GetStringWidth('00000');
  25029. $maxpage = 0; //used for pages on attached documents
  25030. foreach ($this->outlines as $key => $outline) {
  25031. // check for extra pages (used for attachments)
  25032. if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
  25033. $outline['p'] += ($this->page - $page_first);
  25034. }
  25035. if ($this->rtl) {
  25036. $aligntext = 'R';
  25037. $alignnum = 'L';
  25038. } else {
  25039. $aligntext = 'L';
  25040. $alignnum = 'R';
  25041. }
  25042. if ($outline['l'] == 0) {
  25043. $this->SetFont($fontfamily, $fontstyle.'B', $fontsize);
  25044. } else {
  25045. $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']);
  25046. }
  25047. // check for page break
  25048. $this->checkPageBreak((2 * $this->FontSize * $this->cell_height_ratio));
  25049. // set margins and X position
  25050. if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
  25051. $this->lMargin = $lmargin;
  25052. $this->rMargin = $rmargin;
  25053. } else {
  25054. if ($this->current_column != $current_column) {
  25055. if ($this->rtl) {
  25056. $x_start = $this->w - $this->columns[$this->current_column]['x'];
  25057. } else {
  25058. $x_start = $this->columns[$this->current_column]['x'];
  25059. }
  25060. }
  25061. $lmargin = $this->lMargin;
  25062. $rmargin = $this->rMargin;
  25063. $current_page = $this->page;
  25064. $current_column = $this->current_column;
  25065. }
  25066. $this->SetX($x_start);
  25067. $indent = ($spacer * $outline['l']);
  25068. if ($this->rtl) {
  25069. $this->x -= $indent;
  25070. $this->rMargin = $this->w - $this->x;
  25071. } else {
  25072. $this->x += $indent;
  25073. $this->lMargin = $this->x;
  25074. }
  25075. $link = $this->AddLink();
  25076. $this->SetLink($link, $outline['y'], $outline['p']);
  25077. // write the text
  25078. if ($this->rtl) {
  25079. $txt = ' '.$outline['t'];
  25080. } else {
  25081. $txt = $outline['t'].' ';
  25082. }
  25083. $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
  25084. if ($this->rtl) {
  25085. $tw = $this->x - $this->lMargin;
  25086. } else {
  25087. $tw = $this->w - $this->rMargin - $this->x;
  25088. }
  25089. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  25090. if ($this->empty_string($page)) {
  25091. $pagenum = $outline['p'];
  25092. } else {
  25093. // placemark to be replaced with the correct number
  25094. $pagenum = '{#'.($outline['p']).'}';
  25095. if ($this->isUnicodeFont()) {
  25096. $pagenum = '{'.$pagenum.'}';
  25097. }
  25098. $maxpage = max($maxpage, $outline['p']);
  25099. }
  25100. $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
  25101. $numfills = floor($fw / $this->GetStringWidth($filler));
  25102. if ($numfills > 0) {
  25103. $rowfill = str_repeat($filler, $numfills);
  25104. } else {
  25105. $rowfill = '';
  25106. }
  25107. if ($this->rtl) {
  25108. $pagenum = $pagenum.$gap.$rowfill;
  25109. } else {
  25110. $pagenum = $rowfill.$gap.$pagenum;
  25111. }
  25112. // write the number
  25113. $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
  25114. }
  25115. $page_last = $this->getPage();
  25116. $maxpage = max($maxpage, $page_last);
  25117. $numpages = $page_last - $page_first + 1;
  25118. if (!$this->empty_string($page)) {
  25119. for ($p = $page_first; $p <= $page_last; ++$p) {
  25120. // get page data
  25121. $temppage = $this->getPageBuffer($p);
  25122. for ($n = 1; $n <= $maxpage; ++$n) {
  25123. // update page numbers
  25124. $a = '{#'.$n.'}';
  25125. // get page number aliases
  25126. $pnalias = $this->getInternalPageNumberAliases($a);
  25127. // calculate replacement number
  25128. if (($n >= $page) AND ($n <= $this->numpages)) {
  25129. $np = $n + $numpages;
  25130. } else {
  25131. $np = $n;
  25132. }
  25133. $na = $this->formatTOCPageNumber(($this->starting_page_number + $np - 1));
  25134. $nu = $this->UTF8ToUTF16BE($na, false);
  25135. // replace aliases with numbers
  25136. foreach ($pnalias['u'] as $u) {
  25137. $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
  25138. if ($this->rtl) {
  25139. $nr = $nu.$this->UTF8ToUTF16BE(' '.$sfill);
  25140. } else {
  25141. $nr = $this->UTF8ToUTF16BE($sfill.' ').$nu;
  25142. }
  25143. $temppage = str_replace($u, $nr, $temppage);
  25144. }
  25145. foreach ($pnalias['a'] as $a) {
  25146. $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
  25147. if ($this->rtl) {
  25148. $nr = $na.' '.$sfill;
  25149. } else {
  25150. $nr = $sfill.' '.$na;
  25151. }
  25152. $temppage = str_replace($a, $nr, $temppage);
  25153. }
  25154. }
  25155. // save changes
  25156. $this->setPageBuffer($p, $temppage);
  25157. }
  25158. // move pages
  25159. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  25160. for ($i = 0; $i < $numpages; ++$i) {
  25161. $this->movePage($page_last, $page);
  25162. }
  25163. }
  25164. }
  25165. /**
  25166. * Output a Table Of Content Index (TOC) using HTML templates.
  25167. * This method must be called after all Bookmarks were set.
  25168. * Before calling this method you have to open the page using the addTOCPage() method.
  25169. * After calling this method you have to call endTOCPage() to close the TOC page.
  25170. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  25171. * @param $toc_name (string) name to use for TOC bookmark.
  25172. * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
  25173. * @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)
  25174. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  25175. * @param $color (array) RGB color array for title (values from 0 to 255).
  25176. * @public
  25177. * @author Nicola Asuni
  25178. * @since 5.0.001 (2010-05-06)
  25179. * @see addTOCPage(), endTOCPage(), addTOC()
  25180. */
  25181. public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
  25182. $filler = ' ';
  25183. $prev_htmlLinkColorArray = $this->htmlLinkColorArray;
  25184. $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
  25185. // set new style for link
  25186. $this->htmlLinkColorArray = array();
  25187. $this->htmlLinkFontStyle = '';
  25188. $page_first = $this->getPage();
  25189. // get the font type used for numbers in each template
  25190. $current_font = $this->FontFamily;
  25191. foreach ($templates as $level => $html) {
  25192. $dom = $this->getHtmlDomArray($html);
  25193. foreach ($dom as $key => $value) {
  25194. if ($value['value'] == '#TOC_PAGE_NUMBER#') {
  25195. $this->SetFont($dom[($key - 1)]['fontname']);
  25196. $templates['F'.$level] = $this->isUnicodeFont();
  25197. }
  25198. }
  25199. }
  25200. $this->SetFont($current_font);
  25201. $maxpage = 0; //used for pages on attached documents
  25202. foreach ($this->outlines as $key => $outline) {
  25203. // get HTML template
  25204. $row = $templates[$outline['l']];
  25205. if ($this->empty_string($page)) {
  25206. $pagenum = $outline['p'];
  25207. } else {
  25208. // placemark to be replaced with the correct number
  25209. $pagenum = '{#'.($outline['p']).'}';
  25210. if ($templates['F'.$outline['l']]) {
  25211. $pagenum = '{'.$pagenum.'}';
  25212. }
  25213. $maxpage = max($maxpage, $outline['p']);
  25214. }
  25215. // replace templates with current values
  25216. $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
  25217. $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
  25218. // add link to page
  25219. $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
  25220. // write bookmark entry
  25221. $this->writeHTML($row, false, false, true, false, '');
  25222. }
  25223. // restore link styles
  25224. $this->htmlLinkColorArray = $prev_htmlLinkColorArray;
  25225. $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
  25226. // move TOC page and replace numbers
  25227. $page_last = $this->getPage();
  25228. $maxpage = max($maxpage, $page_last);
  25229. $numpages = $page_last - $page_first + 1;
  25230. if (!$this->empty_string($page)) {
  25231. for ($p = $page_first; $p <= $page_last; ++$p) {
  25232. // get page data
  25233. $temppage = $this->getPageBuffer($p);
  25234. for ($n = 1; $n <= $maxpage; ++$n) {
  25235. // update page numbers
  25236. $a = '{#'.$n.'}';
  25237. // get page number aliases
  25238. $pnalias = $this->getInternalPageNumberAliases($a);
  25239. // calculate replacement number
  25240. if ($n >= $page) {
  25241. $np = $n + $numpages;
  25242. } else {
  25243. $np = $n;
  25244. }
  25245. $na = $this->formatTOCPageNumber(($this->starting_page_number + $np - 1));
  25246. $nu = $this->UTF8ToUTF16BE($na, false);
  25247. // replace aliases with numbers
  25248. foreach ($pnalias['u'] as $u) {
  25249. if ($correct_align) {
  25250. $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
  25251. if ($this->rtl) {
  25252. $nr = $nu.$this->UTF8ToUTF16BE(' '.$sfill);
  25253. } else {
  25254. $nr = $this->UTF8ToUTF16BE($sfill.' ').$nu;
  25255. }
  25256. } else {
  25257. $nr = $nu;
  25258. }
  25259. $temppage = str_replace($u, $nr, $temppage);
  25260. }
  25261. foreach ($pnalias['a'] as $a) {
  25262. if ($correct_align) {
  25263. $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
  25264. if ($this->rtl) {
  25265. $nr = $na.' '.$sfill;
  25266. } else {
  25267. $nr = $sfill.' '.$na;
  25268. }
  25269. } else {
  25270. $nr = $na;
  25271. }
  25272. $temppage = str_replace($a, $nr, $temppage);
  25273. }
  25274. }
  25275. // save changes
  25276. $this->setPageBuffer($p, $temppage);
  25277. }
  25278. // move pages
  25279. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  25280. for ($i = 0; $i < $numpages; ++$i) {
  25281. $this->movePage($page_last, $page);
  25282. }
  25283. }
  25284. }
  25285. /**
  25286. * Stores a copy of the current TCPDF object used for undo operation.
  25287. * @public
  25288. * @since 4.5.029 (2009-03-19)
  25289. */
  25290. public function startTransaction() {
  25291. if (isset($this->objcopy)) {
  25292. // remove previous copy
  25293. $this->commitTransaction();
  25294. }
  25295. // record current page number and Y position
  25296. $this->start_transaction_page = $this->page;
  25297. $this->start_transaction_y = $this->y;
  25298. // clone current object
  25299. $this->objcopy = $this->objclone($this);
  25300. }
  25301. /**
  25302. * Delete the copy of the current TCPDF object used for undo operation.
  25303. * @public
  25304. * @since 4.5.029 (2009-03-19)
  25305. */
  25306. public function commitTransaction() {
  25307. if (isset($this->objcopy)) {
  25308. $this->objcopy->_destroy(true, true);
  25309. unset($this->objcopy);
  25310. }
  25311. }
  25312. /**
  25313. * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
  25314. * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
  25315. * @return TCPDF object.
  25316. * @public
  25317. * @since 4.5.029 (2009-03-19)
  25318. */
  25319. public function rollbackTransaction($self=false) {
  25320. if (isset($this->objcopy)) {
  25321. if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
  25322. // truncate files to previous values
  25323. foreach ($this->objcopy->cache_file_length as $file => $length) {
  25324. $file = substr($file, 1);
  25325. $handle = fopen($file, 'r+');
  25326. ftruncate($handle, $length);
  25327. }
  25328. }
  25329. $this->_destroy(true, true);
  25330. if ($self) {
  25331. $objvars = get_object_vars($this->objcopy);
  25332. foreach ($objvars as $key => $value) {
  25333. $this->$key = $value;
  25334. }
  25335. }
  25336. return $this->objcopy;
  25337. }
  25338. return $this;
  25339. }
  25340. /**
  25341. * Creates a copy of a class object
  25342. * @param $object (object) class object to be cloned
  25343. * @return cloned object
  25344. * @public
  25345. * @since 4.5.029 (2009-03-19)
  25346. */
  25347. public function objclone($object) {
  25348. return @clone($object);
  25349. }
  25350. /**
  25351. * Determine whether a string is empty.
  25352. * @param $str (string) string to be checked
  25353. * @return boolean true if string is empty
  25354. * @public
  25355. * @since 4.5.044 (2009-04-16)
  25356. */
  25357. public function empty_string($str) {
  25358. return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
  25359. }
  25360. /**
  25361. * Find position of last occurrence of a substring in a string
  25362. * @param $haystack (string) The string to search in.
  25363. * @param $needle (string) substring to search.
  25364. * @param $offset (int) May be specified to begin searching an arbitrary number of characters into the string.
  25365. * @return Returns the position where the needle exists. Returns FALSE if the needle was not found.
  25366. * @public
  25367. * @since 4.8.038 (2010-03-13)
  25368. */
  25369. public function revstrpos($haystack, $needle, $offset = 0) {
  25370. $length = strlen($haystack);
  25371. $offset = ($offset > 0)?($length - $offset):abs($offset);
  25372. $pos = strpos(strrev($haystack), strrev($needle), $offset);
  25373. return ($pos === false)?false:($length - $pos - strlen($needle));
  25374. }
  25375. // --- MULTI COLUMNS METHODS -----------------------
  25376. /**
  25377. * Set multiple columns of the same size
  25378. * @param $numcols (int) number of columns (set to zero to disable columns mode)
  25379. * @param $width (int) column width
  25380. * @param $y (int) column starting Y position (leave empty for current Y position)
  25381. * @public
  25382. * @since 4.9.001 (2010-03-28)
  25383. */
  25384. public function setEqualColumns($numcols=0, $width=0, $y='') {
  25385. $this->columns = array();
  25386. if ($numcols < 2) {
  25387. $numcols = 0;
  25388. $this->columns = array();
  25389. } else {
  25390. // maximum column width
  25391. $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
  25392. if (($width == 0) OR ($width > $maxwidth)) {
  25393. $width = $maxwidth;
  25394. }
  25395. if ($this->empty_string($y)) {
  25396. $y = $this->y;
  25397. }
  25398. // space between columns
  25399. $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
  25400. // fill the columns array (with, space, starting Y position)
  25401. for ($i = 0; $i < $numcols; ++$i) {
  25402. $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
  25403. }
  25404. }
  25405. $this->num_columns = $numcols;
  25406. $this->current_column = 0;
  25407. $this->column_start_page = $this->page;
  25408. $this->selectColumn(0);
  25409. }
  25410. /**
  25411. * Remove columns and reset page margins.
  25412. * @public
  25413. * @since 5.9.072 (2011-04-26)
  25414. */
  25415. public function resetColumns() {
  25416. $this->lMargin = $this->original_lMargin;
  25417. $this->rMargin = $this->original_rMargin;
  25418. $this->setEqualColumns();
  25419. }
  25420. /**
  25421. * Set columns array.
  25422. * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
  25423. * @param $columns (array)
  25424. * @public
  25425. * @since 4.9.001 (2010-03-28)
  25426. */
  25427. public function setColumnsArray($columns) {
  25428. $this->columns = $columns;
  25429. $this->num_columns = count($columns);
  25430. $this->current_column = 0;
  25431. $this->column_start_page = $this->page;
  25432. $this->selectColumn(0);
  25433. }
  25434. /**
  25435. * Set position at a given column
  25436. * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
  25437. * @public
  25438. * @since 4.9.001 (2010-03-28)
  25439. */
  25440. public function selectColumn($col='') {
  25441. if (is_string($col)) {
  25442. $col = $this->current_column;
  25443. } elseif ($col >= $this->num_columns) {
  25444. $col = 0;
  25445. }
  25446. $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  25447. $enable_thead = false;
  25448. if ($this->num_columns > 1) {
  25449. if ($col != $this->current_column) {
  25450. // move Y pointer at the top of the column
  25451. if ($this->column_start_page == $this->page) {
  25452. $this->y = $this->columns[$col]['y'];
  25453. } else {
  25454. $this->y = $this->tMargin;
  25455. }
  25456. // Avoid to write table headers more than once
  25457. if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
  25458. $enable_thead = true;
  25459. $this->maxselcol['page'] = $this->page;
  25460. $this->maxselcol['column'] = $col;
  25461. }
  25462. }
  25463. $xshift = $this->colxshift;
  25464. // set X position of the current column by case
  25465. $listindent = ($this->listindentlevel * $this->listindent);
  25466. // calculate column X position
  25467. $colpos = 0;
  25468. for ($i = 0; $i < $col; ++$i) {
  25469. $colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
  25470. }
  25471. if ($this->rtl) {
  25472. $x = $this->w - $this->original_rMargin - $colpos;
  25473. $this->rMargin = ($this->w - $x + $listindent);
  25474. $this->lMargin = ($x - $this->columns[$col]['w']);
  25475. $this->x = $x - $listindent;
  25476. } else {
  25477. $x = $this->original_lMargin + $colpos;
  25478. $this->lMargin = ($x + $listindent);
  25479. $this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
  25480. $this->x = $x + $listindent;
  25481. }
  25482. $this->columns[$col]['x'] = $x;
  25483. }
  25484. $this->current_column = $col;
  25485. // fix for HTML mode
  25486. $this->newline = true;
  25487. // print HTML table header (if any)
  25488. if ((!$this->empty_string($this->thead)) AND (!$this->inthead)) {
  25489. if ($enable_thead) {
  25490. // print table header
  25491. $this->writeHTML($this->thead, false, false, false, false, '');
  25492. $this->y += $xshift['s']['V'];
  25493. // store end of header position
  25494. if (!isset($this->columns[$col]['th'])) {
  25495. $this->columns[$col]['th'] = array();
  25496. }
  25497. $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
  25498. $this->lasth = 0;
  25499. } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
  25500. $this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
  25501. }
  25502. }
  25503. // account for an html table cell over multiple columns
  25504. if ($this->rtl) {
  25505. $this->rMargin += $xshift['x'];
  25506. $this->x -= ($xshift['x'] + $xshift['p']['R']);
  25507. } else {
  25508. $this->lMargin += $xshift['x'];
  25509. $this->x += $xshift['x'] + $xshift['p']['L'];
  25510. }
  25511. }
  25512. /**
  25513. * Return the current column number
  25514. * @return int current column number
  25515. * @public
  25516. * @since 5.5.011 (2010-07-08)
  25517. */
  25518. public function getColumn() {
  25519. return $this->current_column;
  25520. }
  25521. /**
  25522. * Return the current number of columns.
  25523. * @return int number of columns
  25524. * @public
  25525. * @since 5.8.018 (2010-08-25)
  25526. */
  25527. public function getNumberOfColumns() {
  25528. return $this->num_columns;
  25529. }
  25530. /**
  25531. * Serialize an array of parameters to be used with TCPDF tag in HTML code.
  25532. * @param $pararray (array) parameters array
  25533. * @return sting containing serialized data
  25534. * @public
  25535. * @since 4.9.006 (2010-04-02)
  25536. */
  25537. public function serializeTCPDFtagParameters($pararray) {
  25538. return urlencode(serialize($pararray));
  25539. }
  25540. /**
  25541. * Set Text rendering mode.
  25542. * @param $stroke (int) outline size in user units (0 = disable).
  25543. * @param $fill (boolean) if true fills the text (default).
  25544. * @param $clip (boolean) if true activate clipping mode
  25545. * @public
  25546. * @since 4.9.008 (2009-04-02)
  25547. */
  25548. public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
  25549. // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
  25550. // convert text rendering parameters
  25551. if ($stroke < 0) {
  25552. $stroke = 0;
  25553. }
  25554. if ($fill === true) {
  25555. if ($stroke > 0) {
  25556. if ($clip === true) {
  25557. // Fill, then stroke text and add to path for clipping
  25558. $textrendermode = 6;
  25559. } else {
  25560. // Fill, then stroke text
  25561. $textrendermode = 2;
  25562. }
  25563. $textstrokewidth = $stroke;
  25564. } else {
  25565. if ($clip === true) {
  25566. // Fill text and add to path for clipping
  25567. $textrendermode = 4;
  25568. } else {
  25569. // Fill text
  25570. $textrendermode = 0;
  25571. }
  25572. }
  25573. } else {
  25574. if ($stroke > 0) {
  25575. if ($clip === true) {
  25576. // Stroke text and add to path for clipping
  25577. $textrendermode = 5;
  25578. } else {
  25579. // Stroke text
  25580. $textrendermode = 1;
  25581. }
  25582. $textstrokewidth = $stroke;
  25583. } else {
  25584. if ($clip === true) {
  25585. // Add text to path for clipping
  25586. $textrendermode = 7;
  25587. } else {
  25588. // Neither fill nor stroke text (invisible)
  25589. $textrendermode = 3;
  25590. }
  25591. }
  25592. }
  25593. $this->textrendermode = $textrendermode;
  25594. $this->textstrokewidth = $stroke * $this->k;
  25595. }
  25596. /**
  25597. * Returns an array of chars containing soft hyphens.
  25598. * @param $word (array) array of chars
  25599. * @param $patterns (array) Array of hypenation patterns.
  25600. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algoritm.
  25601. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  25602. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  25603. * @param $charmin (int) Minimum word length to apply the hyphenation algoritm.
  25604. * @param $charmax (int) Maximum length of broken piece of word.
  25605. * @return array text with soft hyphens
  25606. * @author Nicola Asuni
  25607. * @since 4.9.012 (2010-04-12)
  25608. * @protected
  25609. */
  25610. protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  25611. $hyphenword = array(); // hyphens positions
  25612. $numchars = count($word);
  25613. if ($numchars <= $charmin) {
  25614. return $word;
  25615. }
  25616. $word_string = $this->UTF8ArrSubString($word);
  25617. // some words will be returned as-is
  25618. $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})(\]?)$/';
  25619. if (preg_match($pattern, $word_string) > 0) {
  25620. // email
  25621. return $word;
  25622. }
  25623. $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})(\]?)$/';
  25624. if (preg_match($pattern, $word_string) > 0) {
  25625. // URL
  25626. return $word;
  25627. }
  25628. if (isset($dictionary[$word_string])) {
  25629. return $this->UTF8StringToArray($dictionary[$word_string]);
  25630. }
  25631. // suround word with '_' characters
  25632. $tmpword = array_merge(array(95), $word, array(95));
  25633. $tmpnumchars = $numchars + 2;
  25634. $maxpos = $tmpnumchars - $charmin;
  25635. for ($pos = 0; $pos < $maxpos; ++$pos) {
  25636. $imax = min(($tmpnumchars - $pos), $charmax);
  25637. for ($i = $charmin; $i <= $imax; ++$i) {
  25638. $subword = strtolower($this->UTF8ArrSubString($tmpword, $pos, $pos + $i));
  25639. if (isset($patterns[$subword])) {
  25640. $pattern = $this->UTF8StringToArray($patterns[$subword]);
  25641. $pattern_length = count($pattern);
  25642. $digits = 1;
  25643. for ($j = 0; $j < $pattern_length; ++$j) {
  25644. // check if $pattern[$j] is a number
  25645. if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
  25646. if ($j == 0) {
  25647. $zero = $pos - 1;
  25648. } else {
  25649. $zero = $pos + $j - $digits;
  25650. }
  25651. if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] != $pattern[$j])) {
  25652. $hyphenword[$zero] = $this->unichr($pattern[$j]);
  25653. }
  25654. ++$digits;
  25655. }
  25656. }
  25657. }
  25658. }
  25659. }
  25660. $inserted = 0;
  25661. $maxpos = $numchars - $rightmin;
  25662. for ($i = $leftmin; $i <= $maxpos; ++$i) {
  25663. if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
  25664. // 173 = soft hyphen character
  25665. array_splice($word, $i + $inserted, 0, 173);
  25666. ++$inserted;
  25667. }
  25668. }
  25669. return $word;
  25670. }
  25671. /**
  25672. * Returns an array of hyphenation patterns.
  25673. * @param $file (string) TEX file containing hypenation patterns. TEX pattrns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
  25674. * @return array of hyphenation patterns
  25675. * @author Nicola Asuni
  25676. * @since 4.9.012 (2010-04-12)
  25677. * @public
  25678. */
  25679. public function getHyphenPatternsFromTEX($file) {
  25680. // TEX patterns are available at:
  25681. // http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
  25682. $data = file_get_contents($file);
  25683. $patterns = array();
  25684. // remove comments
  25685. $data = preg_replace('/\%[^\n]*/', '', $data);
  25686. // extract the patterns part
  25687. preg_match('/\\\\patterns\{([^\}]*)\}/i', $data, $matches);
  25688. $data = trim(substr($matches[0], 10, -1));
  25689. // extract each pattern
  25690. $patterns_array = preg_split('/[\s]+/', $data);
  25691. // create new language array of patterns
  25692. $patterns = array();
  25693. foreach($patterns_array as $val) {
  25694. if (!$this->empty_string($val)) {
  25695. $val = trim($val);
  25696. $val = str_replace('\'', '\\\'', $val);
  25697. $key = preg_replace('/[0-9]+/', '', $val);
  25698. $patterns[$key] = $val;
  25699. }
  25700. }
  25701. return $patterns;
  25702. }
  25703. /**
  25704. * Returns text with soft hyphens.
  25705. * @param $text (string) text to process
  25706. * @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/
  25707. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algoritm.
  25708. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  25709. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  25710. * @param $charmin (int) Minimum word length to apply the hyphenation algoritm.
  25711. * @param $charmax (int) Maximum length of broken piece of word.
  25712. * @return array text with soft hyphens
  25713. * @author Nicola Asuni
  25714. * @since 4.9.012 (2010-04-12)
  25715. * @public
  25716. */
  25717. public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  25718. $text = $this->unhtmlentities($text);
  25719. $word = array(); // last word
  25720. $txtarr = array(); // text to be returned
  25721. $intag = false; // true if we are inside an HTML tag
  25722. if (!is_array($patterns)) {
  25723. $patterns = $this->getHyphenPatternsFromTEX($patterns);
  25724. }
  25725. // get array of characters
  25726. $unichars = $this->UTF8StringToArray($text);
  25727. // for each char
  25728. foreach ($unichars as $char) {
  25729. if ((!$intag) AND $this->unicode->uni_type[$char] == 'L') {
  25730. // letter character
  25731. $word[] = $char;
  25732. } else {
  25733. // other type of character
  25734. if (!$this->empty_string($word)) {
  25735. // hypenate the word
  25736. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  25737. $word = array();
  25738. }
  25739. $txtarr[] = $char;
  25740. if (chr($char) == '<') {
  25741. // we are inside an HTML tag
  25742. $intag = true;
  25743. } elseif ($intag AND (chr($char) == '>')) {
  25744. // end of HTML tag
  25745. $intag = false;
  25746. }
  25747. }
  25748. }
  25749. if (!$this->empty_string($word)) {
  25750. // hypenate the word
  25751. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  25752. }
  25753. // convert char array to string and return
  25754. return $this->UTF8ArrSubString($txtarr);
  25755. }
  25756. /**
  25757. * Enable/disable rasterization of vector images using ImageMagick library.
  25758. * @param $mode (boolean) if true enable rasterization, false otherwise.
  25759. * @public
  25760. * @since 5.0.000 (2010-04-27)
  25761. */
  25762. public function setRasterizeVectorImages($mode) {
  25763. $this->rasterize_vector_images = $mode;
  25764. }
  25765. /**
  25766. * Get the Path-Painting Operators.
  25767. * @param $style (string) Style of rendering. Possible values are:
  25768. * <ul>
  25769. * <li>S or D: Stroke the path.</li>
  25770. * <li>s or d: Close and stroke the path.</li>
  25771. * <li>f or F: Fill the path, using the nonzero winding number rule to determine the region to fill.</li>
  25772. * <li>f* or F*: Fill the path, using the even-odd rule to determine the region to fill.</li>
  25773. * <li>B or FD or DF: Fill and then stroke the path, using the nonzero winding number rule to determine the region to fill.</li>
  25774. * <li>B* or F*D or DF*: Fill and then stroke the path, using the even-odd rule to determine the region to fill.</li>
  25775. * <li>b or fd or df: Close, fill, and then stroke the path, using the nonzero winding number rule to determine the region to fill.</li>
  25776. * <li>b or f*d or df*: Close, fill, and then stroke the path, using the even-odd rule to determine the region to fill.</li>
  25777. * <li>CNZ: Clipping mode using the even-odd rule to determine which regions lie inside the clipping path.</li>
  25778. * <li>CEO: Clipping mode using the nonzero winding number rule to determine which regions lie inside the clipping path</li>
  25779. * <li>n: End the path object without filling or stroking it.</li>
  25780. * </ul>
  25781. * @param $default (string) default style
  25782. * @author Nicola Asuni
  25783. * @since 5.0.000 (2010-04-30)
  25784. * @protected
  25785. */
  25786. protected function getPathPaintOperator($style, $default='S') {
  25787. $op = '';
  25788. switch($style) {
  25789. case 'S':
  25790. case 'D': {
  25791. $op = 'S';
  25792. break;
  25793. }
  25794. case 's':
  25795. case 'd': {
  25796. $op = 's';
  25797. break;
  25798. }
  25799. case 'f':
  25800. case 'F': {
  25801. $op = 'f';
  25802. break;
  25803. }
  25804. case 'f*':
  25805. case 'F*': {
  25806. $op = 'f*';
  25807. break;
  25808. }
  25809. case 'B':
  25810. case 'FD':
  25811. case 'DF': {
  25812. $op = 'B';
  25813. break;
  25814. }
  25815. case 'B*':
  25816. case 'F*D':
  25817. case 'DF*': {
  25818. $op = 'B*';
  25819. break;
  25820. }
  25821. case 'b':
  25822. case 'fd':
  25823. case 'df': {
  25824. $op = 'b';
  25825. break;
  25826. }
  25827. case 'b*':
  25828. case 'f*d':
  25829. case 'df*': {
  25830. $op = 'b*';
  25831. break;
  25832. }
  25833. case 'CNZ': {
  25834. $op = 'W n';
  25835. break;
  25836. }
  25837. case 'CEO': {
  25838. $op = 'W* n';
  25839. break;
  25840. }
  25841. case 'n': {
  25842. $op = 'n';
  25843. break;
  25844. }
  25845. default: {
  25846. if (!empty($default)) {
  25847. $op = $this->getPathPaintOperator($default, '');
  25848. } else {
  25849. $op = '';
  25850. }
  25851. }
  25852. }
  25853. return $op;
  25854. }
  25855. /**
  25856. * Enable or disable default option for font subsetting.
  25857. * @param $enable (boolean) if true enable font subsetting by default.
  25858. * @author Nicola Asuni
  25859. * @public
  25860. * @since 5.3.002 (2010-06-07)
  25861. */
  25862. public function setFontSubsetting($enable=true) {
  25863. if ($this->pdfa_mode) {
  25864. $this->font_subsetting = false;
  25865. } else {
  25866. $this->font_subsetting = $enable ? true : false;
  25867. }
  25868. }
  25869. /**
  25870. * Return the default option for font subsetting.
  25871. * @return boolean default font subsetting state.
  25872. * @author Nicola Asuni
  25873. * @public
  25874. * @since 5.3.002 (2010-06-07)
  25875. */
  25876. public function getFontSubsetting() {
  25877. return $this->font_subsetting;
  25878. }
  25879. /**
  25880. * Left trim the input string
  25881. * @param $str (string) string to trim
  25882. * @param $replace (string) string that replace spaces.
  25883. * @return left trimmed string
  25884. * @author Nicola Asuni
  25885. * @public
  25886. * @since 5.8.000 (2010-08-11)
  25887. */
  25888. public function stringLeftTrim($str, $replace='') {
  25889. return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
  25890. }
  25891. /**
  25892. * Right trim the input string
  25893. * @param $str (string) string to trim
  25894. * @param $replace (string) string that replace spaces.
  25895. * @return right trimmed string
  25896. * @author Nicola Asuni
  25897. * @public
  25898. * @since 5.8.000 (2010-08-11)
  25899. */
  25900. public function stringRightTrim($str, $replace='') {
  25901. return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
  25902. }
  25903. /**
  25904. * Trim the input string
  25905. * @param $str (string) string to trim
  25906. * @param $replace (string) string that replace spaces.
  25907. * @return trimmed string
  25908. * @author Nicola Asuni
  25909. * @public
  25910. * @since 5.8.000 (2010-08-11)
  25911. */
  25912. public function stringTrim($str, $replace='') {
  25913. $str = $this->stringLeftTrim($str, $replace);
  25914. $str = $this->stringRightTrim($str, $replace);
  25915. return $str;
  25916. }
  25917. /**
  25918. * Return true if the current font is unicode type.
  25919. * @return true for unicode font, false otherwise.
  25920. * @author Nicola Asuni
  25921. * @public
  25922. * @since 5.8.002 (2010-08-14)
  25923. */
  25924. public function isUnicodeFont() {
  25925. return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
  25926. }
  25927. /**
  25928. * Return normalized font name
  25929. * @param $fontfamily (string) property string containing font family names
  25930. * @return string normalized font name
  25931. * @author Nicola Asuni
  25932. * @public
  25933. * @since 5.8.004 (2010-08-17)
  25934. */
  25935. public function getFontFamilyName($fontfamily) {
  25936. // remove spaces and symbols
  25937. $fontfamily = preg_replace('/[^a-z0-9\,]/', '', strtolower($fontfamily));
  25938. // extract all font names
  25939. $fontslist = preg_split('/[,]/', $fontfamily);
  25940. // find first valid font name
  25941. foreach ($fontslist as $font) {
  25942. // replace font variations
  25943. $font = preg_replace('/italic$/', 'I', $font);
  25944. $font = preg_replace('/oblique$/', 'I', $font);
  25945. $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
  25946. // replace common family names and core fonts
  25947. $pattern = array();
  25948. $replacement = array();
  25949. $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
  25950. $replacement[] = 'times';
  25951. $pattern[] = '/^sansserif/';
  25952. $replacement[] = 'helvetica';
  25953. $pattern[] = '/^monospace/';
  25954. $replacement[] = 'courier';
  25955. $font = preg_replace($pattern, $replacement, $font);
  25956. if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
  25957. return $font;
  25958. }
  25959. }
  25960. // return current font as default
  25961. return $this->CurrentFont['fontkey'];
  25962. }
  25963. /**
  25964. * Start a new XObject Template.
  25965. * 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).
  25966. * 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.
  25967. * Note: X,Y coordinates will be reset to 0,0.
  25968. * @param $w (int) Template width in user units (empty string or zero = page width less margins).
  25969. * @param $h (int) Template height in user units (empty string or zero = page height less margins).
  25970. * @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).
  25971. * @return int the XObject Template ID in case of success or false in case of error.
  25972. * @author Nicola Asuni
  25973. * @public
  25974. * @since 5.8.017 (2010-08-24)
  25975. * @see endTemplate(), printTemplate()
  25976. */
  25977. public function startTemplate($w=0, $h=0, $group=false) {
  25978. if ($this->inxobj) {
  25979. // we are already inside an XObject template
  25980. return false;
  25981. }
  25982. $this->inxobj = true;
  25983. ++$this->n;
  25984. // XObject ID
  25985. $this->xobjid = 'XT'.$this->n;
  25986. // object ID
  25987. $this->xobjects[$this->xobjid] = array('n' => $this->n);
  25988. // store current graphic state
  25989. $this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
  25990. // initialize data
  25991. $this->xobjects[$this->xobjid]['intmrk'] = 0;
  25992. $this->xobjects[$this->xobjid]['transfmrk'] = array();
  25993. $this->xobjects[$this->xobjid]['outdata'] = '';
  25994. $this->xobjects[$this->xobjid]['xobjects'] = array();
  25995. $this->xobjects[$this->xobjid]['images'] = array();
  25996. $this->xobjects[$this->xobjid]['fonts'] = array();
  25997. $this->xobjects[$this->xobjid]['annotations'] = array();
  25998. $this->xobjects[$this->xobjid]['extgstates'] = array();
  25999. $this->xobjects[$this->xobjid]['gradients'] = array();
  26000. $this->xobjects[$this->xobjid]['spot_colors'] = array();
  26001. // set new environment
  26002. $this->num_columns = 1;
  26003. $this->current_column = 0;
  26004. $this->SetAutoPageBreak(false);
  26005. if (($w === '') OR ($w <= 0)) {
  26006. $w = $this->w - $this->lMargin - $this->rMargin;
  26007. }
  26008. if (($h === '') OR ($h <= 0)) {
  26009. $h = $this->h - $this->tMargin - $this->bMargin;
  26010. }
  26011. $this->xobjects[$this->xobjid]['x'] = 0;
  26012. $this->xobjects[$this->xobjid]['y'] = 0;
  26013. $this->xobjects[$this->xobjid]['w'] = $w;
  26014. $this->xobjects[$this->xobjid]['h'] = $h;
  26015. $this->w = $w;
  26016. $this->h = $h;
  26017. $this->wPt = $this->w * $this->k;
  26018. $this->hPt = $this->h * $this->k;
  26019. $this->fwPt = $this->wPt;
  26020. $this->fhPt = $this->hPt;
  26021. $this->x = 0;
  26022. $this->y = 0;
  26023. $this->lMargin = 0;
  26024. $this->rMargin = 0;
  26025. $this->tMargin = 0;
  26026. $this->bMargin = 0;
  26027. // set group mode
  26028. $this->xobjects[$this->xobjid]['group'] = $group;
  26029. return $this->xobjid;
  26030. }
  26031. /**
  26032. * End the current XObject Template started with startTemplate() and restore the previous graphic state.
  26033. * 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).
  26034. * 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.
  26035. * @return int the XObject Template ID in case of success or false in case of error.
  26036. * @author Nicola Asuni
  26037. * @public
  26038. * @since 5.8.017 (2010-08-24)
  26039. * @see startTemplate(), printTemplate()
  26040. */
  26041. public function endTemplate() {
  26042. if (!$this->inxobj) {
  26043. // we are not inside a template
  26044. return false;
  26045. }
  26046. $this->inxobj = false;
  26047. // restore previous graphic state
  26048. $this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
  26049. return $this->xobjid;
  26050. }
  26051. /**
  26052. * Print an XObject Template.
  26053. * You can print an XObject Template inside the currently opened Template.
  26054. * 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).
  26055. * 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.
  26056. * @param $id (string) The ID of XObject Template to print.
  26057. * @param $x (int) X position in user units (empty string = current x position)
  26058. * @param $y (int) Y position in user units (empty string = current y position)
  26059. * @param $w (int) Width in user units (zero = remaining page width)
  26060. * @param $h (int) Height in user units (zero = remaining page height)
  26061. * @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>
  26062. * @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>
  26063. * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
  26064. * @author Nicola Asuni
  26065. * @public
  26066. * @since 5.8.017 (2010-08-24)
  26067. * @see startTemplate(), endTemplate()
  26068. */
  26069. public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
  26070. if (!isset($this->xobjects[$id])) {
  26071. $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
  26072. }
  26073. if ($this->inxobj) {
  26074. if ($id == $this->xobjid) {
  26075. // close current template
  26076. $this->endTemplate();
  26077. } else {
  26078. // use the template as resource for the template currently opened
  26079. $this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
  26080. }
  26081. }
  26082. // set default values
  26083. if ($x === '') {
  26084. $x = $this->x;
  26085. }
  26086. if ($y === '') {
  26087. $y = $this->y;
  26088. }
  26089. // check page for no-write regions and adapt page margins if necessary
  26090. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  26091. $ow = $this->xobjects[$id]['w'];
  26092. $oh = $this->xobjects[$id]['h'];
  26093. // calculate template width and height on document
  26094. if (($w <= 0) AND ($h <= 0)) {
  26095. $w = $ow;
  26096. $h = $oh;
  26097. } elseif ($w <= 0) {
  26098. $w = $h * $ow / $oh;
  26099. } elseif ($h <= 0) {
  26100. $h = $w * $oh / $ow;
  26101. }
  26102. // fit the template on available space
  26103. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  26104. // set page alignment
  26105. $rb_y = $y + $h;
  26106. // set alignment
  26107. if ($this->rtl) {
  26108. if ($palign == 'L') {
  26109. $xt = $this->lMargin;
  26110. } elseif ($palign == 'C') {
  26111. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  26112. } elseif ($palign == 'R') {
  26113. $xt = $this->w - $this->rMargin - $w;
  26114. } else {
  26115. $xt = $x - $w;
  26116. }
  26117. $rb_x = $xt;
  26118. } else {
  26119. if ($palign == 'L') {
  26120. $xt = $this->lMargin;
  26121. } elseif ($palign == 'C') {
  26122. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  26123. } elseif ($palign == 'R') {
  26124. $xt = $this->w - $this->rMargin - $w;
  26125. } else {
  26126. $xt = $x;
  26127. }
  26128. $rb_x = $xt + $w;
  26129. }
  26130. // print XObject Template + Transformation matrix
  26131. $this->StartTransform();
  26132. // translate and scale
  26133. $sx = ($w / $this->xobjects[$id]['w']);
  26134. $sy = ($h / $this->xobjects[$id]['h']);
  26135. $tm = array();
  26136. $tm[0] = $sx;
  26137. $tm[1] = 0;
  26138. $tm[2] = 0;
  26139. $tm[3] = $sy;
  26140. $tm[4] = $xt * $this->k;
  26141. $tm[5] = ($this->h - $h - $y) * $this->k;
  26142. $this->Transform($tm);
  26143. // set object
  26144. $this->_out('/'.$id.' Do');
  26145. $this->StopTransform();
  26146. // add annotations
  26147. if (!empty($this->xobjects[$id]['annotations'])) {
  26148. foreach ($this->xobjects[$id]['annotations'] as $annot) {
  26149. // transform original coordinates
  26150. $coordlt = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
  26151. $ax = ($coordlt[4] / $this->k);
  26152. $ay = ($this->h - $h - ($coordlt[5] / $this->k));
  26153. $coordrb = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
  26154. $aw = ($coordrb[4] / $this->k) - $ax;
  26155. $ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
  26156. $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
  26157. }
  26158. }
  26159. // set pointer to align the next text/objects
  26160. switch($align) {
  26161. case 'T': {
  26162. $this->y = $y;
  26163. $this->x = $rb_x;
  26164. break;
  26165. }
  26166. case 'M': {
  26167. $this->y = $y + round($h/2);
  26168. $this->x = $rb_x;
  26169. break;
  26170. }
  26171. case 'B': {
  26172. $this->y = $rb_y;
  26173. $this->x = $rb_x;
  26174. break;
  26175. }
  26176. case 'N': {
  26177. $this->SetY($rb_y);
  26178. break;
  26179. }
  26180. default:{
  26181. break;
  26182. }
  26183. }
  26184. }
  26185. /**
  26186. * Set the percentage of character stretching.
  26187. * @param $perc (int) percentage of stretching (100 = no stretching)
  26188. * @author Nicola Asuni
  26189. * @public
  26190. * @since 5.9.000 (2010-09-29)
  26191. */
  26192. public function setFontStretching($perc=100) {
  26193. $this->font_stretching = $perc;
  26194. }
  26195. /**
  26196. * Get the percentage of character stretching.
  26197. * @return float stretching value
  26198. * @author Nicola Asuni
  26199. * @public
  26200. * @since 5.9.000 (2010-09-29)
  26201. */
  26202. public function getFontStretching() {
  26203. return $this->font_stretching;
  26204. }
  26205. /**
  26206. * Set the amount to increase or decrease the space between characters in a text.
  26207. * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
  26208. * @author Nicola Asuni
  26209. * @public
  26210. * @since 5.9.000 (2010-09-29)
  26211. */
  26212. public function setFontSpacing($spacing=0) {
  26213. $this->font_spacing = $spacing;
  26214. }
  26215. /**
  26216. * Get the amount to increase or decrease the space between characters in a text.
  26217. * @return int font spacing (tracking/kerning) value
  26218. * @author Nicola Asuni
  26219. * @public
  26220. * @since 5.9.000 (2010-09-29)
  26221. */
  26222. public function getFontSpacing() {
  26223. return $this->font_spacing;
  26224. }
  26225. /**
  26226. * Return an array of no-write page regions
  26227. * @return array of no-write page regions
  26228. * @author Nicola Asuni
  26229. * @public
  26230. * @since 5.9.003 (2010-10-13)
  26231. * @see setPageRegions(), addPageRegion()
  26232. */
  26233. public function getPageRegions() {
  26234. return $this->page_regions;
  26235. }
  26236. /**
  26237. * Set no-write regions on page.
  26238. * 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.
  26239. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  26240. * You can set multiple regions for the same page.
  26241. * @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.
  26242. * @author Nicola Asuni
  26243. * @public
  26244. * @since 5.9.003 (2010-10-13)
  26245. * @see addPageRegion(), getPageRegions()
  26246. */
  26247. public function setPageRegions($regions=array()) {
  26248. // empty current regions array
  26249. $this->page_regions = array();
  26250. // add regions
  26251. foreach ($regions as $data) {
  26252. $this->addPageRegion($data);
  26253. }
  26254. }
  26255. /**
  26256. * Add a single no-write region on selected page.
  26257. * 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.
  26258. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  26259. * You can set multiple regions for the same page.
  26260. * @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).
  26261. * @author Nicola Asuni
  26262. * @public
  26263. * @since 5.9.003 (2010-10-13)
  26264. * @see setPageRegions(), getPageRegions()
  26265. */
  26266. public function addPageRegion($region) {
  26267. if (!isset($region['page']) OR empty($region['page'])) {
  26268. $region['page'] = $this->page;
  26269. }
  26270. if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
  26271. AND isset($region['yt']) AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
  26272. AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
  26273. $this->page_regions[] = $region;
  26274. }
  26275. }
  26276. /**
  26277. * Remove a single no-write region.
  26278. * @param $key (int) region key
  26279. * @author Nicola Asuni
  26280. * @public
  26281. * @since 5.9.003 (2010-10-13)
  26282. * @see setPageRegions(), getPageRegions()
  26283. */
  26284. public function removePageRegion($key) {
  26285. if (isset($this->page_regions[$key])) {
  26286. unset($this->page_regions[$key]);
  26287. }
  26288. }
  26289. /**
  26290. * Check page for no-write regions and adapt current coordinates and page margins if necessary.
  26291. * 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.
  26292. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  26293. * @param $h (float) height of the text/image/object to print in user units
  26294. * @param $x (float) current X coordinate in user units
  26295. * @param $y (float) current Y coordinate in user units
  26296. * @return array($x, $y)
  26297. * @author Nicola Asuni
  26298. * @protected
  26299. * @since 5.9.003 (2010-10-13)
  26300. */
  26301. protected function checkPageRegions($h, $x, $y) {
  26302. // set default values
  26303. if ($x === '') {
  26304. $x = $this->x;
  26305. }
  26306. if ($y === '') {
  26307. $y = $this->y;
  26308. }
  26309. if (empty($this->page_regions)) {
  26310. // no page regions defined
  26311. return array($x, $y);
  26312. }
  26313. if (empty($h)) {
  26314. $h = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  26315. }
  26316. // check for page break
  26317. if ($this->checkPageBreak($h, $y)) {
  26318. // the content will be printed on a new page
  26319. $x = $this->x;
  26320. $y = $this->y;
  26321. }
  26322. if ($this->num_columns > 1) {
  26323. if ($this->rtl) {
  26324. $this->lMargin = $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w'];
  26325. } else {
  26326. $this->rMargin = $this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w'];
  26327. }
  26328. } else {
  26329. if ($this->rtl) {
  26330. $this->lMargin = $this->original_lMargin;
  26331. } else {
  26332. $this->rMargin = $this->original_rMargin;
  26333. }
  26334. }
  26335. // adjust coordinates and page margins
  26336. foreach ($this->page_regions as $regid => $regdata) {
  26337. if ($regdata['page'] == $this->page) {
  26338. // check region boundaries
  26339. if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
  26340. // Y is inside the region
  26341. $minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
  26342. $yt = max($y, $regdata['yt']);
  26343. $yb = min(($yt + $h), $regdata['yb']);
  26344. $xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
  26345. $xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
  26346. if ($regdata['side'] == 'L') { // left side
  26347. $new_margin = max($xt, $xb);
  26348. if ($this->lMargin < $new_margin) {
  26349. if ($this->rtl) {
  26350. // adjust left page margin
  26351. $this->lMargin = $new_margin;
  26352. }
  26353. if ($x < $new_margin) {
  26354. // adjust x position
  26355. $x = $new_margin;
  26356. if ($new_margin > ($this->w - $this->rMargin)) {
  26357. // adjust y position
  26358. $y = $regdata['yb'] - $h;
  26359. }
  26360. }
  26361. }
  26362. } elseif ($regdata['side'] == 'R') { // right side
  26363. $new_margin = min($xt, $xb);
  26364. if (($this->w - $this->rMargin) > $new_margin) {
  26365. if (!$this->rtl) {
  26366. // adjust right page margin
  26367. $this->rMargin = ($this->w - $new_margin);
  26368. }
  26369. if ($x > $new_margin) {
  26370. // adjust x position
  26371. $x = $new_margin;
  26372. if ($new_margin > $this->lMargin) {
  26373. // adjust y position
  26374. $y = $regdata['yb'] - $h;
  26375. }
  26376. }
  26377. }
  26378. }
  26379. }
  26380. }
  26381. }
  26382. return array($x, $y);
  26383. }
  26384. // --- SVG METHODS ---------------------------------------------------------
  26385. /**
  26386. * Embedd a Scalable Vector Graphics (SVG) image.
  26387. * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  26388. * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
  26389. * @param $x (float) Abscissa of the upper-left corner.
  26390. * @param $y (float) Ordinate of the upper-left corner.
  26391. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  26392. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  26393. * @param $link (mixed) URL or identifier returned by AddLink().
  26394. * @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.
  26395. * @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>
  26396. * @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)))
  26397. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  26398. * @author Nicola Asuni
  26399. * @since 5.0.000 (2010-05-02)
  26400. * @public
  26401. */
  26402. public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
  26403. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  26404. // convert SVG to raster image using GD or ImageMagick libraries
  26405. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  26406. }
  26407. if ($file{0} === '@') { // image from string
  26408. $this->svgdir = '';
  26409. $svgdata = substr($file, 1);
  26410. } else { // SVG file
  26411. $this->svgdir = dirname($file);
  26412. $svgdata = file_get_contents($file);
  26413. }
  26414. if ($svgdata === false) {
  26415. $this->Error('SVG file not found: '.$file);
  26416. }
  26417. if ($x === '') {
  26418. $x = $this->x;
  26419. }
  26420. if ($y === '') {
  26421. $y = $this->y;
  26422. }
  26423. // check page for no-write regions and adapt page margins if necessary
  26424. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  26425. $k = $this->k;
  26426. $ox = 0;
  26427. $oy = 0;
  26428. $ow = $w;
  26429. $oh = $h;
  26430. $aspect_ratio_align = 'xMidYMid';
  26431. $aspect_ratio_ms = 'meet';
  26432. $regs = array();
  26433. // get original image width and height
  26434. preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
  26435. if (isset($regs[1]) AND !empty($regs[1])) {
  26436. $tmp = array();
  26437. if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  26438. $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  26439. }
  26440. $tmp = array();
  26441. if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  26442. $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  26443. }
  26444. $tmp = array();
  26445. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  26446. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  26447. }
  26448. $tmp = array();
  26449. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  26450. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  26451. }
  26452. $tmp = array();
  26453. $view_box = array();
  26454. if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
  26455. if (count($tmp) == 5) {
  26456. array_shift($tmp);
  26457. foreach ($tmp as $key => $val) {
  26458. $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  26459. }
  26460. $ox = $view_box[0];
  26461. $oy = $view_box[1];
  26462. }
  26463. // get aspect ratio
  26464. $tmp = array();
  26465. if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  26466. $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
  26467. switch (count($aspect_ratio)) {
  26468. case 3: {
  26469. $aspect_ratio_align = $aspect_ratio[1];
  26470. $aspect_ratio_ms = $aspect_ratio[2];
  26471. break;
  26472. }
  26473. case 2: {
  26474. $aspect_ratio_align = $aspect_ratio[0];
  26475. $aspect_ratio_ms = $aspect_ratio[1];
  26476. break;
  26477. }
  26478. case 1: {
  26479. $aspect_ratio_align = $aspect_ratio[0];
  26480. $aspect_ratio_ms = 'meet';
  26481. break;
  26482. }
  26483. }
  26484. }
  26485. }
  26486. }
  26487. // calculate image width and height on document
  26488. if (($w <= 0) AND ($h <= 0)) {
  26489. // convert image size to document unit
  26490. $w = $ow;
  26491. $h = $oh;
  26492. } elseif ($w <= 0) {
  26493. $w = $h * $ow / $oh;
  26494. } elseif ($h <= 0) {
  26495. $h = $w * $oh / $ow;
  26496. }
  26497. // fit the image on available space
  26498. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  26499. if ($this->rasterize_vector_images) {
  26500. // convert SVG to raster image using GD or ImageMagick libraries
  26501. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  26502. }
  26503. // set alignment
  26504. $this->img_rb_y = $y + $h;
  26505. // set alignment
  26506. if ($this->rtl) {
  26507. if ($palign == 'L') {
  26508. $ximg = $this->lMargin;
  26509. } elseif ($palign == 'C') {
  26510. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  26511. } elseif ($palign == 'R') {
  26512. $ximg = $this->w - $this->rMargin - $w;
  26513. } else {
  26514. $ximg = $x - $w;
  26515. }
  26516. $this->img_rb_x = $ximg;
  26517. } else {
  26518. if ($palign == 'L') {
  26519. $ximg = $this->lMargin;
  26520. } elseif ($palign == 'C') {
  26521. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  26522. } elseif ($palign == 'R') {
  26523. $ximg = $this->w - $this->rMargin - $w;
  26524. } else {
  26525. $ximg = $x;
  26526. }
  26527. $this->img_rb_x = $ximg + $w;
  26528. }
  26529. // store current graphic vars
  26530. $gvars = $this->getGraphicVars();
  26531. // store SVG position and scale factors
  26532. $svgoffset_x = ($ximg - $ox) * $this->k;
  26533. $svgoffset_y = -($y - $oy) * $this->k;
  26534. if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
  26535. $ow = $view_box[2];
  26536. $oh = $view_box[3];
  26537. } else {
  26538. if ($ow <= 0) {
  26539. $ow = $w;
  26540. }
  26541. if ($oh <= 0) {
  26542. $oh = $h;
  26543. }
  26544. }
  26545. $svgscale_x = $w / $ow;
  26546. $svgscale_y = $h / $oh;
  26547. // scaling and alignment
  26548. if ($aspect_ratio_align != 'none') {
  26549. // store current scaling values
  26550. $svgscale_old_x = $svgscale_x;
  26551. $svgscale_old_y = $svgscale_y;
  26552. // force uniform scaling
  26553. if ($aspect_ratio_ms == 'slice') {
  26554. // the entire viewport is covered by the viewBox
  26555. if ($svgscale_x > $svgscale_y) {
  26556. $svgscale_y = $svgscale_x;
  26557. } elseif ($svgscale_x < $svgscale_y) {
  26558. $svgscale_x = $svgscale_y;
  26559. }
  26560. } else { // meet
  26561. // the entire viewBox is visible within the viewport
  26562. if ($svgscale_x < $svgscale_y) {
  26563. $svgscale_y = $svgscale_x;
  26564. } elseif ($svgscale_x > $svgscale_y) {
  26565. $svgscale_x = $svgscale_y;
  26566. }
  26567. }
  26568. // correct X alignment
  26569. switch (substr($aspect_ratio_align, 1, 3)) {
  26570. case 'Min': {
  26571. // do nothing
  26572. break;
  26573. }
  26574. case 'Max': {
  26575. $svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
  26576. break;
  26577. }
  26578. default:
  26579. case 'Mid': {
  26580. $svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
  26581. break;
  26582. }
  26583. }
  26584. // correct Y alignment
  26585. switch (substr($aspect_ratio_align, 5)) {
  26586. case 'Min': {
  26587. // do nothing
  26588. break;
  26589. }
  26590. case 'Max': {
  26591. $svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
  26592. break;
  26593. }
  26594. default:
  26595. case 'Mid': {
  26596. $svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
  26597. break;
  26598. }
  26599. }
  26600. }
  26601. // store current page break mode
  26602. $page_break_mode = $this->AutoPageBreak;
  26603. $page_break_margin = $this->getBreakMargin();
  26604. $cell_padding = $this->cell_padding;
  26605. $this->SetCellPadding(0);
  26606. $this->SetAutoPageBreak(false);
  26607. // save the current graphic state
  26608. $this->_out('q'.$this->epsmarker);
  26609. // set initial clipping mask
  26610. $this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
  26611. // scale and translate
  26612. $e = $ox * $this->k * (1 - $svgscale_x);
  26613. $f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
  26614. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $svgscale_x, 0, 0, $svgscale_y, $e + $svgoffset_x, $f + $svgoffset_y));
  26615. // creates a new XML parser to be used by the other XML functions
  26616. $this->parser = xml_parser_create('UTF-8');
  26617. // the following function allows to use parser inside object
  26618. xml_set_object($this->parser, $this);
  26619. // disable case-folding for this XML parser
  26620. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  26621. // sets the element handler functions for the XML parser
  26622. xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
  26623. // sets the character data handler function for the XML parser
  26624. xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
  26625. // start parsing an XML document
  26626. if (!xml_parse($this->parser, $svgdata)) {
  26627. $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));
  26628. $this->Error($error_message);
  26629. }
  26630. // free this XML parser
  26631. xml_parser_free($this->parser);
  26632. // restore previous graphic state
  26633. $this->_out($this->epsmarker.'Q');
  26634. // restore graphic vars
  26635. $this->setGraphicVars($gvars);
  26636. $this->lasth = $gvars['lasth'];
  26637. if (!empty($border)) {
  26638. $bx = $this->x;
  26639. $by = $this->y;
  26640. $this->x = $ximg;
  26641. if ($this->rtl) {
  26642. $this->x += $w;
  26643. }
  26644. $this->y = $y;
  26645. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  26646. $this->x = $bx;
  26647. $this->y = $by;
  26648. }
  26649. if ($link) {
  26650. $this->Link($ximg, $y, $w, $h, $link, 0);
  26651. }
  26652. // set pointer to align the next text/objects
  26653. switch($align) {
  26654. case 'T':{
  26655. $this->y = $y;
  26656. $this->x = $this->img_rb_x;
  26657. break;
  26658. }
  26659. case 'M':{
  26660. $this->y = $y + round($h/2);
  26661. $this->x = $this->img_rb_x;
  26662. break;
  26663. }
  26664. case 'B':{
  26665. $this->y = $this->img_rb_y;
  26666. $this->x = $this->img_rb_x;
  26667. break;
  26668. }
  26669. case 'N':{
  26670. $this->SetY($this->img_rb_y);
  26671. break;
  26672. }
  26673. default:{
  26674. // restore pointer to starting position
  26675. $this->x = $gvars['x'];
  26676. $this->y = $gvars['y'];
  26677. $this->page = $gvars['page'];
  26678. $this->current_column = $gvars['current_column'];
  26679. $this->tMargin = $gvars['tMargin'];
  26680. $this->bMargin = $gvars['bMargin'];
  26681. $this->w = $gvars['w'];
  26682. $this->h = $gvars['h'];
  26683. $this->wPt = $gvars['wPt'];
  26684. $this->hPt = $gvars['hPt'];
  26685. $this->fwPt = $gvars['fwPt'];
  26686. $this->fhPt = $gvars['fhPt'];
  26687. break;
  26688. }
  26689. }
  26690. $this->endlinex = $this->img_rb_x;
  26691. // restore page break
  26692. $this->SetAutoPageBreak($page_break_mode, $page_break_margin);
  26693. $this->cell_padding = $cell_padding;
  26694. }
  26695. /**
  26696. * Get the tranformation matrix from SVG transform attribute
  26697. * @param $attribute (string) transformation
  26698. * @return array of transformations
  26699. * @author Nicola Asuni
  26700. * @since 5.0.000 (2010-05-02)
  26701. * @protected
  26702. */
  26703. protected function getSVGTransformMatrix($attribute) {
  26704. // identity matrix
  26705. $tm = array(1, 0, 0, 1, 0, 0);
  26706. $transform = array();
  26707. if (preg_match_all('/(matrix|translate|scale|rotate|skewX|skewY)[\s]*\(([^\)]+)\)/si', $attribute, $transform, PREG_SET_ORDER) > 0) {
  26708. foreach ($transform as $key => $data) {
  26709. if (!empty($data[2])) {
  26710. $a = 1;
  26711. $b = 0;
  26712. $c = 0;
  26713. $d = 1;
  26714. $e = 0;
  26715. $f = 0;
  26716. $regs = array();
  26717. switch ($data[1]) {
  26718. case 'matrix': {
  26719. if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
  26720. $a = $regs[1];
  26721. $b = $regs[2];
  26722. $c = $regs[3];
  26723. $d = $regs[4];
  26724. $e = $regs[5];
  26725. $f = $regs[6];
  26726. }
  26727. break;
  26728. }
  26729. case 'translate': {
  26730. if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
  26731. $e = $regs[1];
  26732. $f = $regs[2];
  26733. } elseif (preg_match('/([a-z0-9\-\.]+)/si', $data[2], $regs)) {
  26734. $e = $regs[1];
  26735. }
  26736. break;
  26737. }
  26738. case 'scale': {
  26739. if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
  26740. $a = $regs[1];
  26741. $d = $regs[2];
  26742. } elseif (preg_match('/([a-z0-9\-\.]+)/si', $data[2], $regs)) {
  26743. $a = $regs[1];
  26744. $d = $a;
  26745. }
  26746. break;
  26747. }
  26748. case 'rotate': {
  26749. if (preg_match('/([0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
  26750. $ang = deg2rad($regs[1]);
  26751. $x = $regs[2];
  26752. $y = $regs[3];
  26753. $a = cos($ang);
  26754. $b = sin($ang);
  26755. $c = -$b;
  26756. $d = $a;
  26757. $e = ($x * (1 - $a)) - ($y * $c);
  26758. $f = ($y * (1 - $d)) - ($x * $b);
  26759. } elseif (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) {
  26760. $ang = deg2rad($regs[1]);
  26761. $a = cos($ang);
  26762. $b = sin($ang);
  26763. $c = -$b;
  26764. $d = $a;
  26765. $e = 0;
  26766. $f = 0;
  26767. }
  26768. break;
  26769. }
  26770. case 'skewX': {
  26771. if (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) {
  26772. $c = tan(deg2rad($regs[1]));
  26773. }
  26774. break;
  26775. }
  26776. case 'skewY': {
  26777. if (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) {
  26778. $b = tan(deg2rad($regs[1]));
  26779. }
  26780. break;
  26781. }
  26782. }
  26783. $tm = $this->getTransformationMatrixProduct($tm, array($a, $b, $c, $d, $e, $f));
  26784. }
  26785. }
  26786. }
  26787. return $tm;
  26788. }
  26789. /**
  26790. * Get the product of two SVG tranformation matrices
  26791. * @param $ta (array) first SVG tranformation matrix
  26792. * @param $tb (array) second SVG tranformation matrix
  26793. * @return transformation array
  26794. * @author Nicola Asuni
  26795. * @since 5.0.000 (2010-05-02)
  26796. * @protected
  26797. */
  26798. protected function getTransformationMatrixProduct($ta, $tb) {
  26799. $tm = array();
  26800. $tm[0] = ($ta[0] * $tb[0]) + ($ta[2] * $tb[1]);
  26801. $tm[1] = ($ta[1] * $tb[0]) + ($ta[3] * $tb[1]);
  26802. $tm[2] = ($ta[0] * $tb[2]) + ($ta[2] * $tb[3]);
  26803. $tm[3] = ($ta[1] * $tb[2]) + ($ta[3] * $tb[3]);
  26804. $tm[4] = ($ta[0] * $tb[4]) + ($ta[2] * $tb[5]) + $ta[4];
  26805. $tm[5] = ($ta[1] * $tb[4]) + ($ta[3] * $tb[5]) + $ta[5];
  26806. return $tm;
  26807. }
  26808. /**
  26809. * Convert SVG transformation matrix to PDF.
  26810. * @param $tm (array) original SVG transformation matrix
  26811. * @return array transformation matrix
  26812. * @protected
  26813. * @since 5.0.000 (2010-05-02)
  26814. */
  26815. protected function convertSVGtMatrix($tm) {
  26816. $a = $tm[0];
  26817. $b = -$tm[1];
  26818. $c = -$tm[2];
  26819. $d = $tm[3];
  26820. $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
  26821. $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
  26822. $x = 0;
  26823. $y = $this->h * $this->k;
  26824. $e = ($x * (1 - $a)) - ($y * $c) + $e;
  26825. $f = ($y * (1 - $d)) - ($x * $b) + $f;
  26826. return array($a, $b, $c, $d, $e, $f);
  26827. }
  26828. /**
  26829. * Apply SVG graphic transformation matrix.
  26830. * @param $tm (array) original SVG transformation matrix
  26831. * @protected
  26832. * @since 5.0.000 (2010-05-02)
  26833. */
  26834. protected function SVGTransform($tm) {
  26835. $this->Transform($this->convertSVGtMatrix($tm));
  26836. }
  26837. /**
  26838. * Apply the requested SVG styles (*** TO BE COMPLETED ***)
  26839. * @param $svgstyle (array) array of SVG styles to apply
  26840. * @param $prevsvgstyle (array) array of previous SVG style
  26841. * @param $x (int) X origin of the bounding box
  26842. * @param $y (int) Y origin of the bounding box
  26843. * @param $w (int) width of the bounding box
  26844. * @param $h (int) height of the bounding box
  26845. * @param $clip_function (string) clip function
  26846. * @param $clip_params (array) array of parameters for clipping function
  26847. * @return object style
  26848. * @author Nicola Asuni
  26849. * @since 5.0.000 (2010-05-02)
  26850. * @protected
  26851. */
  26852. protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
  26853. $objstyle = '';
  26854. $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
  26855. if (!isset($svgstyle['opacity'])) {
  26856. return $objstyle;
  26857. }
  26858. // clip-path
  26859. $regs = array();
  26860. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
  26861. $clip_path = $this->svgclippaths[$regs[1]];
  26862. foreach ($clip_path as $cp) {
  26863. $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
  26864. }
  26865. }
  26866. // opacity
  26867. if ($svgstyle['opacity'] != 1) {
  26868. $this->SetAlpha($svgstyle['opacity']);
  26869. }
  26870. // color
  26871. $fill_color = $this->convertHTMLColorToDec($svgstyle['color']);
  26872. $this->SetFillColorArray($fill_color);
  26873. // text color
  26874. $text_color = $this->convertHTMLColorToDec($svgstyle['text-color']);
  26875. $this->SetTextColorArray($text_color);
  26876. // clip
  26877. if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
  26878. $top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
  26879. $right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
  26880. $bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
  26881. $left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
  26882. $cx = $x + $left;
  26883. $cy = $y + $top;
  26884. $cw = $w - $left - $right;
  26885. $ch = $h - $top - $bottom;
  26886. if ($svgstyle['clip-rule'] == 'evenodd') {
  26887. $clip_rule = 'CNZ';
  26888. } else {
  26889. $clip_rule = 'CEO';
  26890. }
  26891. $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
  26892. }
  26893. // fill
  26894. $regs = array();
  26895. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
  26896. // gradient
  26897. $gradient = $this->svggradients[$regs[1]];
  26898. if (isset($gradient['xref'])) {
  26899. // reference to another gradient definition
  26900. $newgradient = $this->svggradients[$gradient['xref']];
  26901. $newgradient['coords'] = $gradient['coords'];
  26902. $newgradient['mode'] = $gradient['mode'];
  26903. $newgradient['gradientUnits'] = $gradient['gradientUnits'];
  26904. if (isset($gradient['gradientTransform'])) {
  26905. $newgradient['gradientTransform'] = $gradient['gradientTransform'];
  26906. }
  26907. $gradient = $newgradient;
  26908. }
  26909. //save current Graphic State
  26910. $this->_out('q');
  26911. //set clipping area
  26912. if (!empty($clip_function) AND method_exists($this, $clip_function)) {
  26913. $bbox = call_user_func_array(array($this, $clip_function), $clip_params);
  26914. if (is_array($bbox) AND (count($bbox) == 4)) {
  26915. list($x, $y, $w, $h) = $bbox;
  26916. }
  26917. }
  26918. if ($gradient['mode'] == 'measure') {
  26919. if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
  26920. $gtm = $gradient['gradientTransform'];
  26921. // apply transformation matrix
  26922. $xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
  26923. $ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
  26924. $xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
  26925. $yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
  26926. if (isset($gradient['coords'][4])) {
  26927. $gradient['coords'][4] = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
  26928. }
  26929. $gradient['coords'][0] = $xa;
  26930. $gradient['coords'][1] = $ya;
  26931. $gradient['coords'][2] = $xb;
  26932. $gradient['coords'][3] = $yb;
  26933. }
  26934. // convert SVG coordinates to user units
  26935. $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
  26936. $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
  26937. $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
  26938. $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
  26939. if (isset($gradient['coords'][4])) {
  26940. $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
  26941. }
  26942. // shift units
  26943. if ($gradient['gradientUnits'] == 'objectBoundingBox') {
  26944. // convert to SVG coordinate system
  26945. $gradient['coords'][0] += $x;
  26946. $gradient['coords'][1] += $y;
  26947. $gradient['coords'][2] += $x;
  26948. $gradient['coords'][3] += $y;
  26949. }
  26950. if ($w <= $minlen) {
  26951. $w = $minlen;
  26952. }
  26953. if ($h <= $minlen) {
  26954. $h = $minlen;
  26955. }
  26956. // calculate percentages
  26957. $gradient['coords'][0] = ($gradient['coords'][0] - $x) / $w;
  26958. $gradient['coords'][1] = ($gradient['coords'][1] - $y) / $h;
  26959. $gradient['coords'][2] = ($gradient['coords'][2] - $x) / $w;
  26960. $gradient['coords'][3] = ($gradient['coords'][3] - $y) / $h;
  26961. if (isset($gradient['coords'][4])) {
  26962. $gradient['coords'][4] /= $w;
  26963. }
  26964. } elseif ($gradient['mode'] == 'percentage') {
  26965. foreach($gradient['coords'] as $key => $val) {
  26966. $gradient['coords'][$key] = (intval($val) / 100);
  26967. }
  26968. }
  26969. // fix values
  26970. foreach($gradient['coords'] as $key => $val) {
  26971. if ($val < 0) {
  26972. $gradient['coords'][$key] = 0;
  26973. } elseif ($val > 1) {
  26974. $gradient['coords'][$key] = 1;
  26975. }
  26976. }
  26977. if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
  26978. // single color (no shading)
  26979. $gradient['coords'][0] = 1;
  26980. $gradient['coords'][1] = 0;
  26981. $gradient['coords'][2] = 0.999;
  26982. $gradient['coords'][3] = 0;
  26983. }
  26984. // swap Y coordinates
  26985. $tmp = $gradient['coords'][1];
  26986. $gradient['coords'][1] = $gradient['coords'][3];
  26987. $gradient['coords'][3] = $tmp;
  26988. // set transformation map for gradient
  26989. if ($gradient['type'] == 3) {
  26990. // gradient is always circular
  26991. $cy = $this->h - $y - ($gradient['coords'][1] * ($w + $h));
  26992. $this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $w*$this->k, $x*$this->k, $cy*$this->k));
  26993. } else {
  26994. $this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k));
  26995. }
  26996. if (count($gradient['stops']) > 1) {
  26997. $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
  26998. }
  26999. } elseif ($svgstyle['fill'] != 'none') {
  27000. $fill_color = $this->convertHTMLColorToDec($svgstyle['fill']);
  27001. if ($svgstyle['fill-opacity'] != 1) {
  27002. $this->SetAlpha($svgstyle['fill-opacity']);
  27003. }
  27004. $this->SetFillColorArray($fill_color);
  27005. if ($svgstyle['fill-rule'] == 'evenodd') {
  27006. $objstyle .= 'F*';
  27007. } else {
  27008. $objstyle .= 'F';
  27009. }
  27010. }
  27011. // stroke
  27012. if ($svgstyle['stroke'] != 'none') {
  27013. $stroke_style = array(
  27014. 'color' => $this->convertHTMLColorToDec($svgstyle['stroke']),
  27015. 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
  27016. 'cap' => $svgstyle['stroke-linecap'],
  27017. 'join' => $svgstyle['stroke-linejoin']
  27018. );
  27019. if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
  27020. $stroke_style['dash'] = $svgstyle['stroke-dasharray'];
  27021. }
  27022. $this->SetLineStyle($stroke_style);
  27023. $objstyle .= 'D';
  27024. }
  27025. // font
  27026. $regs = array();
  27027. if (!empty($svgstyle['font'])) {
  27028. if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
  27029. $font_family = $this->getFontFamilyName($regs[1]);
  27030. } else {
  27031. $font_family = $svgstyle['font-family'];
  27032. }
  27033. if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  27034. $font_size = trim($regs[1]);
  27035. } else {
  27036. $font_size = $svgstyle['font-size'];
  27037. }
  27038. if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  27039. $font_style = trim($regs[1]);
  27040. } else {
  27041. $font_style = $svgstyle['font-style'];
  27042. }
  27043. if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  27044. $font_weight = trim($regs[1]);
  27045. } else {
  27046. $font_weight = $svgstyle['font-weight'];
  27047. }
  27048. if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  27049. $font_stretch = trim($regs[1]);
  27050. } else {
  27051. $font_stretch = $svgstyle['font-stretch'];
  27052. }
  27053. if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  27054. $font_spacing = trim($regs[1]);
  27055. } else {
  27056. $font_spacing = $svgstyle['letter-spacing'];
  27057. }
  27058. } else {
  27059. $font_family = $this->getFontFamilyName($svgstyle['font-family']);
  27060. $font_size = $svgstyle['font-size'];
  27061. $font_style = $svgstyle['font-style'];
  27062. $font_weight = $svgstyle['font-weight'];
  27063. $font_stretch = $svgstyle['font-stretch'];
  27064. $font_spacing = $svgstyle['letter-spacing'];
  27065. }
  27066. $font_size = $this->getHTMLUnitToUnits($font_size, $prevsvgstyle['font-size'], $this->svgunit, false) * $this->k;
  27067. $font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
  27068. $font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
  27069. switch ($font_style) {
  27070. case 'italic': {
  27071. $font_style = 'I';
  27072. break;
  27073. }
  27074. case 'oblique': {
  27075. $font_style = 'I';
  27076. break;
  27077. }
  27078. default:
  27079. case 'normal': {
  27080. $font_style = '';
  27081. break;
  27082. }
  27083. }
  27084. switch ($font_weight) {
  27085. case 'bold':
  27086. case 'bolder': {
  27087. $font_style .= 'B';
  27088. break;
  27089. }
  27090. }
  27091. switch ($svgstyle['text-decoration']) {
  27092. case 'underline': {
  27093. $font_style .= 'U';
  27094. break;
  27095. }
  27096. case 'overline': {
  27097. $font_style .= 'O';
  27098. break;
  27099. }
  27100. case 'line-through': {
  27101. $font_style .= 'D';
  27102. break;
  27103. }
  27104. default:
  27105. case 'none': {
  27106. break;
  27107. }
  27108. }
  27109. $this->SetFont($font_family, $font_style, $font_size);
  27110. $this->setFontStretching($font_stretch);
  27111. $this->setFontSpacing($font_spacing);
  27112. return $objstyle;
  27113. }
  27114. /**
  27115. * Draws an SVG path
  27116. * @param $d (string) attribute d of the path SVG element
  27117. * @param $style (string) Style of rendering. Possible values are:
  27118. * <ul>
  27119. * <li>D or empty string: Draw (default).</li>
  27120. * <li>F: Fill.</li>
  27121. * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  27122. * <li>DF or FD: Draw and fill.</li>
  27123. * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  27124. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  27125. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  27126. * </ul>
  27127. * @return array of container box measures (x, y, w, h)
  27128. * @author Nicola Asuni
  27129. * @since 5.0.000 (2010-05-02)
  27130. * @protected
  27131. */
  27132. protected function SVGPath($d, $style='') {
  27133. // set fill/stroke style
  27134. $op = $this->getPathPaintOperator($style, '');
  27135. if (empty($op)) {
  27136. return;
  27137. }
  27138. $paths = array();
  27139. $d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
  27140. preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
  27141. $x = 0;
  27142. $y = 0;
  27143. $x1 = 0;
  27144. $y1 = 0;
  27145. $x2 = 0;
  27146. $y2 = 0;
  27147. $xmin = 2147483647;
  27148. $xmax = 0;
  27149. $ymin = 2147483647;
  27150. $ymax = 0;
  27151. $relcoord = false;
  27152. $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
  27153. $firstcmd = true; // used to print first point
  27154. // draw curve pieces
  27155. foreach ($paths as $key => $val) {
  27156. // get curve type
  27157. $cmd = trim($val[1]);
  27158. if (strtolower($cmd) == $cmd) {
  27159. // use relative coordinated instead of absolute
  27160. $relcoord = true;
  27161. $xoffset = $x;
  27162. $yoffset = $y;
  27163. } else {
  27164. $relcoord = false;
  27165. $xoffset = 0;
  27166. $yoffset = 0;
  27167. }
  27168. $params = array();
  27169. if (isset($val[2])) {
  27170. // get curve parameters
  27171. $rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
  27172. $params = array();
  27173. foreach ($rawparams as $ck => $cp) {
  27174. $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
  27175. if (abs($params[$ck]) < $minlen) {
  27176. // aproximate little values to zero
  27177. $params[$ck] = 0;
  27178. }
  27179. }
  27180. }
  27181. // store current origin point
  27182. $x0 = $x;
  27183. $y0 = $y;
  27184. switch (strtoupper($cmd)) {
  27185. case 'M': { // moveto
  27186. foreach ($params as $ck => $cp) {
  27187. if (($ck % 2) == 0) {
  27188. $x = $cp + $xoffset;
  27189. } else {
  27190. $y = $cp + $yoffset;
  27191. if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  27192. if ($ck == 1) {
  27193. $this->_outPoint($x, $y);
  27194. $firstcmd = false;
  27195. } else {
  27196. $this->_outLine($x, $y);
  27197. }
  27198. }
  27199. $xmin = min($xmin, $x);
  27200. $ymin = min($ymin, $y);
  27201. $xmax = max($xmax, $x);
  27202. $ymax = max($ymax, $y);
  27203. if ($relcoord) {
  27204. $xoffset = $x;
  27205. $yoffset = $y;
  27206. }
  27207. }
  27208. }
  27209. break;
  27210. }
  27211. case 'L': { // lineto
  27212. foreach ($params as $ck => $cp) {
  27213. if (($ck % 2) == 0) {
  27214. $x = $cp + $xoffset;
  27215. } else {
  27216. $y = $cp + $yoffset;
  27217. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  27218. $this->_outLine($x, $y);
  27219. }
  27220. $xmin = min($xmin, $x);
  27221. $ymin = min($ymin, $y);
  27222. $xmax = max($xmax, $x);
  27223. $ymax = max($ymax, $y);
  27224. if ($relcoord) {
  27225. $xoffset = $x;
  27226. $yoffset = $y;
  27227. }
  27228. }
  27229. }
  27230. break;
  27231. }
  27232. case 'H': { // horizontal lineto
  27233. foreach ($params as $ck => $cp) {
  27234. $x = $cp + $xoffset;
  27235. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  27236. $this->_outLine($x, $y);
  27237. }
  27238. $xmin = min($xmin, $x);
  27239. $xmax = max($xmax, $x);
  27240. if ($relcoord) {
  27241. $xoffset = $x;
  27242. }
  27243. }
  27244. break;
  27245. }
  27246. case 'V': { // vertical lineto
  27247. foreach ($params as $ck => $cp) {
  27248. $y = $cp + $yoffset;
  27249. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  27250. $this->_outLine($x, $y);
  27251. }
  27252. $ymin = min($ymin, $y);
  27253. $ymax = max($ymax, $y);
  27254. if ($relcoord) {
  27255. $yoffset = $y;
  27256. }
  27257. }
  27258. break;
  27259. }
  27260. case 'C': { // curveto
  27261. foreach ($params as $ck => $cp) {
  27262. $params[$ck] = $cp;
  27263. if ((($ck + 1) % 6) == 0) {
  27264. $x1 = $params[($ck - 5)] + $xoffset;
  27265. $y1 = $params[($ck - 4)] + $yoffset;
  27266. $x2 = $params[($ck - 3)] + $xoffset;
  27267. $y2 = $params[($ck - 2)] + $yoffset;
  27268. $x = $params[($ck - 1)] + $xoffset;
  27269. $y = $params[($ck)] + $yoffset;
  27270. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  27271. $xmin = min($xmin, $x, $x1, $x2);
  27272. $ymin = min($ymin, $y, $y1, $y2);
  27273. $xmax = max($xmax, $x, $x1, $x2);
  27274. $ymax = max($ymax, $y, $y1, $y2);
  27275. if ($relcoord) {
  27276. $xoffset = $x;
  27277. $yoffset = $y;
  27278. }
  27279. }
  27280. }
  27281. break;
  27282. }
  27283. case 'S': { // shorthand/smooth curveto
  27284. foreach ($params as $ck => $cp) {
  27285. $params[$ck] = $cp;
  27286. if ((($ck + 1) % 4) == 0) {
  27287. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
  27288. $x1 = (2 * $x) - $x2;
  27289. $y1 = (2 * $y) - $y2;
  27290. } else {
  27291. $x1 = $x;
  27292. $y1 = $y;
  27293. }
  27294. $x2 = $params[($ck - 3)] + $xoffset;
  27295. $y2 = $params[($ck - 2)] + $yoffset;
  27296. $x = $params[($ck - 1)] + $xoffset;
  27297. $y = $params[($ck)] + $yoffset;
  27298. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  27299. $xmin = min($xmin, $x, $x1, $x2);
  27300. $ymin = min($ymin, $y, $y1, $y2);
  27301. $xmax = max($xmax, $x, $x1, $x2);
  27302. $ymax = max($ymax, $y, $y1, $y2);
  27303. if ($relcoord) {
  27304. $xoffset = $x;
  27305. $yoffset = $y;
  27306. }
  27307. }
  27308. }
  27309. break;
  27310. }
  27311. case 'Q': { // quadratic Bézier curveto
  27312. foreach ($params as $ck => $cp) {
  27313. $params[$ck] = $cp;
  27314. if ((($ck + 1) % 4) == 0) {
  27315. // convert quadratic points to cubic points
  27316. $x1 = $params[($ck - 3)] + $xoffset;
  27317. $y1 = $params[($ck - 2)] + $yoffset;
  27318. $xa = ($x + (2 * $x1)) / 3;
  27319. $ya = ($y + (2 * $y1)) / 3;
  27320. $x = $params[($ck - 1)] + $xoffset;
  27321. $y = $params[($ck)] + $yoffset;
  27322. $xb = ($x + (2 * $x1)) / 3;
  27323. $yb = ($y + (2 * $y1)) / 3;
  27324. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  27325. $xmin = min($xmin, $x, $xa, $xb);
  27326. $ymin = min($ymin, $y, $ya, $yb);
  27327. $xmax = max($xmax, $x, $xa, $xb);
  27328. $ymax = max($ymax, $y, $ya, $yb);
  27329. if ($relcoord) {
  27330. $xoffset = $x;
  27331. $yoffset = $y;
  27332. }
  27333. }
  27334. }
  27335. break;
  27336. }
  27337. case 'T': { // shorthand/smooth quadratic Bézier curveto
  27338. foreach ($params as $ck => $cp) {
  27339. $params[$ck] = $cp;
  27340. if (($ck % 2) != 0) {
  27341. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
  27342. $x1 = (2 * $x) - $x1;
  27343. $y1 = (2 * $y) - $y1;
  27344. } else {
  27345. $x1 = $x;
  27346. $y1 = $y;
  27347. }
  27348. // convert quadratic points to cubic points
  27349. $xa = ($x + (2 * $x1)) / 3;
  27350. $ya = ($y + (2 * $y1)) / 3;
  27351. $x = $params[($ck - 1)] + $xoffset;
  27352. $y = $params[($ck)] + $yoffset;
  27353. $xb = ($x + (2 * $x1)) / 3;
  27354. $yb = ($y + (2 * $y1)) / 3;
  27355. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  27356. $xmin = min($xmin, $x, $xa, $xb);
  27357. $ymin = min($ymin, $y, $ya, $yb);
  27358. $xmax = max($xmax, $x, $xa, $xb);
  27359. $ymax = max($ymax, $y, $ya, $yb);
  27360. if ($relcoord) {
  27361. $xoffset = $x;
  27362. $yoffset = $y;
  27363. }
  27364. }
  27365. }
  27366. break;
  27367. }
  27368. case 'A': { // elliptical arc
  27369. foreach ($params as $ck => $cp) {
  27370. $params[$ck] = $cp;
  27371. if ((($ck + 1) % 7) == 0) {
  27372. $x0 = $x;
  27373. $y0 = $y;
  27374. $rx = abs($params[($ck - 6)]);
  27375. $ry = abs($params[($ck - 5)]);
  27376. $ang = -$rawparams[($ck - 4)];
  27377. $angle = deg2rad($ang);
  27378. $fa = $rawparams[($ck - 3)]; // large-arc-flag
  27379. $fs = $rawparams[($ck - 2)]; // sweep-flag
  27380. $x = $params[($ck - 1)] + $xoffset;
  27381. $y = $params[$ck] + $yoffset;
  27382. if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
  27383. // endpoints are almost identical
  27384. $xmin = min($xmin, $x);
  27385. $ymin = min($ymin, $y);
  27386. $xmax = max($xmax, $x);
  27387. $ymax = max($ymax, $y);
  27388. } else {
  27389. $cos_ang = cos($angle);
  27390. $sin_ang = sin($angle);
  27391. $a = (($x0 - $x) / 2);
  27392. $b = (($y0 - $y) / 2);
  27393. $xa = ($a * $cos_ang) - ($b * $sin_ang);
  27394. $ya = ($a * $sin_ang) + ($b * $cos_ang);
  27395. $rx2 = $rx * $rx;
  27396. $ry2 = $ry * $ry;
  27397. $xa2 = $xa * $xa;
  27398. $ya2 = $ya * $ya;
  27399. $delta = ($xa2 / $rx2) + ($ya2 / $ry2);
  27400. if ($delta > 1) {
  27401. $rx *= sqrt($delta);
  27402. $ry *= sqrt($delta);
  27403. $rx2 = $rx * $rx;
  27404. $ry2 = $ry * $ry;
  27405. }
  27406. $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
  27407. if ($numerator < 0) {
  27408. $root = 0;
  27409. } else {
  27410. $root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
  27411. }
  27412. if ($fa == $fs){
  27413. $root *= -1;
  27414. }
  27415. $cax = $root * (($rx * $ya) / $ry);
  27416. $cay = -$root * (($ry * $xa) / $rx);
  27417. // coordinates of ellipse center
  27418. $cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
  27419. $cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
  27420. // get angles
  27421. $angs = $this->getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
  27422. $dang = $this->getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
  27423. if (($fs == 0) AND ($dang > 0)) {
  27424. $dang -= (2 * M_PI);
  27425. } elseif (($fs == 1) AND ($dang < 0)) {
  27426. $dang += (2 * M_PI);
  27427. }
  27428. $angf = $angs - $dang;
  27429. if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
  27430. // reverse angles
  27431. $tmp = $angs;
  27432. $angs = $angf;
  27433. $angf = $tmp;
  27434. }
  27435. $angs = round(rad2deg($angs), 6);
  27436. $angf = round(rad2deg($angf), 6);
  27437. // covent angles to positive values
  27438. if (($angs < 0) AND ($angf < 0)) {
  27439. $angs += 360;
  27440. $angf += 360;
  27441. }
  27442. $pie = false;
  27443. if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
  27444. $pie = true;
  27445. }
  27446. list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
  27447. $xmin = min($xmin, $x, $axmin);
  27448. $ymin = min($ymin, $y, $aymin);
  27449. $xmax = max($xmax, $x, $axmax);
  27450. $ymax = max($ymax, $y, $aymax);
  27451. }
  27452. if ($relcoord) {
  27453. $xoffset = $x;
  27454. $yoffset = $y;
  27455. }
  27456. }
  27457. }
  27458. break;
  27459. }
  27460. case 'Z': {
  27461. $this->_out('h');
  27462. break;
  27463. }
  27464. }
  27465. $firstcmd = false;
  27466. } // end foreach
  27467. if (!empty($op)) {
  27468. $this->_out($op);
  27469. }
  27470. return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
  27471. }
  27472. /**
  27473. * Returns the angle in radiants between two vectors
  27474. * @param $x1 (int) X coordinate of first vector point
  27475. * @param $y1 (int) Y coordinate of first vector point
  27476. * @param $x2 (int) X coordinate of second vector point
  27477. * @param $y2 (int) Y coordinate of second vector point
  27478. * @author Nicola Asuni
  27479. * @since 5.0.000 (2010-05-04)
  27480. * @protected
  27481. */
  27482. protected function getVectorsAngle($x1, $y1, $x2, $y2) {
  27483. $dprod = ($x1 * $x2) + ($y1 * $y2);
  27484. $dist1 = sqrt(($x1 * $x1) + ($y1 * $y1));
  27485. $dist2 = sqrt(($x2 * $x2) + ($y2 * $y2));
  27486. $angle = acos($dprod / ($dist1 * $dist2));
  27487. if (is_nan($angle)) {
  27488. $angle = M_PI;
  27489. }
  27490. if ((($x1 * $y2) - ($x2 * $y1)) < 0) {
  27491. $angle *= -1;
  27492. }
  27493. return $angle;
  27494. }
  27495. /**
  27496. * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
  27497. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  27498. * @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.
  27499. * @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.
  27500. * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
  27501. * @author Nicola Asuni
  27502. * @since 5.0.000 (2010-05-02)
  27503. * @protected
  27504. */
  27505. protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
  27506. // check if we are in clip mode
  27507. if ($this->svgclipmode) {
  27508. $this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
  27509. return;
  27510. }
  27511. if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
  27512. if (!isset($attribs['id'])) {
  27513. $attribs['id'] = 'DF_'.(count($this->svgdefs) + 1);
  27514. }
  27515. $this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  27516. return;
  27517. }
  27518. $clipping = false;
  27519. if ($parser == 'clip-path') {
  27520. // set clipping mode
  27521. $clipping = true;
  27522. }
  27523. // get styling properties
  27524. $prev_svgstyle = $this->svgstyles[(count($this->svgstyles) - 1)]; // previous style
  27525. $svgstyle = $this->svgstyles[0]; // set default style
  27526. if (isset($attribs['style']) AND !$this->empty_string($attribs['style'])) {
  27527. // fix style for regular expression
  27528. $attribs['style'] = ';'.$attribs['style'];
  27529. }
  27530. foreach ($prev_svgstyle as $key => $val) {
  27531. if (in_array($key, $this->svginheritprop)) {
  27532. // inherit previous value
  27533. $svgstyle[$key] = $val;
  27534. }
  27535. if (isset($attribs[$key]) AND !$this->empty_string($attribs[$key])) {
  27536. // specific attribute settings
  27537. if ($attribs[$key] == 'inherit') {
  27538. $svgstyle[$key] = $val;
  27539. } else {
  27540. $svgstyle[$key] = $attribs[$key];
  27541. }
  27542. } elseif (isset($attribs['style']) AND !$this->empty_string($attribs['style'])) {
  27543. // CSS style syntax
  27544. $attrval = array();
  27545. if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
  27546. if ($attrval[1] == 'inherit') {
  27547. $svgstyle[$key] = $val;
  27548. } else {
  27549. $svgstyle[$key] = $attrval[1];
  27550. }
  27551. }
  27552. }
  27553. }
  27554. // transformation matrix
  27555. if (!empty($ctm)) {
  27556. $tm = $ctm;
  27557. } else {
  27558. $tm = $this->svgstyles[(count($this->svgstyles) - 1)]['transfmatrix'];
  27559. }
  27560. if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
  27561. $tm = $this->getTransformationMatrixProduct($tm, $this->getSVGTransformMatrix($attribs['transform']));
  27562. }
  27563. $svgstyle['transfmatrix'] = $tm;
  27564. $invisible = false;
  27565. if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
  27566. // the current graphics element is invisible (nothing is painted)
  27567. $invisible = true;
  27568. }
  27569. // process tag
  27570. switch($name) {
  27571. case 'defs': {
  27572. $this->svgdefsmode = true;
  27573. break;
  27574. }
  27575. // clipPath
  27576. case 'clipPath': {
  27577. if ($invisible) {
  27578. break;
  27579. }
  27580. $this->svgclipmode = true;
  27581. if (!isset($attribs['id'])) {
  27582. $attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
  27583. }
  27584. $this->svgclipid = $attribs['id'];
  27585. $this->svgclippaths[$this->svgclipid] = array();
  27586. $this->svgcliptm[$this->svgclipid] = $tm;
  27587. break;
  27588. }
  27589. case 'svg': {
  27590. // start of SVG object
  27591. break;
  27592. }
  27593. case 'g': {
  27594. // group together related graphics elements
  27595. array_push($this->svgstyles, $svgstyle);
  27596. $this->StartTransform();
  27597. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  27598. break;
  27599. }
  27600. case 'linearGradient': {
  27601. if ($this->pdfa_mode) {
  27602. break;
  27603. }
  27604. if (!isset($attribs['id'])) {
  27605. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  27606. }
  27607. $this->svggradientid = $attribs['id'];
  27608. $this->svggradients[$this->svggradientid] = array();
  27609. $this->svggradients[$this->svggradientid]['type'] = 2;
  27610. $this->svggradients[$this->svggradientid]['stops'] = array();
  27611. if (isset($attribs['gradientUnits'])) {
  27612. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  27613. } else {
  27614. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  27615. }
  27616. //$attribs['spreadMethod']
  27617. $x1 = (isset($attribs['x1'])?$attribs['x1']:'0%');
  27618. $y1 = (isset($attribs['y1'])?$attribs['y1']:'0%');
  27619. $x2 = (isset($attribs['x2'])?$attribs['x2']:'100%');
  27620. $y2 = (isset($attribs['y2'])?$attribs['y2']:'0%');
  27621. if (substr($x1, -1) != '%') {
  27622. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  27623. } else {
  27624. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  27625. }
  27626. if (isset($attribs['gradientTransform'])) {
  27627. $this->svggradients[$this->svggradientid]['gradientTransform'] = $this->getSVGTransformMatrix($attribs['gradientTransform']);
  27628. }
  27629. $this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
  27630. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  27631. // gradient is defined on another place
  27632. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  27633. }
  27634. break;
  27635. }
  27636. case 'radialGradient': {
  27637. if ($this->pdfa_mode) {
  27638. break;
  27639. }
  27640. if (!isset($attribs['id'])) {
  27641. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  27642. }
  27643. $this->svggradientid = $attribs['id'];
  27644. $this->svggradients[$this->svggradientid] = array();
  27645. $this->svggradients[$this->svggradientid]['type'] = 3;
  27646. $this->svggradients[$this->svggradientid]['stops'] = array();
  27647. if (isset($attribs['gradientUnits'])) {
  27648. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  27649. } else {
  27650. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  27651. }
  27652. //$attribs['spreadMethod']
  27653. $cx = (isset($attribs['cx'])?$attribs['cx']:0.5);
  27654. $cy = (isset($attribs['cy'])?$attribs['cy']:0.5);
  27655. $fx = (isset($attribs['fx'])?$attribs['fx']:$cx);
  27656. $fy = (isset($attribs['fy'])?$attribs['fy']:$cy);
  27657. $r = (isset($attribs['r'])?$attribs['r']:0.5);
  27658. if (isset($attribs['cx']) AND (substr($attribs['cx'], -1) != '%')) {
  27659. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  27660. } else {
  27661. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  27662. }
  27663. if (isset($attribs['gradientTransform'])) {
  27664. $this->svggradients[$this->svggradientid]['gradientTransform'] = $this->getSVGTransformMatrix($attribs['gradientTransform']);
  27665. }
  27666. $this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
  27667. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  27668. // gradient is defined on another place
  27669. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  27670. }
  27671. break;
  27672. }
  27673. case 'stop': {
  27674. // gradient stops
  27675. if (substr($attribs['offset'], -1) == '%') {
  27676. $offset = floatval(substr($attribs['offset'], -1)) / 100;
  27677. } else {
  27678. $offset = floatval($attribs['offset']);
  27679. if ($offset > 1) {
  27680. $offset /= 100;
  27681. }
  27682. }
  27683. $stop_color = isset($svgstyle['stop-color'])?$this->convertHTMLColorToDec($svgstyle['stop-color']):'black';
  27684. $opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
  27685. $this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
  27686. break;
  27687. }
  27688. // paths
  27689. case 'path': {
  27690. if ($invisible) {
  27691. break;
  27692. }
  27693. if (isset($attribs['d'])) {
  27694. $d = trim($attribs['d']);
  27695. if (!empty($d)) {
  27696. if ($clipping) {
  27697. $this->SVGTransform($tm);
  27698. $this->SVGPath($d, 'CNZ');
  27699. } else {
  27700. $this->StartTransform();
  27701. $this->SVGTransform($tm);
  27702. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, 0, 0, 1, 1, 'SVGPath', array($d, 'CNZ'));
  27703. if (!empty($obstyle)) {
  27704. $this->SVGPath($d, $obstyle);
  27705. }
  27706. $this->StopTransform();
  27707. }
  27708. }
  27709. }
  27710. break;
  27711. }
  27712. // shapes
  27713. case 'rect': {
  27714. if ($invisible) {
  27715. break;
  27716. }
  27717. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  27718. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  27719. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  27720. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  27721. $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
  27722. $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
  27723. if ($clipping) {
  27724. $this->SVGTransform($tm);
  27725. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
  27726. } else {
  27727. $this->StartTransform();
  27728. $this->SVGTransform($tm);
  27729. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
  27730. if (!empty($obstyle)) {
  27731. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
  27732. }
  27733. $this->StopTransform();
  27734. }
  27735. break;
  27736. }
  27737. case 'circle': {
  27738. if ($invisible) {
  27739. break;
  27740. }
  27741. $cx = (isset($attribs['cx'])?$this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false):0);
  27742. $cy = (isset($attribs['cy'])?$this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false):0);
  27743. $r = (isset($attribs['r'])?$this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false):0);
  27744. $x = $cx - $r;
  27745. $y = $cy - $r;
  27746. $w = 2 * $r;
  27747. $h = $w;
  27748. if ($clipping) {
  27749. $this->SVGTransform($tm);
  27750. $this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
  27751. } else {
  27752. $this->StartTransform();
  27753. $this->SVGTransform($tm);
  27754. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
  27755. if (!empty($obstyle)) {
  27756. $this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
  27757. }
  27758. $this->StopTransform();
  27759. }
  27760. break;
  27761. }
  27762. case 'ellipse': {
  27763. if ($invisible) {
  27764. break;
  27765. }
  27766. $cx = (isset($attribs['cx'])?$this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false):0);
  27767. $cy = (isset($attribs['cy'])?$this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false):0);
  27768. $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
  27769. $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):0);
  27770. $x = $cx - $rx;
  27771. $y = $cy - $ry;
  27772. $w = 2 * $rx;
  27773. $h = 2 * $ry;
  27774. if ($clipping) {
  27775. $this->SVGTransform($tm);
  27776. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
  27777. } else {
  27778. $this->StartTransform();
  27779. $this->SVGTransform($tm);
  27780. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
  27781. if (!empty($obstyle)) {
  27782. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
  27783. }
  27784. $this->StopTransform();
  27785. }
  27786. break;
  27787. }
  27788. case 'line': {
  27789. if ($invisible) {
  27790. break;
  27791. }
  27792. $x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
  27793. $y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
  27794. $x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
  27795. $y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
  27796. $x = $x1;
  27797. $y = $y1;
  27798. $w = abs($x2 - $x1);
  27799. $h = abs($y2 - $y1);
  27800. if (!$clipping) {
  27801. $this->StartTransform();
  27802. $this->SVGTransform($tm);
  27803. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
  27804. $this->Line($x1, $y1, $x2, $y2);
  27805. $this->StopTransform();
  27806. }
  27807. break;
  27808. }
  27809. case 'polyline':
  27810. case 'polygon': {
  27811. if ($invisible) {
  27812. break;
  27813. }
  27814. $points = (isset($attribs['points'])?$attribs['points']:'0 0');
  27815. $points = trim($points);
  27816. // note that point may use a complex syntax not covered here
  27817. $points = preg_split('/[\,\s]+/si', $points);
  27818. if (count($points) < 4) {
  27819. break;
  27820. }
  27821. $p = array();
  27822. $xmin = 2147483647;
  27823. $xmax = 0;
  27824. $ymin = 2147483647;
  27825. $ymax = 0;
  27826. foreach ($points as $key => $val) {
  27827. $p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  27828. if (($key % 2) == 0) {
  27829. // X coordinate
  27830. $xmin = min($xmin, $p[$key]);
  27831. $xmax = max($xmax, $p[$key]);
  27832. } else {
  27833. // Y coordinate
  27834. $ymin = min($ymin, $p[$key]);
  27835. $ymax = max($ymax, $p[$key]);
  27836. }
  27837. }
  27838. $x = $xmin;
  27839. $y = $ymin;
  27840. $w = ($xmax - $xmin);
  27841. $h = ($ymax - $ymin);
  27842. if ($name == 'polyline') {
  27843. $this->StartTransform();
  27844. $this->SVGTransform($tm);
  27845. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
  27846. $this->PolyLine($p, 'D', array(), array());
  27847. $this->StopTransform();
  27848. } else { // polygon
  27849. if ($clipping) {
  27850. $this->SVGTransform($tm);
  27851. $this->Polygon($p, 'CNZ', array(), array(), true);
  27852. } else {
  27853. $this->StartTransform();
  27854. $this->SVGTransform($tm);
  27855. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
  27856. if (!empty($obstyle)) {
  27857. $this->Polygon($p, $obstyle, array(), array(), true);
  27858. }
  27859. $this->StopTransform();
  27860. }
  27861. }
  27862. break;
  27863. }
  27864. // image
  27865. case 'image': {
  27866. if ($invisible) {
  27867. break;
  27868. }
  27869. if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
  27870. break;
  27871. }
  27872. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  27873. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  27874. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  27875. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  27876. $img = $attribs['xlink:href'];
  27877. if (!$clipping) {
  27878. $this->StartTransform();
  27879. $this->SVGTransform($tm);
  27880. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
  27881. if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
  27882. // embedded image encoded as base64
  27883. $img = '@'.base64_decode(substr($img, strlen($m[0])));
  27884. } else {
  27885. // fix image path
  27886. if (!$this->empty_string($this->svgdir) AND (($img{0} == '.') OR (basename($img) == $img))) {
  27887. // replace relative path with full server path
  27888. $img = $this->svgdir.'/'.$img;
  27889. }
  27890. if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  27891. $findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
  27892. if (($findroot === false) OR ($findroot > 1)) {
  27893. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  27894. $img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
  27895. } else {
  27896. $img = $_SERVER['DOCUMENT_ROOT'].$img;
  27897. }
  27898. }
  27899. }
  27900. $img = urldecode($img);
  27901. $testscrtype = @parse_url($img);
  27902. if (!isset($testscrtype['query']) OR empty($testscrtype['query'])) {
  27903. // convert URL to server path
  27904. $img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
  27905. }
  27906. }
  27907. $this->Image($img, $x, $y, $w, $h);
  27908. $this->StopTransform();
  27909. }
  27910. break;
  27911. }
  27912. // text
  27913. case 'text':
  27914. case 'tspan': {
  27915. $this->svgtextmode['invisible'] = $invisible;
  27916. if ($invisible) {
  27917. break;
  27918. }
  27919. array_push($this->svgstyles, $svgstyle);
  27920. // only basic support - advanced features must be implemented
  27921. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):$this->x);
  27922. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):$this->y);
  27923. $svgstyle['text-color'] = $svgstyle['fill'];
  27924. $this->svgtext = '';
  27925. if (isset($svgstyle['text-anchor'])) {
  27926. $this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
  27927. } else {
  27928. $this->svgtextmode['text-anchor'] = 'start';
  27929. }
  27930. if (isset($svgstyle['direction'])) {
  27931. if ($svgstyle['direction'] == 'rtl') {
  27932. $this->svgtextmode['rtl'] = true;
  27933. } else {
  27934. $this->svgtextmode['rtl'] = false;
  27935. }
  27936. } else {
  27937. $this->svgtextmode['rtl'] = false;
  27938. }
  27939. if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
  27940. $this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
  27941. } else {
  27942. $this->svgtextmode['stroke'] = false;
  27943. }
  27944. $this->StartTransform();
  27945. $this->SVGTransform($tm);
  27946. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
  27947. $this->x = $x;
  27948. $this->y = $y;
  27949. break;
  27950. }
  27951. // use
  27952. case 'use': {
  27953. if (isset($attribs['xlink:href'])) {
  27954. $use = $this->svgdefs[substr($attribs['xlink:href'], 1)];
  27955. if (isset($attribs['xlink:href'])) {
  27956. unset($attribs['xlink:href']);
  27957. }
  27958. if (isset($attribs['id'])) {
  27959. unset($attribs['id']);
  27960. }
  27961. $attribs = array_merge($use['attribs'], $attribs);
  27962. $this->startSVGElementHandler($parser, $use['name'], $use['attribs']);
  27963. }
  27964. break;
  27965. }
  27966. default: {
  27967. break;
  27968. }
  27969. } // end of switch
  27970. }
  27971. /**
  27972. * Sets the closing SVG element handler function for the XML parser.
  27973. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  27974. * @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.
  27975. * @author Nicola Asuni
  27976. * @since 5.0.000 (2010-05-02)
  27977. * @protected
  27978. */
  27979. protected function endSVGElementHandler($parser, $name) {
  27980. switch($name) {
  27981. case 'defs': {
  27982. $this->svgdefsmode = false;
  27983. break;
  27984. }
  27985. // clipPath
  27986. case 'clipPath': {
  27987. $this->svgclipmode = false;
  27988. break;
  27989. }
  27990. case 'g': {
  27991. // ungroup: remove last style from array
  27992. array_pop($this->svgstyles);
  27993. $this->StopTransform();
  27994. break;
  27995. }
  27996. case 'text':
  27997. case 'tspan': {
  27998. if ($this->svgtextmode['invisible']) {
  27999. // This implementation must be fixed to following the rule:
  28000. // 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.
  28001. break;
  28002. }
  28003. // print text
  28004. $text = $this->stringTrim($this->svgtext);
  28005. if ($this->svgtextmode['text-anchor'] != 'start') {
  28006. $textlen = $this->GetStringWidth($text);
  28007. // check if string is RTL text
  28008. if ($this->svgtextmode['text-anchor'] == 'end') {
  28009. if ($this->svgtextmode['rtl']) {
  28010. $this->x += $textlen;
  28011. } else {
  28012. $this->x -= $textlen;
  28013. }
  28014. } elseif ($this->svgtextmode['text-anchor'] == 'middle') {
  28015. if ($this->svgtextmode['rtl']) {
  28016. $this->x += ($textlen / 2);
  28017. } else {
  28018. $this->x -= ($textlen / 2);
  28019. }
  28020. }
  28021. }
  28022. $textrendermode = $this->textrendermode;
  28023. $textstrokewidth = $this->textstrokewidth;
  28024. $this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
  28025. $this->Cell(0, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
  28026. // restore previous rendering mode
  28027. $this->textrendermode = $textrendermode;
  28028. $this->textstrokewidth = $textstrokewidth;
  28029. $this->svgtext = '';
  28030. $this->StopTransform();
  28031. array_pop($this->svgstyles);
  28032. break;
  28033. }
  28034. default: {
  28035. break;
  28036. }
  28037. }
  28038. }
  28039. /**
  28040. * Sets the character data handler function for the XML parser.
  28041. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  28042. * @param $data (string) The second parameter, data, contains the character data as a string.
  28043. * @author Nicola Asuni
  28044. * @since 5.0.000 (2010-05-02)
  28045. * @protected
  28046. */
  28047. protected function segSVGContentHandler($parser, $data) {
  28048. $this->svgtext .= $data;
  28049. }
  28050. // --- END SVG METHODS -----------------------------------------------------
  28051. } // END OF TCPDF CLASS
  28052. //============================================================+
  28053. // END OF FILE
  28054. //============================================================+