/tools/tcpdf/tcpdf.php

https://bitbucket.org/enurkov/prestashop · PHP · 27422 lines · 18763 code · 757 blank · 7902 comment · 4063 complexity · 7aa19c022eb2a4c7b2b08d21381d1762 MD5 · raw file

  1. <?php
  2. //============================================================+
  3. // File name : tcpdf.php
  4. // Version : 5.9.179
  5. // Begin : 2002-08-03
  6. // Last Update : 2012-08-04
  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);
  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. // Aleksey Kuznetsov for some suggestions and text shadows.
  101. // Anyone else that has reported a bug or sent a suggestion.
  102. //============================================================+
  103. /**
  104. * @file
  105. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  106. * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
  107. * <h3>TCPDF main features are:</h3>
  108. * <ul>
  109. * <li>no external libraries are required for the basic functions;</li>
  110. * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
  111. * <li>UTF-8 Unicode and Right-To-Left languages;</li>
  112. * <li>TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
  113. * <li>font subsetting;</li>
  114. * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
  115. * <li>images, graphic (geometric figures) and transformation methods;
  116. * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)</li>
  117. * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;</li>
  118. * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
  119. * <li>automatic page header and footer management;</li>
  120. * <li>document encryption up to 256 bit and digital signature certifications;</li>
  121. * <li>transactions to UNDO commands;</li>
  122. * <li>PDF annotations, including links, text and file attachments;</li>
  123. * <li>text rendering modes (fill, stroke and clipping);</li>
  124. * <li>multiple columns mode;</li>
  125. * <li>no-write page regions;</li>
  126. * <li>bookmarks, named destinations and table of content;</li>
  127. * <li>text hyphenation;</li>
  128. * <li>text stretching and spacing (tracking);</li>
  129. * <li>automatic page break, line break and text alignments including justification;</li>
  130. * <li>automatic page numbering and page groups;</li>
  131. * <li>move and delete pages;</li>
  132. * <li>page compression (requires php-zlib extension);</li>
  133. * <li>XOBject Templates;</li>
  134. * <li>Layers and object visibility;</li>
  135. * <li>PDF/A-1b support.</li>
  136. * </ul>
  137. * Tools to encode your unicode fonts are on fonts/utils directory.</p>
  138. * @package com.tecnick.tcpdf
  139. * @author Nicola Asuni
  140. * @version 5.9.179
  141. */
  142. // Main configuration file. Define the K_TCPDF_EXTERNAL_CONFIG constant to skip this file.
  143. require_once(dirname(__FILE__).'/config/tcpdf_config.php');
  144. /**
  145. * @class TCPDF
  146. * PHP class for generating PDF documents without requiring external extensions.
  147. * 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>
  148. * @package com.tecnick.tcpdf
  149. * @brief PHP class for generating PDF documents without requiring external extensions.
  150. * @version 5.9.179
  151. * @author Nicola Asuni - info@tecnick.com
  152. */
  153. class TCPDF {
  154. // private properties
  155. /**
  156. * Current TCPDF version.
  157. * @private
  158. */
  159. private $tcpdf_version = '5.9.179';
  160. // Protected properties
  161. /**
  162. * Current page number.
  163. * @protected
  164. */
  165. protected $page;
  166. /**
  167. * Current object number.
  168. * @protected
  169. */
  170. protected $n;
  171. /**
  172. * Array of object offsets.
  173. * @protected
  174. */
  175. protected $offsets = array();
  176. /**
  177. * Array of object IDs for each page.
  178. * @protected
  179. */
  180. protected $pageobjects = array();
  181. /**
  182. * Buffer holding in-memory PDF.
  183. * @protected
  184. */
  185. protected $buffer;
  186. /**
  187. * Array containing pages.
  188. * @protected
  189. */
  190. protected $pages = array();
  191. /**
  192. * Current document state.
  193. * @protected
  194. */
  195. protected $state;
  196. /**
  197. * Compression flag.
  198. * @protected
  199. */
  200. protected $compress;
  201. /**
  202. * Current page orientation (P = Portrait, L = Landscape).
  203. * @protected
  204. */
  205. protected $CurOrientation;
  206. /**
  207. * Page dimensions.
  208. * @protected
  209. */
  210. protected $pagedim = array();
  211. /**
  212. * Scale factor (number of points in user unit).
  213. * @protected
  214. */
  215. protected $k;
  216. /**
  217. * Width of page format in points.
  218. * @protected
  219. */
  220. protected $fwPt;
  221. /**
  222. * Height of page format in points.
  223. * @protected
  224. */
  225. protected $fhPt;
  226. /**
  227. * Current width of page in points.
  228. * @protected
  229. */
  230. protected $wPt;
  231. /**
  232. * Current height of page in points.
  233. * @protected
  234. */
  235. protected $hPt;
  236. /**
  237. * Current width of page in user unit.
  238. * @protected
  239. */
  240. protected $w;
  241. /**
  242. * Current height of page in user unit.
  243. * @protected
  244. */
  245. protected $h;
  246. /**
  247. * Left margin.
  248. * @protected
  249. */
  250. protected $lMargin;
  251. /**
  252. * Top margin.
  253. * @protected
  254. */
  255. protected $tMargin;
  256. /**
  257. * Right margin.
  258. * @protected
  259. */
  260. protected $rMargin;
  261. /**
  262. * Page break margin.
  263. * @protected
  264. */
  265. protected $bMargin;
  266. /**
  267. * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  268. * @since 5.9.000 (2010-10-03)
  269. * @protected
  270. */
  271. protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  272. /**
  273. * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  274. * @since 5.9.000 (2010-10-04)
  275. * @protected
  276. */
  277. protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  278. /**
  279. * Current horizontal position in user unit for cell positioning.
  280. * @protected
  281. */
  282. protected $x;
  283. /**
  284. * Current vertical position in user unit for cell positioning.
  285. * @protected
  286. */
  287. protected $y;
  288. /**
  289. * Height of last cell printed.
  290. * @protected
  291. */
  292. protected $lasth;
  293. /**
  294. * Line width in user unit.
  295. * @protected
  296. */
  297. protected $LineWidth;
  298. /**
  299. * Array of standard font names.
  300. * @protected
  301. */
  302. protected $CoreFonts;
  303. /**
  304. * Array of used fonts.
  305. * @protected
  306. */
  307. protected $fonts = array();
  308. /**
  309. * Array of font files.
  310. * @protected
  311. */
  312. protected $FontFiles = array();
  313. /**
  314. * Array of encoding differences.
  315. * @protected
  316. */
  317. protected $diffs = array();
  318. /**
  319. * Array of used images.
  320. * @protected
  321. */
  322. protected $images = array();
  323. /**
  324. * Array of Annotations in pages.
  325. * @protected
  326. */
  327. protected $PageAnnots = array();
  328. /**
  329. * Array of internal links.
  330. * @protected
  331. */
  332. protected $links = array();
  333. /**
  334. * Current font family.
  335. * @protected
  336. */
  337. protected $FontFamily;
  338. /**
  339. * Current font style.
  340. * @protected
  341. */
  342. protected $FontStyle;
  343. /**
  344. * Current font ascent (distance between font top and baseline).
  345. * @protected
  346. * @since 2.8.000 (2007-03-29)
  347. */
  348. protected $FontAscent;
  349. /**
  350. * Current font descent (distance between font bottom and baseline).
  351. * @protected
  352. * @since 2.8.000 (2007-03-29)
  353. */
  354. protected $FontDescent;
  355. /**
  356. * Underlining flag.
  357. * @protected
  358. */
  359. protected $underline;
  360. /**
  361. * Overlining flag.
  362. * @protected
  363. */
  364. protected $overline;
  365. /**
  366. * Current font info.
  367. * @protected
  368. */
  369. protected $CurrentFont;
  370. /**
  371. * Current font size in points.
  372. * @protected
  373. */
  374. protected $FontSizePt;
  375. /**
  376. * Current font size in user unit.
  377. * @protected
  378. */
  379. protected $FontSize;
  380. /**
  381. * Commands for drawing color.
  382. * @protected
  383. */
  384. protected $DrawColor;
  385. /**
  386. * Commands for filling color.
  387. * @protected
  388. */
  389. protected $FillColor;
  390. /**
  391. * Commands for text color.
  392. * @protected
  393. */
  394. protected $TextColor;
  395. /**
  396. * Indicates whether fill and text colors are different.
  397. * @protected
  398. */
  399. protected $ColorFlag;
  400. /**
  401. * Automatic page breaking.
  402. * @protected
  403. */
  404. protected $AutoPageBreak;
  405. /**
  406. * Threshold used to trigger page breaks.
  407. * @protected
  408. */
  409. protected $PageBreakTrigger;
  410. /**
  411. * Flag set when processing page header.
  412. * @protected
  413. */
  414. protected $InHeader = false;
  415. /**
  416. * Flag set when processing page footer.
  417. * @protected
  418. */
  419. protected $InFooter = false;
  420. /**
  421. * Zoom display mode.
  422. * @protected
  423. */
  424. protected $ZoomMode;
  425. /**
  426. * Layout display mode.
  427. * @protected
  428. */
  429. protected $LayoutMode;
  430. /**
  431. * If true set the document information dictionary in Unicode.
  432. * @protected
  433. */
  434. protected $docinfounicode = true;
  435. /**
  436. * Document title.
  437. * @protected
  438. */
  439. protected $title = '';
  440. /**
  441. * Document subject.
  442. * @protected
  443. */
  444. protected $subject = '';
  445. /**
  446. * Document author.
  447. * @protected
  448. */
  449. protected $author = '';
  450. /**
  451. * Document keywords.
  452. * @protected
  453. */
  454. protected $keywords = '';
  455. /**
  456. * Document creator.
  457. * @protected
  458. */
  459. protected $creator = '';
  460. /**
  461. * Starting page number.
  462. * @protected
  463. */
  464. protected $starting_page_number = 1;
  465. /**
  466. * String alias for total number of pages.
  467. * @protected
  468. */
  469. protected $alias_tot_pages = '{:ptp:}';
  470. /**
  471. * String alias for page number.
  472. * @protected
  473. */
  474. protected $alias_num_page = '{:pnp:}';
  475. /**
  476. * String alias for total number of pages in a single group.
  477. * @protected
  478. */
  479. protected $alias_group_tot_pages = '{:ptg:}';
  480. /**
  481. * String alias for group page number.
  482. * @protected
  483. */
  484. protected $alias_group_num_page = '{:png:}';
  485. /**
  486. * String alias for right shift compensation used to correctly align page numbers on the right.
  487. * @protected
  488. */
  489. protected $alias_right_shift = '{rsc:';
  490. /**
  491. * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
  492. * @since 2002-07-31
  493. * @author Nicola Asuni
  494. * @protected
  495. */
  496. protected $img_rb_x;
  497. /**
  498. * The right-bottom corner Y coordinate of last inserted image.
  499. * @since 2002-07-31
  500. * @author Nicola Asuni
  501. * @protected
  502. */
  503. protected $img_rb_y;
  504. /**
  505. * Adjusting factor to convert pixels to user units.
  506. * @since 2004-06-14
  507. * @author Nicola Asuni
  508. * @protected
  509. */
  510. protected $imgscale = 1;
  511. /**
  512. * Boolean flag set to true when the input text is unicode (require unicode fonts).
  513. * @since 2005-01-02
  514. * @author Nicola Asuni
  515. * @protected
  516. */
  517. protected $isunicode = false;
  518. /**
  519. * Object containing unicode data.
  520. * @since 5.9.004 (2010-10-18)
  521. * @author Nicola Asuni
  522. * @protected
  523. */
  524. protected $unicode;
  525. /**
  526. * Object containing font encoding maps.
  527. * @since 5.9.123 (2011-10-01)
  528. * @author Nicola Asuni
  529. * @protected
  530. */
  531. protected $encmaps;
  532. /**
  533. * PDF version.
  534. * @since 1.5.3
  535. * @protected
  536. */
  537. protected $PDFVersion = '1.7';
  538. /**
  539. * ID of the stored default header template (-1 = not set).
  540. * @protected
  541. */
  542. protected $header_xobjid = -1;
  543. /**
  544. * If true reset the Header Xobject template at each page
  545. * @protected
  546. */
  547. protected $header_xobj_autoreset = false;
  548. /**
  549. * Minimum distance between header and top page margin.
  550. * @protected
  551. */
  552. protected $header_margin;
  553. /**
  554. * Minimum distance between footer and bottom page margin.
  555. * @protected
  556. */
  557. protected $footer_margin;
  558. /**
  559. * Original left margin value.
  560. * @protected
  561. * @since 1.53.0.TC013
  562. */
  563. protected $original_lMargin;
  564. /**
  565. * Original right margin value.
  566. * @protected
  567. * @since 1.53.0.TC013
  568. */
  569. protected $original_rMargin;
  570. /**
  571. * Default font used on page header.
  572. * @protected
  573. */
  574. protected $header_font;
  575. /**
  576. * Default font used on page footer.
  577. * @protected
  578. */
  579. protected $footer_font;
  580. /**
  581. * Language templates.
  582. * @protected
  583. */
  584. protected $l;
  585. /**
  586. * Barcode to print on page footer (only if set).
  587. * @protected
  588. */
  589. protected $barcode = false;
  590. /**
  591. * Boolean flag to print/hide page header.
  592. * @protected
  593. */
  594. protected $print_header = true;
  595. /**
  596. * Boolean flag to print/hide page footer.
  597. * @protected
  598. */
  599. protected $print_footer = true;
  600. /**
  601. * Header image logo.
  602. * @protected
  603. */
  604. protected $header_logo = '';
  605. /**
  606. * Width of header image logo in user units.
  607. * @protected
  608. */
  609. protected $header_logo_width = 30;
  610. /**
  611. * Title to be printed on default page header.
  612. * @protected
  613. */
  614. protected $header_title = '';
  615. /**
  616. * String to pring on page header after title.
  617. * @protected
  618. */
  619. protected $header_string = '';
  620. /**
  621. * Color for header text (RGB array).
  622. * @since 5.9.174 (2012-07-25)
  623. * @protected
  624. */
  625. protected $header_text_color = array(0,0,0);
  626. /**
  627. * Color for header line (RGB array).
  628. * @since 5.9.174 (2012-07-25)
  629. * @protected
  630. */
  631. protected $header_line_color = array(0,0,0);
  632. /**
  633. * Color for footer text (RGB array).
  634. * @since 5.9.174 (2012-07-25)
  635. * @protected
  636. */
  637. protected $footer_text_color = array(0,0,0);
  638. /**
  639. * Color for footer line (RGB array).
  640. * @since 5.9.174 (2012-07-25)
  641. * @protected
  642. */
  643. protected $footer_line_color = array(0,0,0);
  644. /**
  645. * Text shadow data array.
  646. * @since 5.9.174 (2012-07-25)
  647. * @protected
  648. */
  649. protected $txtshadow = array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal');
  650. /**
  651. * Default number of columns for html table.
  652. * @protected
  653. */
  654. protected $default_table_columns = 4;
  655. // variables for html parser
  656. /**
  657. * HTML PARSER: array to store current link and rendering styles.
  658. * @protected
  659. */
  660. protected $HREF = array();
  661. /**
  662. * List of available fonts on filesystem.
  663. * @protected
  664. */
  665. protected $fontlist = array();
  666. /**
  667. * Current foreground color.
  668. * @protected
  669. */
  670. protected $fgcolor;
  671. /**
  672. * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
  673. * @protected
  674. */
  675. protected $listordered = array();
  676. /**
  677. * HTML PARSER: array count list items on nested lists.
  678. * @protected
  679. */
  680. protected $listcount = array();
  681. /**
  682. * HTML PARSER: current list nesting level.
  683. * @protected
  684. */
  685. protected $listnum = 0;
  686. /**
  687. * HTML PARSER: indent amount for lists.
  688. * @protected
  689. */
  690. protected $listindent = 0;
  691. /**
  692. * HTML PARSER: current list indententation level.
  693. * @protected
  694. */
  695. protected $listindentlevel = 0;
  696. /**
  697. * Current background color.
  698. * @protected
  699. */
  700. protected $bgcolor;
  701. /**
  702. * Temporary font size in points.
  703. * @protected
  704. */
  705. protected $tempfontsize = 10;
  706. /**
  707. * Spacer string for LI tags.
  708. * @protected
  709. */
  710. protected $lispacer = '';
  711. /**
  712. * Default encoding.
  713. * @protected
  714. * @since 1.53.0.TC010
  715. */
  716. protected $encoding = 'UTF-8';
  717. /**
  718. * PHP internal encoding.
  719. * @protected
  720. * @since 1.53.0.TC016
  721. */
  722. protected $internal_encoding;
  723. /**
  724. * Boolean flag to indicate if the document language is Right-To-Left.
  725. * @protected
  726. * @since 2.0.000
  727. */
  728. protected $rtl = false;
  729. /**
  730. * Boolean flag used to force RTL or LTR string direction.
  731. * @protected
  732. * @since 2.0.000
  733. */
  734. protected $tmprtl = false;
  735. // --- Variables used for document encryption:
  736. /**
  737. * IBoolean flag indicating whether document is protected.
  738. * @protected
  739. * @since 2.0.000 (2008-01-02)
  740. */
  741. protected $encrypted;
  742. /**
  743. * Array containing encryption settings.
  744. * @protected
  745. * @since 5.0.005 (2010-05-11)
  746. */
  747. protected $encryptdata = array();
  748. /**
  749. * Last RC4 key encrypted (cached for optimisation).
  750. * @protected
  751. * @since 2.0.000 (2008-01-02)
  752. */
  753. protected $last_enc_key;
  754. /**
  755. * Last RC4 computed key.
  756. * @protected
  757. * @since 2.0.000 (2008-01-02)
  758. */
  759. protected $last_enc_key_c;
  760. /**
  761. * Encryption padding string.
  762. * @protected
  763. */
  764. 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";
  765. /**
  766. * File ID (used on document trailer).
  767. * @protected
  768. * @since 5.0.005 (2010-05-12)
  769. */
  770. protected $file_id;
  771. // --- bookmark ---
  772. /**
  773. * Outlines for bookmark.
  774. * @protected
  775. * @since 2.1.002 (2008-02-12)
  776. */
  777. protected $outlines = array();
  778. /**
  779. * Outline root for bookmark.
  780. * @protected
  781. * @since 2.1.002 (2008-02-12)
  782. */
  783. protected $OutlineRoot;
  784. // --- javascript and form ---
  785. /**
  786. * Javascript code.
  787. * @protected
  788. * @since 2.1.002 (2008-02-12)
  789. */
  790. protected $javascript = '';
  791. /**
  792. * Javascript counter.
  793. * @protected
  794. * @since 2.1.002 (2008-02-12)
  795. */
  796. protected $n_js;
  797. /**
  798. * line trough state
  799. * @protected
  800. * @since 2.8.000 (2008-03-19)
  801. */
  802. protected $linethrough;
  803. /**
  804. * Array with additional document-wide usage rights for the document.
  805. * @protected
  806. * @since 5.8.014 (2010-08-23)
  807. */
  808. protected $ur = array();
  809. /**
  810. * DPI (Dot Per Inch) Document Resolution (do not change).
  811. * @protected
  812. * @since 3.0.000 (2008-03-27)
  813. */
  814. protected $dpi = 72;
  815. /**
  816. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  817. * @protected
  818. * @since 3.0.000 (2008-03-27)
  819. */
  820. protected $newpagegroup = array();
  821. /**
  822. * Array that contains the number of pages in each page group.
  823. * @protected
  824. * @since 3.0.000 (2008-03-27)
  825. */
  826. protected $pagegroups = array();
  827. /**
  828. * Current page group number.
  829. * @protected
  830. * @since 3.0.000 (2008-03-27)
  831. */
  832. protected $currpagegroup = 0;
  833. /**
  834. * Array of transparency objects and parameters.
  835. * @protected
  836. * @since 3.0.000 (2008-03-27)
  837. */
  838. protected $extgstates;
  839. /**
  840. * Set the default JPEG compression quality (1-100).
  841. * @protected
  842. * @since 3.0.000 (2008-03-27)
  843. */
  844. protected $jpeg_quality;
  845. /**
  846. * Default cell height ratio.
  847. * @protected
  848. * @since 3.0.014 (2008-05-23)
  849. */
  850. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  851. /**
  852. * PDF viewer preferences.
  853. * @protected
  854. * @since 3.1.000 (2008-06-09)
  855. */
  856. protected $viewer_preferences;
  857. /**
  858. * A name object specifying how the document should be displayed when opened.
  859. * @protected
  860. * @since 3.1.000 (2008-06-09)
  861. */
  862. protected $PageMode;
  863. /**
  864. * Array for storing gradient information.
  865. * @protected
  866. * @since 3.1.000 (2008-06-09)
  867. */
  868. protected $gradients = array();
  869. /**
  870. * Array used to store positions inside the pages buffer (keys are the page numbers).
  871. * @protected
  872. * @since 3.2.000 (2008-06-26)
  873. */
  874. protected $intmrk = array();
  875. /**
  876. * Array used to store positions inside the pages buffer (keys are the page numbers).
  877. * @protected
  878. * @since 5.7.000 (2010-08-03)
  879. */
  880. protected $bordermrk = array();
  881. /**
  882. * Array used to store page positions to track empty pages (keys are the page numbers).
  883. * @protected
  884. * @since 5.8.007 (2010-08-18)
  885. */
  886. protected $emptypagemrk = array();
  887. /**
  888. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  889. * @protected
  890. * @since 4.6.021 (2009-07-20)
  891. */
  892. protected $cntmrk = array();
  893. /**
  894. * Array used to store footer positions of each page.
  895. * @protected
  896. * @since 3.2.000 (2008-07-01)
  897. */
  898. protected $footerpos = array();
  899. /**
  900. * Array used to store footer length of each page.
  901. * @protected
  902. * @since 4.0.014 (2008-07-29)
  903. */
  904. protected $footerlen = array();
  905. /**
  906. * Boolean flag to indicate if a new line is created.
  907. * @protected
  908. * @since 3.2.000 (2008-07-01)
  909. */
  910. protected $newline = true;
  911. /**
  912. * End position of the latest inserted line.
  913. * @protected
  914. * @since 3.2.000 (2008-07-01)
  915. */
  916. protected $endlinex = 0;
  917. /**
  918. * PDF string for width value of the last line.
  919. * @protected
  920. * @since 4.0.006 (2008-07-16)
  921. */
  922. protected $linestyleWidth = '';
  923. /**
  924. * PDF string for CAP value of the last line.
  925. * @protected
  926. * @since 4.0.006 (2008-07-16)
  927. */
  928. protected $linestyleCap = '0 J';
  929. /**
  930. * PDF string for join value of the last line.
  931. * @protected
  932. * @since 4.0.006 (2008-07-16)
  933. */
  934. protected $linestyleJoin = '0 j';
  935. /**
  936. * PDF string for dash value of the last line.
  937. * @protected
  938. * @since 4.0.006 (2008-07-16)
  939. */
  940. protected $linestyleDash = '[] 0 d';
  941. /**
  942. * Boolean flag to indicate if marked-content sequence is open.
  943. * @protected
  944. * @since 4.0.013 (2008-07-28)
  945. */
  946. protected $openMarkedContent = false;
  947. /**
  948. * Count the latest inserted vertical spaces on HTML.
  949. * @protected
  950. * @since 4.0.021 (2008-08-24)
  951. */
  952. protected $htmlvspace = 0;
  953. /**
  954. * Array of Spot colors.
  955. * @protected
  956. * @since 4.0.024 (2008-09-12)
  957. */
  958. protected $spot_colors = array();
  959. /**
  960. * Symbol used for HTML unordered list items.
  961. * @protected
  962. * @since 4.0.028 (2008-09-26)
  963. */
  964. protected $lisymbol = '';
  965. /**
  966. * String used to mark the beginning and end of EPS image blocks.
  967. * @protected
  968. * @since 4.1.000 (2008-10-18)
  969. */
  970. protected $epsmarker = 'x#!#EPS#!#x';
  971. /**
  972. * Array of transformation matrix.
  973. * @protected
  974. * @since 4.2.000 (2008-10-29)
  975. */
  976. protected $transfmatrix = array();
  977. /**
  978. * Current key for transformation matrix.
  979. * @protected
  980. * @since 4.8.005 (2009-09-17)
  981. */
  982. protected $transfmatrix_key = 0;
  983. /**
  984. * Booklet mode for double-sided pages.
  985. * @protected
  986. * @since 4.2.000 (2008-10-29)
  987. */
  988. protected $booklet = false;
  989. /**
  990. * Epsilon value used for float calculations.
  991. * @protected
  992. * @since 4.2.000 (2008-10-29)
  993. */
  994. protected $feps = 0.005;
  995. /**
  996. * Array used for custom vertical spaces for HTML tags.
  997. * @protected
  998. * @since 4.2.001 (2008-10-30)
  999. */
  1000. protected $tagvspaces = array();
  1001. /**
  1002. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  1003. * @protected
  1004. * @since 4.2.007 (2008-11-12)
  1005. */
  1006. protected $customlistindent = -1;
  1007. /**
  1008. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  1009. * @protected
  1010. * @since 4.2.010 (2008-11-14)
  1011. */
  1012. protected $opencell = true;
  1013. /**
  1014. * Array of files to embedd.
  1015. * @protected
  1016. * @since 4.4.000 (2008-12-07)
  1017. */
  1018. protected $embeddedfiles = array();
  1019. /**
  1020. * Boolean flag to indicate if we are inside a PRE tag.
  1021. * @protected
  1022. * @since 4.4.001 (2008-12-08)
  1023. */
  1024. protected $premode = false;
  1025. /**
  1026. * Array used to store positions of graphics transformation blocks inside the page buffer.
  1027. * keys are the page numbers
  1028. * @protected
  1029. * @since 4.4.002 (2008-12-09)
  1030. */
  1031. protected $transfmrk = array();
  1032. /**
  1033. * Default color for html links.
  1034. * @protected
  1035. * @since 4.4.003 (2008-12-09)
  1036. */
  1037. protected $htmlLinkColorArray = array(0, 0, 255);
  1038. /**
  1039. * Default font style to add to html links.
  1040. * @protected
  1041. * @since 4.4.003 (2008-12-09)
  1042. */
  1043. protected $htmlLinkFontStyle = 'U';
  1044. /**
  1045. * Counts the number of pages.
  1046. * @protected
  1047. * @since 4.5.000 (2008-12-31)
  1048. */
  1049. protected $numpages = 0;
  1050. /**
  1051. * Array containing page lengths in bytes.
  1052. * @protected
  1053. * @since 4.5.000 (2008-12-31)
  1054. */
  1055. protected $pagelen = array();
  1056. /**
  1057. * Counts the number of pages.
  1058. * @protected
  1059. * @since 4.5.000 (2008-12-31)
  1060. */
  1061. protected $numimages = 0;
  1062. /**
  1063. * Store the image keys.
  1064. * @protected
  1065. * @since 4.5.000 (2008-12-31)
  1066. */
  1067. protected $imagekeys = array();
  1068. /**
  1069. * Length of the buffer in bytes.
  1070. * @protected
  1071. * @since 4.5.000 (2008-12-31)
  1072. */
  1073. protected $bufferlen = 0;
  1074. /**
  1075. * If true enables disk caching.
  1076. * @protected
  1077. * @since 4.5.000 (2008-12-31)
  1078. */
  1079. protected $diskcache = false;
  1080. /**
  1081. * Counts the number of fonts.
  1082. * @protected
  1083. * @since 4.5.000 (2009-01-02)
  1084. */
  1085. protected $numfonts = 0;
  1086. /**
  1087. * Store the font keys.
  1088. * @protected
  1089. * @since 4.5.000 (2009-01-02)
  1090. */
  1091. protected $fontkeys = array();
  1092. /**
  1093. * Store the font object IDs.
  1094. * @protected
  1095. * @since 4.8.001 (2009-09-09)
  1096. */
  1097. protected $font_obj_ids = array();
  1098. /**
  1099. * Store the fage status (true when opened, false when closed).
  1100. * @protected
  1101. * @since 4.5.000 (2009-01-02)
  1102. */
  1103. protected $pageopen = array();
  1104. /**
  1105. * Default monospace font.
  1106. * @protected
  1107. * @since 4.5.025 (2009-03-10)
  1108. */
  1109. protected $default_monospaced_font = 'courier';
  1110. /**
  1111. * Cloned copy of the current class object.
  1112. * @protected
  1113. * @since 4.5.029 (2009-03-19)
  1114. */
  1115. protected $objcopy;
  1116. /**
  1117. * Array used to store the lengths of cache files.
  1118. * @protected
  1119. * @since 4.5.029 (2009-03-19)
  1120. */
  1121. protected $cache_file_length = array();
  1122. /**
  1123. * Table header content to be repeated on each new page.
  1124. * @protected
  1125. * @since 4.5.030 (2009-03-20)
  1126. */
  1127. protected $thead = '';
  1128. /**
  1129. * Margins used for table header.
  1130. * @protected
  1131. * @since 4.5.030 (2009-03-20)
  1132. */
  1133. protected $theadMargins = array();
  1134. /**
  1135. * Cache array for UTF8StringToArray() method.
  1136. * @protected
  1137. * @since 4.5.037 (2009-04-07)
  1138. */
  1139. protected $cache_UTF8StringToArray = array();
  1140. /**
  1141. * Maximum size of cache array used for UTF8StringToArray() method.
  1142. * @protected
  1143. * @since 4.5.037 (2009-04-07)
  1144. */
  1145. protected $cache_maxsize_UTF8StringToArray = 8;
  1146. /**
  1147. * Current size of cache array used for UTF8StringToArray() method.
  1148. * @protected
  1149. * @since 4.5.037 (2009-04-07)
  1150. */
  1151. protected $cache_size_UTF8StringToArray = 0;
  1152. /**
  1153. * Boolean flag to enable document digital signature.
  1154. * @protected
  1155. * @since 4.6.005 (2009-04-24)
  1156. */
  1157. protected $sign = false;
  1158. /**
  1159. * Digital signature data.
  1160. * @protected
  1161. * @since 4.6.005 (2009-04-24)
  1162. */
  1163. protected $signature_data = array();
  1164. /**
  1165. * Digital signature max length.
  1166. * @protected
  1167. * @since 4.6.005 (2009-04-24)
  1168. */
  1169. protected $signature_max_length = 11742;
  1170. /**
  1171. * Data for digital signature appearance.
  1172. * @protected
  1173. * @since 5.3.011 (2010-06-16)
  1174. */
  1175. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1176. /**
  1177. * Array of empty digital signature appearances.
  1178. * @protected
  1179. * @since 5.9.101 (2011-07-06)
  1180. */
  1181. protected $empty_signature_appearance = array();
  1182. /**
  1183. * Regular expression used to find blank characters (required for word-wrapping).
  1184. * @protected
  1185. * @since 4.6.006 (2009-04-28)
  1186. */
  1187. protected $re_spaces = '/[^\S\xa0]/';
  1188. /**
  1189. * Array of $re_spaces parts.
  1190. * @protected
  1191. * @since 5.5.011 (2010-07-09)
  1192. */
  1193. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1194. /**
  1195. * Digital signature object ID.
  1196. * @protected
  1197. * @since 4.6.022 (2009-06-23)
  1198. */
  1199. protected $sig_obj_id = 0;
  1200. /**
  1201. * ByteRange placemark used during digital signature process.
  1202. * @protected
  1203. * @since 4.6.028 (2009-08-25)
  1204. */
  1205. protected $byterange_string = '/ByteRange[0 ********** ********** **********]';
  1206. /**
  1207. * Placemark used during digital signature process.
  1208. * @protected
  1209. * @since 4.6.028 (2009-08-25)
  1210. */
  1211. protected $sig_annot_ref = '***SIGANNREF*** 0 R';
  1212. /**
  1213. * ID of page objects.
  1214. * @protected
  1215. * @since 4.7.000 (2009-08-29)
  1216. */
  1217. protected $page_obj_id = array();
  1218. /**
  1219. * List of form annotations IDs.
  1220. * @protected
  1221. * @since 4.8.000 (2009-09-07)
  1222. */
  1223. protected $form_obj_id = array();
  1224. /**
  1225. * 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.
  1226. * @protected
  1227. * @since 4.8.000 (2009-09-07)
  1228. */
  1229. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1230. /**
  1231. * Javascript objects array.
  1232. * @protected
  1233. * @since 4.8.000 (2009-09-07)
  1234. */
  1235. protected $js_objects = array();
  1236. /**
  1237. * Current form action (used during XHTML rendering).
  1238. * @protected
  1239. * @since 4.8.000 (2009-09-07)
  1240. */
  1241. protected $form_action = '';
  1242. /**
  1243. * Current form encryption type (used during XHTML rendering).
  1244. * @protected
  1245. * @since 4.8.000 (2009-09-07)
  1246. */
  1247. protected $form_enctype = 'application/x-www-form-urlencoded';
  1248. /**
  1249. * Current method to submit forms.
  1250. * @protected
  1251. * @since 4.8.000 (2009-09-07)
  1252. */
  1253. protected $form_mode = 'post';
  1254. /**
  1255. * List of fonts used on form fields (fontname => fontkey).
  1256. * @protected
  1257. * @since 4.8.001 (2009-09-09)
  1258. */
  1259. protected $annotation_fonts = array();
  1260. /**
  1261. * List of radio buttons parent objects.
  1262. * @protected
  1263. * @since 4.8.001 (2009-09-09)
  1264. */
  1265. protected $radiobutton_groups = array();
  1266. /**
  1267. * List of radio group objects IDs.
  1268. * @protected
  1269. * @since 4.8.001 (2009-09-09)
  1270. */
  1271. protected $radio_groups = array();
  1272. /**
  1273. * Text indentation value (used for text-indent CSS attribute).
  1274. * @protected
  1275. * @since 4.8.006 (2009-09-23)
  1276. */
  1277. protected $textindent = 0;
  1278. /**
  1279. * Store page number when startTransaction() is called.
  1280. * @protected
  1281. * @since 4.8.006 (2009-09-23)
  1282. */
  1283. protected $start_transaction_page = 0;
  1284. /**
  1285. * Store Y position when startTransaction() is called.
  1286. * @protected
  1287. * @since 4.9.001 (2010-03-28)
  1288. */
  1289. protected $start_transaction_y = 0;
  1290. /**
  1291. * True when we are printing the thead section on a new page.
  1292. * @protected
  1293. * @since 4.8.027 (2010-01-25)
  1294. */
  1295. protected $inthead = false;
  1296. /**
  1297. * Array of column measures (width, space, starting Y position).
  1298. * @protected
  1299. * @since 4.9.001 (2010-03-28)
  1300. */
  1301. protected $columns = array();
  1302. /**
  1303. * Number of colums.
  1304. * @protected
  1305. * @since 4.9.001 (2010-03-28)
  1306. */
  1307. protected $num_columns = 1;
  1308. /**
  1309. * Current column number.
  1310. * @protected
  1311. * @since 4.9.001 (2010-03-28)
  1312. */
  1313. protected $current_column = 0;
  1314. /**
  1315. * Starting page for columns.
  1316. * @protected
  1317. * @since 4.9.001 (2010-03-28)
  1318. */
  1319. protected $column_start_page = 0;
  1320. /**
  1321. * Maximum page and column selected.
  1322. * @protected
  1323. * @since 5.8.000 (2010-08-11)
  1324. */
  1325. protected $maxselcol = array('page' => 0, 'column' => 0);
  1326. /**
  1327. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1328. * @protected
  1329. * @since 5.8.000 (2010-08-11)
  1330. */
  1331. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1332. /**
  1333. * 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.
  1334. * @protected
  1335. * @since 4.9.008 (2010-04-03)
  1336. */
  1337. protected $textrendermode = 0;
  1338. /**
  1339. * Text stroke width in doc units.
  1340. * @protected
  1341. * @since 4.9.008 (2010-04-03)
  1342. */
  1343. protected $textstrokewidth = 0;
  1344. /**
  1345. * Current stroke color.
  1346. * @protected
  1347. * @since 4.9.008 (2010-04-03)
  1348. */
  1349. protected $strokecolor;
  1350. /**
  1351. * Default unit of measure for document.
  1352. * @protected
  1353. * @since 5.0.000 (2010-04-22)
  1354. */
  1355. protected $pdfunit = 'mm';
  1356. /**
  1357. * Boolean flag true when we are on TOC (Table Of Content) page.
  1358. * @protected
  1359. */
  1360. protected $tocpage = false;
  1361. /**
  1362. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1363. * @protected
  1364. * @since 5.0.000 (2010-04-26)
  1365. */
  1366. protected $rasterize_vector_images = false;
  1367. /**
  1368. * Boolean flag: if true enables font subsetting by default.
  1369. * @protected
  1370. * @since 5.3.002 (2010-06-07)
  1371. */
  1372. protected $font_subsetting = true;
  1373. /**
  1374. * Array of default graphic settings.
  1375. * @protected
  1376. * @since 5.5.008 (2010-07-02)
  1377. */
  1378. protected $default_graphic_vars = array();
  1379. /**
  1380. * Array of XObjects.
  1381. * @protected
  1382. * @since 5.8.014 (2010-08-23)
  1383. */
  1384. protected $xobjects = array();
  1385. /**
  1386. * Boolean value true when we are inside an XObject.
  1387. * @protected
  1388. * @since 5.8.017 (2010-08-24)
  1389. */
  1390. protected $inxobj = false;
  1391. /**
  1392. * Current XObject ID.
  1393. * @protected
  1394. * @since 5.8.017 (2010-08-24)
  1395. */
  1396. protected $xobjid = '';
  1397. /**
  1398. * Percentage of character stretching.
  1399. * @protected
  1400. * @since 5.9.000 (2010-09-29)
  1401. */
  1402. protected $font_stretching = 100;
  1403. /**
  1404. * Increases or decreases the space between characters in a text by the specified amount (tracking).
  1405. * @protected
  1406. * @since 5.9.000 (2010-09-29)
  1407. */
  1408. protected $font_spacing = 0;
  1409. /**
  1410. * Array of no-write regions.
  1411. * ('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)
  1412. * @protected
  1413. * @since 5.9.003 (2010-10-14)
  1414. */
  1415. protected $page_regions = array();
  1416. /**
  1417. * Array containing HTML color names and values.
  1418. * @protected
  1419. * @since 5.9.004 (2010-10-18)
  1420. */
  1421. protected $webcolor = array();
  1422. /**
  1423. * Array containing spot color names and values.
  1424. * @protected
  1425. * @since 5.9.012 (2010-11-11)
  1426. */
  1427. protected $spotcolor = array();
  1428. /**
  1429. * Array of PDF layers data.
  1430. * @protected
  1431. * @since 5.9.102 (2011-07-13)
  1432. */
  1433. protected $pdflayers = array();
  1434. /**
  1435. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1436. * @protected
  1437. * @since 5.9.097 (2011-06-23)
  1438. */
  1439. protected $dests = array();
  1440. /**
  1441. * Object ID for Named Destinations
  1442. * @protected
  1443. * @since 5.9.097 (2011-06-23)
  1444. */
  1445. protected $n_dests;
  1446. /**
  1447. * Directory used for the last SVG image.
  1448. * @protected
  1449. * @since 5.0.000 (2010-05-05)
  1450. */
  1451. protected $svgdir = '';
  1452. /**
  1453. * Deafult unit of measure for SVG.
  1454. * @protected
  1455. * @since 5.0.000 (2010-05-02)
  1456. */
  1457. protected $svgunit = 'px';
  1458. /**
  1459. * Array of SVG gradients.
  1460. * @protected
  1461. * @since 5.0.000 (2010-05-02)
  1462. */
  1463. protected $svggradients = array();
  1464. /**
  1465. * ID of last SVG gradient.
  1466. * @protected
  1467. * @since 5.0.000 (2010-05-02)
  1468. */
  1469. protected $svggradientid = 0;
  1470. /**
  1471. * Boolean value true when in SVG defs group.
  1472. * @protected
  1473. * @since 5.0.000 (2010-05-02)
  1474. */
  1475. protected $svgdefsmode = false;
  1476. /**
  1477. * Array of SVG defs.
  1478. * @protected
  1479. * @since 5.0.000 (2010-05-02)
  1480. */
  1481. protected $svgdefs = array();
  1482. /**
  1483. * Boolean value true when in SVG clipPath tag.
  1484. * @protected
  1485. * @since 5.0.000 (2010-04-26)
  1486. */
  1487. protected $svgclipmode = false;
  1488. /**
  1489. * Array of SVG clipPath commands.
  1490. * @protected
  1491. * @since 5.0.000 (2010-05-02)
  1492. */
  1493. protected $svgclippaths = array();
  1494. /**
  1495. * Array of SVG clipPath tranformation matrix.
  1496. * @protected
  1497. * @since 5.8.022 (2010-08-31)
  1498. */
  1499. protected $svgcliptm = array();
  1500. /**
  1501. * ID of last SVG clipPath.
  1502. * @protected
  1503. * @since 5.0.000 (2010-05-02)
  1504. */
  1505. protected $svgclipid = 0;
  1506. /**
  1507. * SVG text.
  1508. * @protected
  1509. * @since 5.0.000 (2010-05-02)
  1510. */
  1511. protected $svgtext = '';
  1512. /**
  1513. * SVG text properties.
  1514. * @protected
  1515. * @since 5.8.013 (2010-08-23)
  1516. */
  1517. protected $svgtextmode = array();
  1518. /**
  1519. * Array of hinheritable SVG properties.
  1520. * @protected
  1521. * @since 5.0.000 (2010-05-02)
  1522. */
  1523. 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');
  1524. /**
  1525. * Array of SVG properties.
  1526. * @protected
  1527. * @since 5.0.000 (2010-05-02)
  1528. */
  1529. protected $svgstyles = array(array(
  1530. 'alignment-baseline' => 'auto',
  1531. 'baseline-shift' => 'baseline',
  1532. 'clip' => 'auto',
  1533. 'clip-path' => 'none',
  1534. 'clip-rule' => 'nonzero',
  1535. 'color' => 'black',
  1536. 'color-interpolation' => 'sRGB',
  1537. 'color-interpolation-filters' => 'linearRGB',
  1538. 'color-profile' => 'auto',
  1539. 'color-rendering' => 'auto',
  1540. 'cursor' => 'auto',
  1541. 'direction' => 'ltr',
  1542. 'display' => 'inline',
  1543. 'dominant-baseline' => 'auto',
  1544. 'enable-background' => 'accumulate',
  1545. 'fill' => 'black',
  1546. 'fill-opacity' => 1,
  1547. 'fill-rule' => 'nonzero',
  1548. 'filter' => 'none',
  1549. 'flood-color' => 'black',
  1550. 'flood-opacity' => 1,
  1551. 'font' => '',
  1552. 'font-family' => 'helvetica',
  1553. 'font-size' => 'medium',
  1554. 'font-size-adjust' => 'none',
  1555. 'font-stretch' => 'normal',
  1556. 'font-style' => 'normal',
  1557. 'font-variant' => 'normal',
  1558. 'font-weight' => 'normal',
  1559. 'glyph-orientation-horizontal' => '0deg',
  1560. 'glyph-orientation-vertical' => 'auto',
  1561. 'image-rendering' => 'auto',
  1562. 'kerning' => 'auto',
  1563. 'letter-spacing' => 'normal',
  1564. 'lighting-color' => 'white',
  1565. 'marker' => '',
  1566. 'marker-end' => 'none',
  1567. 'marker-mid' => 'none',
  1568. 'marker-start' => 'none',
  1569. 'mask' => 'none',
  1570. 'opacity' => 1,
  1571. 'overflow' => 'auto',
  1572. 'pointer-events' => 'visiblePainted',
  1573. 'shape-rendering' => 'auto',
  1574. 'stop-color' => 'black',
  1575. 'stop-opacity' => 1,
  1576. 'stroke' => 'none',
  1577. 'stroke-dasharray' => 'none',
  1578. 'stroke-dashoffset' => 0,
  1579. 'stroke-linecap' => 'butt',
  1580. 'stroke-linejoin' => 'miter',
  1581. 'stroke-miterlimit' => 4,
  1582. 'stroke-opacity' => 1,
  1583. 'stroke-width' => 1,
  1584. 'text-anchor' => 'start',
  1585. 'text-decoration' => 'none',
  1586. 'text-rendering' => 'auto',
  1587. 'unicode-bidi' => 'normal',
  1588. 'visibility' => 'visible',
  1589. 'word-spacing' => 'normal',
  1590. 'writing-mode' => 'lr-tb',
  1591. 'text-color' => 'black',
  1592. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1593. ));
  1594. /**
  1595. * If true force sRGB color profile for all document.
  1596. * @protected
  1597. * @since 5.9.121 (2011-09-28)
  1598. */
  1599. protected $force_srgb = false;
  1600. /**
  1601. * If true set the document to PDF/A mode.
  1602. * @protected
  1603. * @since 5.9.121 (2011-09-27)
  1604. */
  1605. protected $pdfa_mode = false;
  1606. /**
  1607. * Document creation date-time
  1608. * @protected
  1609. * @since 5.9.152 (2012-03-22)
  1610. */
  1611. protected $doc_creation_timestamp;
  1612. /**
  1613. * Document modification date-time
  1614. * @protected
  1615. * @since 5.9.152 (2012-03-22)
  1616. */
  1617. protected $doc_modification_timestamp;
  1618. /**
  1619. * Custom XMP data.
  1620. * @protected
  1621. * @since 5.9.128 (2011-10-06)
  1622. */
  1623. protected $custom_xmp = '';
  1624. /**
  1625. * Overprint mode array.
  1626. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1627. * @protected
  1628. * @since 5.9.152 (2012-03-23)
  1629. */
  1630. protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
  1631. /**
  1632. * Alpha mode array.
  1633. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1634. * @protected
  1635. * @since 5.9.152 (2012-03-23)
  1636. */
  1637. protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
  1638. /**
  1639. * Define the page boundaries boxes to be set on document.
  1640. * @protected
  1641. * @since 5.9.152 (2012-03-23)
  1642. */
  1643. protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  1644. /**
  1645. * Set the document producer metadata.
  1646. * @protected
  1647. * @since 5.9.152 (2012-03-23)
  1648. */
  1649. protected $pdfproducer;
  1650. /**
  1651. * If true print TCPDF meta link.
  1652. * @protected
  1653. * @since 5.9.152 (2012-03-23)
  1654. */
  1655. protected $tcpdflink = true;
  1656. /**
  1657. * Cache array for computed GD gamma values.
  1658. * @protected
  1659. * @since 5.9.1632 (2012-06-05)
  1660. */
  1661. protected $gdgammacache = array();
  1662. //------------------------------------------------------------
  1663. // METHODS
  1664. //------------------------------------------------------------
  1665. /**
  1666. * This is the class constructor.
  1667. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
  1668. * @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>
  1669. * @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.
  1670. * @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().
  1671. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1672. * @param $encoding (string) Charset encoding; default is UTF-8.
  1673. * @param $diskcache (boolean) If TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
  1674. * @param $pdfa (boolean) If TRUE set the document to PDF/A mode.
  1675. * @public
  1676. * @see getPageSizeFromFormat(), setPageFormat()
  1677. */
  1678. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1679. /* Set internal character encoding to ASCII */
  1680. if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
  1681. $this->internal_encoding = mb_internal_encoding();
  1682. mb_internal_encoding('ASCII');
  1683. }
  1684. // get array of HTML colors
  1685. require(dirname(__FILE__).'/htmlcolors.php');
  1686. $this->webcolor = $webcolor;
  1687. // get array of custom spot colors
  1688. if (file_exists(dirname(__FILE__).'/spotcolors.php')) {
  1689. require(dirname(__FILE__).'/spotcolors.php');
  1690. $this->spotcolor = $spotcolor;
  1691. } else {
  1692. $this->spotcolor = array();
  1693. }
  1694. require_once(dirname(__FILE__).'/unicode_data.php');
  1695. $this->unicode = new TCPDF_UNICODE_DATA();
  1696. require_once(dirname(__FILE__).'/encodings_maps.php');
  1697. $this->encmaps = new TCPDF_ENCODING_MAPS();
  1698. $this->font_obj_ids = array();
  1699. $this->page_obj_id = array();
  1700. $this->form_obj_id = array();
  1701. // set pdf/a mode
  1702. $this->pdfa_mode = $pdfa;
  1703. $this->force_srgb = false;
  1704. // set disk caching
  1705. $this->diskcache = $diskcache ? true : false;
  1706. // set language direction
  1707. $this->rtl = false;
  1708. $this->tmprtl = false;
  1709. // some checks
  1710. $this->_dochecks();
  1711. // initialization of properties
  1712. $this->isunicode = $unicode;
  1713. $this->page = 0;
  1714. $this->transfmrk[0] = array();
  1715. $this->pagedim = array();
  1716. $this->n = 2;
  1717. $this->buffer = '';
  1718. $this->pages = array();
  1719. $this->state = 0;
  1720. $this->fonts = array();
  1721. $this->FontFiles = array();
  1722. $this->diffs = array();
  1723. $this->images = array();
  1724. $this->links = array();
  1725. $this->gradients = array();
  1726. $this->InFooter = false;
  1727. $this->lasth = 0;
  1728. $this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  1729. $this->FontStyle = '';
  1730. $this->FontSizePt = 12;
  1731. $this->underline = false;
  1732. $this->overline = false;
  1733. $this->linethrough = false;
  1734. $this->DrawColor = '0 G';
  1735. $this->FillColor = '0 g';
  1736. $this->TextColor = '0 g';
  1737. $this->ColorFlag = false;
  1738. $this->pdflayers = array();
  1739. // encryption values
  1740. $this->encrypted = false;
  1741. $this->last_enc_key = '';
  1742. // standard Unicode fonts
  1743. $this->CoreFonts = array(
  1744. 'courier'=>'Courier',
  1745. 'courierB'=>'Courier-Bold',
  1746. 'courierI'=>'Courier-Oblique',
  1747. 'courierBI'=>'Courier-BoldOblique',
  1748. 'helvetica'=>'Helvetica',
  1749. 'helveticaB'=>'Helvetica-Bold',
  1750. 'helveticaI'=>'Helvetica-Oblique',
  1751. 'helveticaBI'=>'Helvetica-BoldOblique',
  1752. 'times'=>'Times-Roman',
  1753. 'timesB'=>'Times-Bold',
  1754. 'timesI'=>'Times-Italic',
  1755. 'timesBI'=>'Times-BoldItalic',
  1756. 'symbol'=>'Symbol',
  1757. 'zapfdingbats'=>'ZapfDingbats'
  1758. );
  1759. // set scale factor
  1760. $this->setPageUnit($unit);
  1761. // set page format and orientation
  1762. $this->setPageFormat($format, $orientation);
  1763. // page margins (1 cm)
  1764. $margin = 28.35 / $this->k;
  1765. $this->SetMargins($margin, $margin);
  1766. // internal cell padding
  1767. $cpadding = $margin / 10;
  1768. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1769. // cell margins
  1770. $this->setCellMargins(0, 0, 0, 0);
  1771. // line width (0.2 mm)
  1772. $this->LineWidth = 0.57 / $this->k;
  1773. $this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
  1774. $this->linestyleCap = '0 J';
  1775. $this->linestyleJoin = '0 j';
  1776. $this->linestyleDash = '[] 0 d';
  1777. // automatic page break
  1778. $this->SetAutoPageBreak(true, (2 * $margin));
  1779. // full width display mode
  1780. $this->SetDisplayMode('fullwidth');
  1781. // compression
  1782. $this->SetCompression();
  1783. // set default PDF version number
  1784. $this->setPDFVersion();
  1785. $this->pdfproducer = "\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";
  1786. $this->tcpdflink = true;
  1787. $this->encoding = $encoding;
  1788. $this->HREF = array();
  1789. $this->getFontsList();
  1790. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1791. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1792. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1793. $this->extgstates = array();
  1794. $this->setTextShadow();
  1795. // user's rights
  1796. $this->sign = false;
  1797. $this->ur['enabled'] = false;
  1798. $this->ur['document'] = '/FullSave';
  1799. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1800. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1801. $this->ur['signature'] = '/Modify';
  1802. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1803. $this->ur['formex'] = '';
  1804. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1805. $this->empty_signature_appearance = array();
  1806. // set default JPEG quality
  1807. $this->jpeg_quality = 75;
  1808. // initialize some settings
  1809. $this->utf8Bidi(array(''), '');
  1810. // set default font
  1811. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1812. // check if PCRE Unicode support is enabled
  1813. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1814. // PCRE unicode support is turned ON
  1815. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  1816. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  1817. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  1818. //$this->setSpacesRE('/[^\S\P{Z}\P{Lo}\xa0]/u');
  1819. $this->setSpacesRE('/[^\S\P{Z}\xa0]/u');
  1820. } else {
  1821. // PCRE unicode support is turned OFF
  1822. $this->setSpacesRE('/[^\S\xa0]/');
  1823. }
  1824. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1825. // set file ID for trailer
  1826. $serformat = (is_array($format) ? serialize($format) : $format);
  1827. $this->file_id = md5($this->getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
  1828. // set document creation and modification timestamp
  1829. $this->doc_creation_timestamp = time();
  1830. $this->doc_modification_timestamp = $this->doc_creation_timestamp;
  1831. // get default graphic vars
  1832. $this->default_graphic_vars = $this->getGraphicVars();
  1833. $this->header_xobj_autoreset = false;
  1834. $this->custom_xmp = '';
  1835. }
  1836. /**
  1837. * Default destructor.
  1838. * @public
  1839. * @since 1.53.0.TC016
  1840. */
  1841. public function __destruct() {
  1842. // restore internal encoding
  1843. if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
  1844. mb_internal_encoding($this->internal_encoding);
  1845. }
  1846. // unset all class variables
  1847. $this->_destroy(true);
  1848. }
  1849. /**
  1850. * Return the current TCPDF version.
  1851. * @return TCPDF version string
  1852. * @public
  1853. * @since 5.9.012 (2010-11-10)
  1854. */
  1855. public function getTCPDFVersion() {
  1856. return $this->tcpdf_version;
  1857. }
  1858. /**
  1859. * Set the units of measure for the document.
  1860. * @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.
  1861. * @public
  1862. * @since 3.0.015 (2008-06-06)
  1863. */
  1864. public function setPageUnit($unit) {
  1865. $unit = strtolower($unit);
  1866. //Set scale factor
  1867. switch ($unit) {
  1868. // points
  1869. case 'px':
  1870. case 'pt': {
  1871. $this->k = 1;
  1872. break;
  1873. }
  1874. // millimeters
  1875. case 'mm': {
  1876. $this->k = $this->dpi / 25.4;
  1877. break;
  1878. }
  1879. // centimeters
  1880. case 'cm': {
  1881. $this->k = $this->dpi / 2.54;
  1882. break;
  1883. }
  1884. // inches
  1885. case 'in': {
  1886. $this->k = $this->dpi;
  1887. break;
  1888. }
  1889. // unsupported unit
  1890. default : {
  1891. $this->Error('Incorrect unit: '.$unit);
  1892. break;
  1893. }
  1894. }
  1895. $this->pdfunit = $unit;
  1896. if (isset($this->CurOrientation)) {
  1897. $this->setPageOrientation($this->CurOrientation);
  1898. }
  1899. }
  1900. /**
  1901. * Get page dimensions from format name.
  1902. * @param $format (mixed) The format name. It can be: <ul>
  1903. * <li><b>ISO 216 A Series + 2 SIS 014711 extensions</b></li>
  1904. * <li>A0 (841x1189 mm ; 33.11x46.81 in)</li>
  1905. * <li>A1 (594x841 mm ; 23.39x33.11 in)</li>
  1906. * <li>A2 (420x594 mm ; 16.54x23.39 in)</li>
  1907. * <li>A3 (297x420 mm ; 11.69x16.54 in)</li>
  1908. * <li>A4 (210x297 mm ; 8.27x11.69 in)</li>
  1909. * <li>A5 (148x210 mm ; 5.83x8.27 in)</li>
  1910. * <li>A6 (105x148 mm ; 4.13x5.83 in)</li>
  1911. * <li>A7 (74x105 mm ; 2.91x4.13 in)</li>
  1912. * <li>A8 (52x74 mm ; 2.05x2.91 in)</li>
  1913. * <li>A9 (37x52 mm ; 1.46x2.05 in)</li>
  1914. * <li>A10 (26x37 mm ; 1.02x1.46 in)</li>
  1915. * <li>A11 (18x26 mm ; 0.71x1.02 in)</li>
  1916. * <li>A12 (13x18 mm ; 0.51x0.71 in)</li>
  1917. * <li><b>ISO 216 B Series + 2 SIS 014711 extensions</b></li>
  1918. * <li>B0 (1000x1414 mm ; 39.37x55.67 in)</li>
  1919. * <li>B1 (707x1000 mm ; 27.83x39.37 in)</li>
  1920. * <li>B2 (500x707 mm ; 19.69x27.83 in)</li>
  1921. * <li>B3 (353x500 mm ; 13.90x19.69 in)</li>
  1922. * <li>B4 (250x353 mm ; 9.84x13.90 in)</li>
  1923. * <li>B5 (176x250 mm ; 6.93x9.84 in)</li>
  1924. * <li>B6 (125x176 mm ; 4.92x6.93 in)</li>
  1925. * <li>B7 (88x125 mm ; 3.46x4.92 in)</li>
  1926. * <li>B8 (62x88 mm ; 2.44x3.46 in)</li>
  1927. * <li>B9 (44x62 mm ; 1.73x2.44 in)</li>
  1928. * <li>B10 (31x44 mm ; 1.22x1.73 in)</li>
  1929. * <li>B11 (22x31 mm ; 0.87x1.22 in)</li>
  1930. * <li>B12 (15x22 mm ; 0.59x0.87 in)</li>
  1931. * <li><b>ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION</b></li>
  1932. * <li>C0 (917x1297 mm ; 36.10x51.06 in)</li>
  1933. * <li>C1 (648x917 mm ; 25.51x36.10 in)</li>
  1934. * <li>C2 (458x648 mm ; 18.03x25.51 in)</li>
  1935. * <li>C3 (324x458 mm ; 12.76x18.03 in)</li>
  1936. * <li>C4 (229x324 mm ; 9.02x12.76 in)</li>
  1937. * <li>C5 (162x229 mm ; 6.38x9.02 in)</li>
  1938. * <li>C6 (114x162 mm ; 4.49x6.38 in)</li>
  1939. * <li>C7 (81x114 mm ; 3.19x4.49 in)</li>
  1940. * <li>C8 (57x81 mm ; 2.24x3.19 in)</li>
  1941. * <li>C9 (40x57 mm ; 1.57x2.24 in)</li>
  1942. * <li>C10 (28x40 mm ; 1.10x1.57 in)</li>
  1943. * <li>C11 (20x28 mm ; 0.79x1.10 in)</li>
  1944. * <li>C12 (14x20 mm ; 0.55x0.79 in)</li>
  1945. * <li>C76 (81x162 mm ; 3.19x6.38 in)</li>
  1946. * <li>DL (110x220 mm ; 4.33x8.66 in)</li>
  1947. * <li><b>SIS 014711 E Series</b></li>
  1948. * <li>E0 (879x1241 mm ; 34.61x48.86 in)</li>
  1949. * <li>E1 (620x879 mm ; 24.41x34.61 in)</li>
  1950. * <li>E2 (440x620 mm ; 17.32x24.41 in)</li>
  1951. * <li>E3 (310x440 mm ; 12.20x17.32 in)</li>
  1952. * <li>E4 (220x310 mm ; 8.66x12.20 in)</li>
  1953. * <li>E5 (155x220 mm ; 6.10x8.66 in)</li>
  1954. * <li>E6 (110x155 mm ; 4.33x6.10 in)</li>
  1955. * <li>E7 (78x110 mm ; 3.07x4.33 in)</li>
  1956. * <li>E8 (55x78 mm ; 2.17x3.07 in)</li>
  1957. * <li>E9 (39x55 mm ; 1.54x2.17 in)</li>
  1958. * <li>E10 (27x39 mm ; 1.06x1.54 in)</li>
  1959. * <li>E11 (19x27 mm ; 0.75x1.06 in)</li>
  1960. * <li>E12 (13x19 mm ; 0.51x0.75 in)</li>
  1961. * <li><b>SIS 014711 G Series</b></li>
  1962. * <li>G0 (958x1354 mm ; 37.72x53.31 in)</li>
  1963. * <li>G1 (677x958 mm ; 26.65x37.72 in)</li>
  1964. * <li>G2 (479x677 mm ; 18.86x26.65 in)</li>
  1965. * <li>G3 (338x479 mm ; 13.31x18.86 in)</li>
  1966. * <li>G4 (239x338 mm ; 9.41x13.31 in)</li>
  1967. * <li>G5 (169x239 mm ; 6.65x9.41 in)</li>
  1968. * <li>G6 (119x169 mm ; 4.69x6.65 in)</li>
  1969. * <li>G7 (84x119 mm ; 3.31x4.69 in)</li>
  1970. * <li>G8 (59x84 mm ; 2.32x3.31 in)</li>
  1971. * <li>G9 (42x59 mm ; 1.65x2.32 in)</li>
  1972. * <li>G10 (29x42 mm ; 1.14x1.65 in)</li>
  1973. * <li>G11 (21x29 mm ; 0.83x1.14 in)</li>
  1974. * <li>G12 (14x21 mm ; 0.55x0.83 in)</li>
  1975. * <li><b>ISO Press</b></li>
  1976. * <li>RA0 (860x1220 mm ; 33.86x48.03 in)</li>
  1977. * <li>RA1 (610x860 mm ; 24.02x33.86 in)</li>
  1978. * <li>RA2 (430x610 mm ; 16.93x24.02 in)</li>
  1979. * <li>RA3 (305x430 mm ; 12.01x16.93 in)</li>
  1980. * <li>RA4 (215x305 mm ; 8.46x12.01 in)</li>
  1981. * <li>SRA0 (900x1280 mm ; 35.43x50.39 in)</li>
  1982. * <li>SRA1 (640x900 mm ; 25.20x35.43 in)</li>
  1983. * <li>SRA2 (450x640 mm ; 17.72x25.20 in)</li>
  1984. * <li>SRA3 (320x450 mm ; 12.60x17.72 in)</li>
  1985. * <li>SRA4 (225x320 mm ; 8.86x12.60 in)</li>
  1986. * <li><b>German DIN 476</b></li>
  1987. * <li>4A0 (1682x2378 mm ; 66.22x93.62 in)</li>
  1988. * <li>2A0 (1189x1682 mm ; 46.81x66.22 in)</li>
  1989. * <li><b>Variations on the ISO Standard</b></li>
  1990. * <li>A2_EXTRA (445x619 mm ; 17.52x24.37 in)</li>
  1991. * <li>A3+ (329x483 mm ; 12.95x19.02 in)</li>
  1992. * <li>A3_EXTRA (322x445 mm ; 12.68x17.52 in)</li>
  1993. * <li>A3_SUPER (305x508 mm ; 12.01x20.00 in)</li>
  1994. * <li>SUPER_A3 (305x487 mm ; 12.01x19.17 in)</li>
  1995. * <li>A4_EXTRA (235x322 mm ; 9.25x12.68 in)</li>
  1996. * <li>A4_SUPER (229x322 mm ; 9.02x12.68 in)</li>
  1997. * <li>SUPER_A4 (227x356 mm ; 8.94x14.02 in)</li>
  1998. * <li>A4_LONG (210x348 mm ; 8.27x13.70 in)</li>
  1999. * <li>F4 (210x330 mm ; 8.27x12.99 in)</li>
  2000. * <li>SO_B5_EXTRA (202x276 mm ; 7.95x10.87 in)</li>
  2001. * <li>A5_EXTRA (173x235 mm ; 6.81x9.25 in)</li>
  2002. * <li><b>ANSI Series</b></li>
  2003. * <li>ANSI_E (864x1118 mm ; 34.00x44.00 in)</li>
  2004. * <li>ANSI_D (559x864 mm ; 22.00x34.00 in)</li>
  2005. * <li>ANSI_C (432x559 mm ; 17.00x22.00 in)</li>
  2006. * <li>ANSI_B (279x432 mm ; 11.00x17.00 in)</li>
  2007. * <li>ANSI_A (216x279 mm ; 8.50x11.00 in)</li>
  2008. * <li><b>Traditional 'Loose' North American Paper Sizes</b></li>
  2009. * <li>LEDGER, USLEDGER (432x279 mm ; 17.00x11.00 in)</li>
  2010. * <li>TABLOID, USTABLOID, BIBLE, ORGANIZERK (279x432 mm ; 11.00x17.00 in)</li>
  2011. * <li>LETTER, USLETTER, ORGANIZERM (216x279 mm ; 8.50x11.00 in)</li>
  2012. * <li>LEGAL, USLEGAL (216x356 mm ; 8.50x14.00 in)</li>
  2013. * <li>GLETTER, GOVERNMENTLETTER (203x267 mm ; 8.00x10.50 in)</li>
  2014. * <li>JLEGAL, JUNIORLEGAL (203x127 mm ; 8.00x5.00 in)</li>
  2015. * <li><b>Other North American Paper Sizes</b></li>
  2016. * <li>QUADDEMY (889x1143 mm ; 35.00x45.00 in)</li>
  2017. * <li>SUPER_B (330x483 mm ; 13.00x19.00 in)</li>
  2018. * <li>QUARTO (229x279 mm ; 9.00x11.00 in)</li>
  2019. * <li>FOLIO, GOVERNMENTLEGAL (216x330 mm ; 8.50x13.00 in)</li>
  2020. * <li>EXECUTIVE, MONARCH (184x267 mm ; 7.25x10.50 in)</li>
  2021. * <li>MEMO, STATEMENT, ORGANIZERL (140x216 mm ; 5.50x8.50 in)</li>
  2022. * <li>FOOLSCAP (210x330 mm ; 8.27x13.00 in)</li>
  2023. * <li>COMPACT (108x171 mm ; 4.25x6.75 in)</li>
  2024. * <li>ORGANIZERJ (70x127 mm ; 2.75x5.00 in)</li>
  2025. * <li><b>Canadian standard CAN 2-9.60M</b></li>
  2026. * <li>P1 (560x860 mm ; 22.05x33.86 in)</li>
  2027. * <li>P2 (430x560 mm ; 16.93x22.05 in)</li>
  2028. * <li>P3 (280x430 mm ; 11.02x16.93 in)</li>
  2029. * <li>P4 (215x280 mm ; 8.46x11.02 in)</li>
  2030. * <li>P5 (140x215 mm ; 5.51x8.46 in)</li>
  2031. * <li>P6 (107x140 mm ; 4.21x5.51 in)</li>
  2032. * <li><b>North American Architectural Sizes</b></li>
  2033. * <li>ARCH_E (914x1219 mm ; 36.00x48.00 in)</li>
  2034. * <li>ARCH_E1 (762x1067 mm ; 30.00x42.00 in)</li>
  2035. * <li>ARCH_D (610x914 mm ; 24.00x36.00 in)</li>
  2036. * <li>ARCH_C, BROADSHEET (457x610 mm ; 18.00x24.00 in)</li>
  2037. * <li>ARCH_B (305x457 mm ; 12.00x18.00 in)</li>
  2038. * <li>ARCH_A (229x305 mm ; 9.00x12.00 in)</li>
  2039. * <li><b>Announcement Envelopes</b></li>
  2040. * <li>ANNENV_A2 (111x146 mm ; 4.37x5.75 in)</li>
  2041. * <li>ANNENV_A6 (121x165 mm ; 4.75x6.50 in)</li>
  2042. * <li>ANNENV_A7 (133x184 mm ; 5.25x7.25 in)</li>
  2043. * <li>ANNENV_A8 (140x206 mm ; 5.50x8.12 in)</li>
  2044. * <li>ANNENV_A10 (159x244 mm ; 6.25x9.62 in)</li>
  2045. * <li>ANNENV_SLIM (98x225 mm ; 3.87x8.87 in)</li>
  2046. * <li><b>Commercial Envelopes</b></li>
  2047. * <li>COMMENV_N6_1/4 (89x152 mm ; 3.50x6.00 in)</li>
  2048. * <li>COMMENV_N6_3/4 (92x165 mm ; 3.62x6.50 in)</li>
  2049. * <li>COMMENV_N8 (98x191 mm ; 3.87x7.50 in)</li>
  2050. * <li>COMMENV_N9 (98x225 mm ; 3.87x8.87 in)</li>
  2051. * <li>COMMENV_N10 (105x241 mm ; 4.12x9.50 in)</li>
  2052. * <li>COMMENV_N11 (114x263 mm ; 4.50x10.37 in)</li>
  2053. * <li>COMMENV_N12 (121x279 mm ; 4.75x11.00 in)</li>
  2054. * <li>COMMENV_N14 (127x292 mm ; 5.00x11.50 in)</li>
  2055. * <li><b>Catalogue Envelopes</b></li>
  2056. * <li>CATENV_N1 (152x229 mm ; 6.00x9.00 in)</li>
  2057. * <li>CATENV_N1_3/4 (165x241 mm ; 6.50x9.50 in)</li>
  2058. * <li>CATENV_N2 (165x254 mm ; 6.50x10.00 in)</li>
  2059. * <li>CATENV_N3 (178x254 mm ; 7.00x10.00 in)</li>
  2060. * <li>CATENV_N6 (191x267 mm ; 7.50x10.50 in)</li>
  2061. * <li>CATENV_N7 (203x279 mm ; 8.00x11.00 in)</li>
  2062. * <li>CATENV_N8 (210x286 mm ; 8.25x11.25 in)</li>
  2063. * <li>CATENV_N9_1/2 (216x267 mm ; 8.50x10.50 in)</li>
  2064. * <li>CATENV_N9_3/4 (222x286 mm ; 8.75x11.25 in)</li>
  2065. * <li>CATENV_N10_1/2 (229x305 mm ; 9.00x12.00 in)</li>
  2066. * <li>CATENV_N12_1/2 (241x318 mm ; 9.50x12.50 in)</li>
  2067. * <li>CATENV_N13_1/2 (254x330 mm ; 10.00x13.00 in)</li>
  2068. * <li>CATENV_N14_1/4 (286x311 mm ; 11.25x12.25 in)</li>
  2069. * <li>CATENV_N14_1/2 (292x368 mm ; 11.50x14.50 in)</li>
  2070. * <li><b>Japanese (JIS P 0138-61) Standard B-Series</b></li>
  2071. * <li>JIS_B0 (1030x1456 mm ; 40.55x57.32 in)</li>
  2072. * <li>JIS_B1 (728x1030 mm ; 28.66x40.55 in)</li>
  2073. * <li>JIS_B2 (515x728 mm ; 20.28x28.66 in)</li>
  2074. * <li>JIS_B3 (364x515 mm ; 14.33x20.28 in)</li>
  2075. * <li>JIS_B4 (257x364 mm ; 10.12x14.33 in)</li>
  2076. * <li>JIS_B5 (182x257 mm ; 7.17x10.12 in)</li>
  2077. * <li>JIS_B6 (128x182 mm ; 5.04x7.17 in)</li>
  2078. * <li>JIS_B7 (91x128 mm ; 3.58x5.04 in)</li>
  2079. * <li>JIS_B8 (64x91 mm ; 2.52x3.58 in)</li>
  2080. * <li>JIS_B9 (45x64 mm ; 1.77x2.52 in)</li>
  2081. * <li>JIS_B10 (32x45 mm ; 1.26x1.77 in)</li>
  2082. * <li>JIS_B11 (22x32 mm ; 0.87x1.26 in)</li>
  2083. * <li>JIS_B12 (16x22 mm ; 0.63x0.87 in)</li>
  2084. * <li><b>PA Series</b></li>
  2085. * <li>PA0 (840x1120 mm ; 33.07x44.09 in)</li>
  2086. * <li>PA1 (560x840 mm ; 22.05x33.07 in)</li>
  2087. * <li>PA2 (420x560 mm ; 16.54x22.05 in)</li>
  2088. * <li>PA3 (280x420 mm ; 11.02x16.54 in)</li>
  2089. * <li>PA4 (210x280 mm ; 8.27x11.02 in)</li>
  2090. * <li>PA5 (140x210 mm ; 5.51x8.27 in)</li>
  2091. * <li>PA6 (105x140 mm ; 4.13x5.51 in)</li>
  2092. * <li>PA7 (70x105 mm ; 2.76x4.13 in)</li>
  2093. * <li>PA8 (52x70 mm ; 2.05x2.76 in)</li>
  2094. * <li>PA9 (35x52 mm ; 1.38x2.05 in)</li>
  2095. * <li>PA10 (26x35 mm ; 1.02x1.38 in)</li>
  2096. * <li><b>Standard Photographic Print Sizes</b></li>
  2097. * <li>PASSPORT_PHOTO (35x45 mm ; 1.38x1.77 in)</li>
  2098. * <li>E (82x120 mm ; 3.25x4.72 in)</li>
  2099. * <li>3R, L (89x127 mm ; 3.50x5.00 in)</li>
  2100. * <li>4R, KG (102x152 mm ; 4.02x5.98 in)</li>
  2101. * <li>4D (120x152 mm ; 4.72x5.98 in)</li>
  2102. * <li>5R, 2L (127x178 mm ; 5.00x7.01 in)</li>
  2103. * <li>6R, 8P (152x203 mm ; 5.98x7.99 in)</li>
  2104. * <li>8R, 6P (203x254 mm ; 7.99x10.00 in)</li>
  2105. * <li>S8R, 6PW (203x305 mm ; 7.99x12.01 in)</li>
  2106. * <li>10R, 4P (254x305 mm ; 10.00x12.01 in)</li>
  2107. * <li>S10R, 4PW (254x381 mm ; 10.00x15.00 in)</li>
  2108. * <li>11R (279x356 mm ; 10.98x14.02 in)</li>
  2109. * <li>S11R (279x432 mm ; 10.98x17.01 in)</li>
  2110. * <li>12R (305x381 mm ; 12.01x15.00 in)</li>
  2111. * <li>S12R (305x456 mm ; 12.01x17.95 in)</li>
  2112. * <li><b>Common Newspaper Sizes</b></li>
  2113. * <li>NEWSPAPER_BROADSHEET (750x600 mm ; 29.53x23.62 in)</li>
  2114. * <li>NEWSPAPER_BERLINER (470x315 mm ; 18.50x12.40 in)</li>
  2115. * <li>NEWSPAPER_COMPACT, NEWSPAPER_TABLOID (430x280 mm ; 16.93x11.02 in)</li>
  2116. * <li><b>Business Cards</b></li>
  2117. * <li>CREDIT_CARD, BUSINESS_CARD, BUSINESS_CARD_ISO7810 (54x86 mm ; 2.13x3.37 in)</li>
  2118. * <li>BUSINESS_CARD_ISO216 (52x74 mm ; 2.05x2.91 in)</li>
  2119. * <li>BUSINESS_CARD_IT, BUSINESS_CARD_UK, BUSINESS_CARD_FR, BUSINESS_CARD_DE, BUSINESS_CARD_ES (55x85 mm ; 2.17x3.35 in)</li>
  2120. * <li>BUSINESS_CARD_US, BUSINESS_CARD_CA (51x89 mm ; 2.01x3.50 in)</li>
  2121. * <li>BUSINESS_CARD_JP (55x91 mm ; 2.17x3.58 in)</li>
  2122. * <li>BUSINESS_CARD_HK (54x90 mm ; 2.13x3.54 in)</li>
  2123. * <li>BUSINESS_CARD_AU, BUSINESS_CARD_DK, BUSINESS_CARD_SE (55x90 mm ; 2.17x3.54 in)</li>
  2124. * <li>BUSINESS_CARD_RU, BUSINESS_CARD_CZ, BUSINESS_CARD_FI, BUSINESS_CARD_HU, BUSINESS_CARD_IL (50x90 mm ; 1.97x3.54 in)</li>
  2125. * <li><b>Billboards</b></li>
  2126. * <li>4SHEET (1016x1524 mm ; 40.00x60.00 in)</li>
  2127. * <li>6SHEET (1200x1800 mm ; 47.24x70.87 in)</li>
  2128. * <li>12SHEET (3048x1524 mm ; 120.00x60.00 in)</li>
  2129. * <li>16SHEET (2032x3048 mm ; 80.00x120.00 in)</li>
  2130. * <li>32SHEET (4064x3048 mm ; 160.00x120.00 in)</li>
  2131. * <li>48SHEET (6096x3048 mm ; 240.00x120.00 in)</li>
  2132. * <li>64SHEET (8128x3048 mm ; 320.00x120.00 in)</li>
  2133. * <li>96SHEET (12192x3048 mm ; 480.00x120.00 in)</li>
  2134. * <li><b>Old Imperial English (some are still used in USA)</b></li>
  2135. * <li>EN_EMPEROR (1219x1829 mm ; 48.00x72.00 in)</li>
  2136. * <li>EN_ANTIQUARIAN (787x1346 mm ; 31.00x53.00 in)</li>
  2137. * <li>EN_GRAND_EAGLE (730x1067 mm ; 28.75x42.00 in)</li>
  2138. * <li>EN_DOUBLE_ELEPHANT (679x1016 mm ; 26.75x40.00 in)</li>
  2139. * <li>EN_ATLAS (660x864 mm ; 26.00x34.00 in)</li>
  2140. * <li>EN_COLOMBIER (597x876 mm ; 23.50x34.50 in)</li>
  2141. * <li>EN_ELEPHANT (584x711 mm ; 23.00x28.00 in)</li>
  2142. * <li>EN_DOUBLE_DEMY (572x902 mm ; 22.50x35.50 in)</li>
  2143. * <li>EN_IMPERIAL (559x762 mm ; 22.00x30.00 in)</li>
  2144. * <li>EN_PRINCESS (546x711 mm ; 21.50x28.00 in)</li>
  2145. * <li>EN_CARTRIDGE (533x660 mm ; 21.00x26.00 in)</li>
  2146. * <li>EN_DOUBLE_LARGE_POST (533x838 mm ; 21.00x33.00 in)</li>
  2147. * <li>EN_ROYAL (508x635 mm ; 20.00x25.00 in)</li>
  2148. * <li>EN_SHEET, EN_HALF_POST (495x597 mm ; 19.50x23.50 in)</li>
  2149. * <li>EN_SUPER_ROYAL (483x686 mm ; 19.00x27.00 in)</li>
  2150. * <li>EN_DOUBLE_POST (483x775 mm ; 19.00x30.50 in)</li>
  2151. * <li>EN_MEDIUM (445x584 mm ; 17.50x23.00 in)</li>
  2152. * <li>EN_DEMY (445x572 mm ; 17.50x22.50 in)</li>
  2153. * <li>EN_LARGE_POST (419x533 mm ; 16.50x21.00 in)</li>
  2154. * <li>EN_COPY_DRAUGHT (406x508 mm ; 16.00x20.00 in)</li>
  2155. * <li>EN_POST (394x489 mm ; 15.50x19.25 in)</li>
  2156. * <li>EN_CROWN (381x508 mm ; 15.00x20.00 in)</li>
  2157. * <li>EN_PINCHED_POST (375x470 mm ; 14.75x18.50 in)</li>
  2158. * <li>EN_BRIEF (343x406 mm ; 13.50x16.00 in)</li>
  2159. * <li>EN_FOOLSCAP (343x432 mm ; 13.50x17.00 in)</li>
  2160. * <li>EN_SMALL_FOOLSCAP (337x419 mm ; 13.25x16.50 in)</li>
  2161. * <li>EN_POTT (318x381 mm ; 12.50x15.00 in)</li>
  2162. * <li><b>Old Imperial Belgian</b></li>
  2163. * <li>BE_GRAND_AIGLE (700x1040 mm ; 27.56x40.94 in)</li>
  2164. * <li>BE_COLOMBIER (620x850 mm ; 24.41x33.46 in)</li>
  2165. * <li>BE_DOUBLE_CARRE (620x920 mm ; 24.41x36.22 in)</li>
  2166. * <li>BE_ELEPHANT (616x770 mm ; 24.25x30.31 in)</li>
  2167. * <li>BE_PETIT_AIGLE (600x840 mm ; 23.62x33.07 in)</li>
  2168. * <li>BE_GRAND_JESUS (550x730 mm ; 21.65x28.74 in)</li>
  2169. * <li>BE_JESUS (540x730 mm ; 21.26x28.74 in)</li>
  2170. * <li>BE_RAISIN (500x650 mm ; 19.69x25.59 in)</li>
  2171. * <li>BE_GRAND_MEDIAN (460x605 mm ; 18.11x23.82 in)</li>
  2172. * <li>BE_DOUBLE_POSTE (435x565 mm ; 17.13x22.24 in)</li>
  2173. * <li>BE_COQUILLE (430x560 mm ; 16.93x22.05 in)</li>
  2174. * <li>BE_PETIT_MEDIAN (415x530 mm ; 16.34x20.87 in)</li>
  2175. * <li>BE_RUCHE (360x460 mm ; 14.17x18.11 in)</li>
  2176. * <li>BE_PROPATRIA (345x430 mm ; 13.58x16.93 in)</li>
  2177. * <li>BE_LYS (317x397 mm ; 12.48x15.63 in)</li>
  2178. * <li>BE_POT (307x384 mm ; 12.09x15.12 in)</li>
  2179. * <li>BE_ROSETTE (270x347 mm ; 10.63x13.66 in)</li>
  2180. * <li><b>Old Imperial French</b></li>
  2181. * <li>FR_UNIVERS (1000x1300 mm ; 39.37x51.18 in)</li>
  2182. * <li>FR_DOUBLE_COLOMBIER (900x1260 mm ; 35.43x49.61 in)</li>
  2183. * <li>FR_GRANDE_MONDE (900x1260 mm ; 35.43x49.61 in)</li>
  2184. * <li>FR_DOUBLE_SOLEIL (800x1200 mm ; 31.50x47.24 in)</li>
  2185. * <li>FR_DOUBLE_JESUS (760x1120 mm ; 29.92x44.09 in)</li>
  2186. * <li>FR_GRAND_AIGLE (750x1060 mm ; 29.53x41.73 in)</li>
  2187. * <li>FR_PETIT_AIGLE (700x940 mm ; 27.56x37.01 in)</li>
  2188. * <li>FR_DOUBLE_RAISIN (650x1000 mm ; 25.59x39.37 in)</li>
  2189. * <li>FR_JOURNAL (650x940 mm ; 25.59x37.01 in)</li>
  2190. * <li>FR_COLOMBIER_AFFICHE (630x900 mm ; 24.80x35.43 in)</li>
  2191. * <li>FR_DOUBLE_CAVALIER (620x920 mm ; 24.41x36.22 in)</li>
  2192. * <li>FR_CLOCHE (600x800 mm ; 23.62x31.50 in)</li>
  2193. * <li>FR_SOLEIL (600x800 mm ; 23.62x31.50 in)</li>
  2194. * <li>FR_DOUBLE_CARRE (560x900 mm ; 22.05x35.43 in)</li>
  2195. * <li>FR_DOUBLE_COQUILLE (560x880 mm ; 22.05x34.65 in)</li>
  2196. * <li>FR_JESUS (560x760 mm ; 22.05x29.92 in)</li>
  2197. * <li>FR_RAISIN (500x650 mm ; 19.69x25.59 in)</li>
  2198. * <li>FR_CAVALIER (460x620 mm ; 18.11x24.41 in)</li>
  2199. * <li>FR_DOUBLE_COURONNE (460x720 mm ; 18.11x28.35 in)</li>
  2200. * <li>FR_CARRE (450x560 mm ; 17.72x22.05 in)</li>
  2201. * <li>FR_COQUILLE (440x560 mm ; 17.32x22.05 in)</li>
  2202. * <li>FR_DOUBLE_TELLIERE (440x680 mm ; 17.32x26.77 in)</li>
  2203. * <li>FR_DOUBLE_CLOCHE (400x600 mm ; 15.75x23.62 in)</li>
  2204. * <li>FR_DOUBLE_POT (400x620 mm ; 15.75x24.41 in)</li>
  2205. * <li>FR_ECU (400x520 mm ; 15.75x20.47 in)</li>
  2206. * <li>FR_COURONNE (360x460 mm ; 14.17x18.11 in)</li>
  2207. * <li>FR_TELLIERE (340x440 mm ; 13.39x17.32 in)</li>
  2208. * <li>FR_POT (310x400 mm ; 12.20x15.75 in)</li>
  2209. * </ul>
  2210. * @return array containing page width and height in points
  2211. * @public
  2212. * @since 5.0.010 (2010-05-17)
  2213. */
  2214. public function getPageSizeFromFormat($format) {
  2215. // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 25.4 mm)
  2216. switch (strtoupper($format)) {
  2217. // ISO 216 A Series + 2 SIS 014711 extensions
  2218. case 'A0' : {$pf = array( 2383.937, 3370.394); break;}
  2219. case 'A1' : {$pf = array( 1683.780, 2383.937); break;}
  2220. case 'A2' : {$pf = array( 1190.551, 1683.780); break;}
  2221. case 'A3' : {$pf = array( 841.890, 1190.551); break;}
  2222. case 'A4' : {$pf = array( 595.276, 841.890); break;}
  2223. case 'A5' : {$pf = array( 419.528, 595.276); break;}
  2224. case 'A6' : {$pf = array( 297.638, 419.528); break;}
  2225. case 'A7' : {$pf = array( 209.764, 297.638); break;}
  2226. case 'A8' : {$pf = array( 147.402, 209.764); break;}
  2227. case 'A9' : {$pf = array( 104.882, 147.402); break;}
  2228. case 'A10': {$pf = array( 73.701, 104.882); break;}
  2229. case 'A11': {$pf = array( 51.024, 73.701); break;}
  2230. case 'A12': {$pf = array( 36.850, 51.024); break;}
  2231. // ISO 216 B Series + 2 SIS 014711 extensions
  2232. case 'B0' : {$pf = array( 2834.646, 4008.189); break;}
  2233. case 'B1' : {$pf = array( 2004.094, 2834.646); break;}
  2234. case 'B2' : {$pf = array( 1417.323, 2004.094); break;}
  2235. case 'B3' : {$pf = array( 1000.630, 1417.323); break;}
  2236. case 'B4' : {$pf = array( 708.661, 1000.630); break;}
  2237. case 'B5' : {$pf = array( 498.898, 708.661); break;}
  2238. case 'B6' : {$pf = array( 354.331, 498.898); break;}
  2239. case 'B7' : {$pf = array( 249.449, 354.331); break;}
  2240. case 'B8' : {$pf = array( 175.748, 249.449); break;}
  2241. case 'B9' : {$pf = array( 124.724, 175.748); break;}
  2242. case 'B10': {$pf = array( 87.874, 124.724); break;}
  2243. case 'B11': {$pf = array( 62.362, 87.874); break;}
  2244. case 'B12': {$pf = array( 42.520, 62.362); break;}
  2245. // ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION
  2246. case 'C0' : {$pf = array( 2599.370, 3676.535); break;}
  2247. case 'C1' : {$pf = array( 1836.850, 2599.370); break;}
  2248. case 'C2' : {$pf = array( 1298.268, 1836.850); break;}
  2249. case 'C3' : {$pf = array( 918.425, 1298.268); break;}
  2250. case 'C4' : {$pf = array( 649.134, 918.425); break;}
  2251. case 'C5' : {$pf = array( 459.213, 649.134); break;}
  2252. case 'C6' : {$pf = array( 323.150, 459.213); break;}
  2253. case 'C7' : {$pf = array( 229.606, 323.150); break;}
  2254. case 'C8' : {$pf = array( 161.575, 229.606); break;}
  2255. case 'C9' : {$pf = array( 113.386, 161.575); break;}
  2256. case 'C10': {$pf = array( 79.370, 113.386); break;}
  2257. case 'C11': {$pf = array( 56.693, 79.370); break;}
  2258. case 'C12': {$pf = array( 39.685, 56.693); break;}
  2259. case 'C76': {$pf = array( 229.606, 459.213); break;}
  2260. case 'DL' : {$pf = array( 311.811, 623.622); break;}
  2261. // SIS 014711 E Series
  2262. case 'E0' : {$pf = array( 2491.654, 3517.795); break;}
  2263. case 'E1' : {$pf = array( 1757.480, 2491.654); break;}
  2264. case 'E2' : {$pf = array( 1247.244, 1757.480); break;}
  2265. case 'E3' : {$pf = array( 878.740, 1247.244); break;}
  2266. case 'E4' : {$pf = array( 623.622, 878.740); break;}
  2267. case 'E5' : {$pf = array( 439.370, 623.622); break;}
  2268. case 'E6' : {$pf = array( 311.811, 439.370); break;}
  2269. case 'E7' : {$pf = array( 221.102, 311.811); break;}
  2270. case 'E8' : {$pf = array( 155.906, 221.102); break;}
  2271. case 'E9' : {$pf = array( 110.551, 155.906); break;}
  2272. case 'E10': {$pf = array( 76.535, 110.551); break;}
  2273. case 'E11': {$pf = array( 53.858, 76.535); break;}
  2274. case 'E12': {$pf = array( 36.850, 53.858); break;}
  2275. // SIS 014711 G Series
  2276. case 'G0' : {$pf = array( 2715.591, 3838.110); break;}
  2277. case 'G1' : {$pf = array( 1919.055, 2715.591); break;}
  2278. case 'G2' : {$pf = array( 1357.795, 1919.055); break;}
  2279. case 'G3' : {$pf = array( 958.110, 1357.795); break;}
  2280. case 'G4' : {$pf = array( 677.480, 958.110); break;}
  2281. case 'G5' : {$pf = array( 479.055, 677.480); break;}
  2282. case 'G6' : {$pf = array( 337.323, 479.055); break;}
  2283. case 'G7' : {$pf = array( 238.110, 337.323); break;}
  2284. case 'G8' : {$pf = array( 167.244, 238.110); break;}
  2285. case 'G9' : {$pf = array( 119.055, 167.244); break;}
  2286. case 'G10': {$pf = array( 82.205, 119.055); break;}
  2287. case 'G11': {$pf = array( 59.528, 82.205); break;}
  2288. case 'G12': {$pf = array( 39.685, 59.528); break;}
  2289. // ISO Press
  2290. case 'RA0': {$pf = array( 2437.795, 3458.268); break;}
  2291. case 'RA1': {$pf = array( 1729.134, 2437.795); break;}
  2292. case 'RA2': {$pf = array( 1218.898, 1729.134); break;}
  2293. case 'RA3': {$pf = array( 864.567, 1218.898); break;}
  2294. case 'RA4': {$pf = array( 609.449, 864.567); break;}
  2295. case 'SRA0': {$pf = array( 2551.181, 3628.346); break;}
  2296. case 'SRA1': {$pf = array( 1814.173, 2551.181); break;}
  2297. case 'SRA2': {$pf = array( 1275.591, 1814.173); break;}
  2298. case 'SRA3': {$pf = array( 907.087, 1275.591); break;}
  2299. case 'SRA4': {$pf = array( 637.795, 907.087); break;}
  2300. // German DIN 476
  2301. case '4A0': {$pf = array( 4767.874, 6740.787); break;}
  2302. case '2A0': {$pf = array( 3370.394, 4767.874); break;}
  2303. // Variations on the ISO Standard
  2304. case 'A2_EXTRA' : {$pf = array( 1261.417, 1754.646); break;}
  2305. case 'A3+' : {$pf = array( 932.598, 1369.134); break;}
  2306. case 'A3_EXTRA' : {$pf = array( 912.756, 1261.417); break;}
  2307. case 'A3_SUPER' : {$pf = array( 864.567, 1440.000); break;}
  2308. case 'SUPER_A3' : {$pf = array( 864.567, 1380.472); break;}
  2309. case 'A4_EXTRA' : {$pf = array( 666.142, 912.756); break;}
  2310. case 'A4_SUPER' : {$pf = array( 649.134, 912.756); break;}
  2311. case 'SUPER_A4' : {$pf = array( 643.465, 1009.134); break;}
  2312. case 'A4_LONG' : {$pf = array( 595.276, 986.457); break;}
  2313. case 'F4' : {$pf = array( 595.276, 935.433); break;}
  2314. case 'SO_B5_EXTRA': {$pf = array( 572.598, 782.362); break;}
  2315. case 'A5_EXTRA' : {$pf = array( 490.394, 666.142); break;}
  2316. // ANSI Series
  2317. case 'ANSI_E': {$pf = array( 2448.000, 3168.000); break;}
  2318. case 'ANSI_D': {$pf = array( 1584.000, 2448.000); break;}
  2319. case 'ANSI_C': {$pf = array( 1224.000, 1584.000); break;}
  2320. case 'ANSI_B': {$pf = array( 792.000, 1224.000); break;}
  2321. case 'ANSI_A': {$pf = array( 612.000, 792.000); break;}
  2322. // Traditional 'Loose' North American Paper Sizes
  2323. case 'USLEDGER':
  2324. case 'LEDGER' : {$pf = array( 1224.000, 792.000); break;}
  2325. case 'ORGANIZERK':
  2326. case 'BIBLE':
  2327. case 'USTABLOID':
  2328. case 'TABLOID': {$pf = array( 792.000, 1224.000); break;}
  2329. case 'ORGANIZERM':
  2330. case 'USLETTER':
  2331. case 'LETTER' : {$pf = array( 612.000, 792.000); break;}
  2332. case 'USLEGAL':
  2333. case 'LEGAL' : {$pf = array( 612.000, 1008.000); break;}
  2334. case 'GOVERNMENTLETTER':
  2335. case 'GLETTER': {$pf = array( 576.000, 756.000); break;}
  2336. case 'JUNIORLEGAL':
  2337. case 'JLEGAL' : {$pf = array( 576.000, 360.000); break;}
  2338. // Other North American Paper Sizes
  2339. case 'QUADDEMY': {$pf = array( 2520.000, 3240.000); break;}
  2340. case 'SUPER_B': {$pf = array( 936.000, 1368.000); break;}
  2341. case 'QUARTO': {$pf = array( 648.000, 792.000); break;}
  2342. case 'GOVERNMENTLEGAL':
  2343. case 'FOLIO': {$pf = array( 612.000, 936.000); break;}
  2344. case 'MONARCH':
  2345. case 'EXECUTIVE': {$pf = array( 522.000, 756.000); break;}
  2346. case 'ORGANIZERL':
  2347. case 'STATEMENT':
  2348. case 'MEMO': {$pf = array( 396.000, 612.000); break;}
  2349. case 'FOOLSCAP': {$pf = array( 595.440, 936.000); break;}
  2350. case 'COMPACT': {$pf = array( 306.000, 486.000); break;}
  2351. case 'ORGANIZERJ': {$pf = array( 198.000, 360.000); break;}
  2352. // Canadian standard CAN 2-9.60M
  2353. case 'P1': {$pf = array( 1587.402, 2437.795); break;}
  2354. case 'P2': {$pf = array( 1218.898, 1587.402); break;}
  2355. case 'P3': {$pf = array( 793.701, 1218.898); break;}
  2356. case 'P4': {$pf = array( 609.449, 793.701); break;}
  2357. case 'P5': {$pf = array( 396.850, 609.449); break;}
  2358. case 'P6': {$pf = array( 303.307, 396.850); break;}
  2359. // North American Architectural Sizes
  2360. case 'ARCH_E' : {$pf = array( 2592.000, 3456.000); break;}
  2361. case 'ARCH_E1': {$pf = array( 2160.000, 3024.000); break;}
  2362. case 'ARCH_D' : {$pf = array( 1728.000, 2592.000); break;}
  2363. case 'BROADSHEET':
  2364. case 'ARCH_C' : {$pf = array( 1296.000, 1728.000); break;}
  2365. case 'ARCH_B' : {$pf = array( 864.000, 1296.000); break;}
  2366. case 'ARCH_A' : {$pf = array( 648.000, 864.000); break;}
  2367. // --- North American Envelope Sizes ---
  2368. // - Announcement Envelopes
  2369. case 'ANNENV_A2' : {$pf = array( 314.640, 414.000); break;}
  2370. case 'ANNENV_A6' : {$pf = array( 342.000, 468.000); break;}
  2371. case 'ANNENV_A7' : {$pf = array( 378.000, 522.000); break;}
  2372. case 'ANNENV_A8' : {$pf = array( 396.000, 584.640); break;}
  2373. case 'ANNENV_A10' : {$pf = array( 450.000, 692.640); break;}
  2374. case 'ANNENV_SLIM': {$pf = array( 278.640, 638.640); break;}
  2375. // - Commercial Envelopes
  2376. case 'COMMENV_N6_1/4': {$pf = array( 252.000, 432.000); break;}
  2377. case 'COMMENV_N6_3/4': {$pf = array( 260.640, 468.000); break;}
  2378. case 'COMMENV_N8' : {$pf = array( 278.640, 540.000); break;}
  2379. case 'COMMENV_N9' : {$pf = array( 278.640, 638.640); break;}
  2380. case 'COMMENV_N10' : {$pf = array( 296.640, 684.000); break;}
  2381. case 'COMMENV_N11' : {$pf = array( 324.000, 746.640); break;}
  2382. case 'COMMENV_N12' : {$pf = array( 342.000, 792.000); break;}
  2383. case 'COMMENV_N14' : {$pf = array( 360.000, 828.000); break;}
  2384. // - Catalogue Envelopes
  2385. case 'CATENV_N1' : {$pf = array( 432.000, 648.000); break;}
  2386. case 'CATENV_N1_3/4' : {$pf = array( 468.000, 684.000); break;}
  2387. case 'CATENV_N2' : {$pf = array( 468.000, 720.000); break;}
  2388. case 'CATENV_N3' : {$pf = array( 504.000, 720.000); break;}
  2389. case 'CATENV_N6' : {$pf = array( 540.000, 756.000); break;}
  2390. case 'CATENV_N7' : {$pf = array( 576.000, 792.000); break;}
  2391. case 'CATENV_N8' : {$pf = array( 594.000, 810.000); break;}
  2392. case 'CATENV_N9_1/2' : {$pf = array( 612.000, 756.000); break;}
  2393. case 'CATENV_N9_3/4' : {$pf = array( 630.000, 810.000); break;}
  2394. case 'CATENV_N10_1/2': {$pf = array( 648.000, 864.000); break;}
  2395. case 'CATENV_N12_1/2': {$pf = array( 684.000, 900.000); break;}
  2396. case 'CATENV_N13_1/2': {$pf = array( 720.000, 936.000); break;}
  2397. case 'CATENV_N14_1/4': {$pf = array( 810.000, 882.000); break;}
  2398. case 'CATENV_N14_1/2': {$pf = array( 828.000, 1044.000); break;}
  2399. // Japanese (JIS P 0138-61) Standard B-Series
  2400. case 'JIS_B0' : {$pf = array( 2919.685, 4127.244); break;}
  2401. case 'JIS_B1' : {$pf = array( 2063.622, 2919.685); break;}
  2402. case 'JIS_B2' : {$pf = array( 1459.843, 2063.622); break;}
  2403. case 'JIS_B3' : {$pf = array( 1031.811, 1459.843); break;}
  2404. case 'JIS_B4' : {$pf = array( 728.504, 1031.811); break;}
  2405. case 'JIS_B5' : {$pf = array( 515.906, 728.504); break;}
  2406. case 'JIS_B6' : {$pf = array( 362.835, 515.906); break;}
  2407. case 'JIS_B7' : {$pf = array( 257.953, 362.835); break;}
  2408. case 'JIS_B8' : {$pf = array( 181.417, 257.953); break;}
  2409. case 'JIS_B9' : {$pf = array( 127.559, 181.417); break;}
  2410. case 'JIS_B10': {$pf = array( 90.709, 127.559); break;}
  2411. case 'JIS_B11': {$pf = array( 62.362, 90.709); break;}
  2412. case 'JIS_B12': {$pf = array( 45.354, 62.362); break;}
  2413. // PA Series
  2414. case 'PA0' : {$pf = array( 2381.102, 3174.803,); break;}
  2415. case 'PA1' : {$pf = array( 1587.402, 2381.102); break;}
  2416. case 'PA2' : {$pf = array( 1190.551, 1587.402); break;}
  2417. case 'PA3' : {$pf = array( 793.701, 1190.551); break;}
  2418. case 'PA4' : {$pf = array( 595.276, 793.701); break;}
  2419. case 'PA5' : {$pf = array( 396.850, 595.276); break;}
  2420. case 'PA6' : {$pf = array( 297.638, 396.850); break;}
  2421. case 'PA7' : {$pf = array( 198.425, 297.638); break;}
  2422. case 'PA8' : {$pf = array( 147.402, 198.425); break;}
  2423. case 'PA9' : {$pf = array( 99.213, 147.402); break;}
  2424. case 'PA10': {$pf = array( 73.701, 99.213); break;}
  2425. // Standard Photographic Print Sizes
  2426. case 'PASSPORT_PHOTO': {$pf = array( 99.213, 127.559); break;}
  2427. case 'E' : {$pf = array( 233.858, 340.157); break;}
  2428. case 'L':
  2429. case '3R' : {$pf = array( 252.283, 360.000); break;}
  2430. case 'KG':
  2431. case '4R' : {$pf = array( 289.134, 430.866); break;}
  2432. case '4D' : {$pf = array( 340.157, 430.866); break;}
  2433. case '2L':
  2434. case '5R' : {$pf = array( 360.000, 504.567); break;}
  2435. case '8P':
  2436. case '6R' : {$pf = array( 430.866, 575.433); break;}
  2437. case '6P':
  2438. case '8R' : {$pf = array( 575.433, 720.000); break;}
  2439. case '6PW':
  2440. case 'S8R' : {$pf = array( 575.433, 864.567); break;}
  2441. case '4P':
  2442. case '10R' : {$pf = array( 720.000, 864.567); break;}
  2443. case '4PW':
  2444. case 'S10R': {$pf = array( 720.000, 1080.000); break;}
  2445. case '11R' : {$pf = array( 790.866, 1009.134); break;}
  2446. case 'S11R': {$pf = array( 790.866, 1224.567); break;}
  2447. case '12R' : {$pf = array( 864.567, 1080.000); break;}
  2448. case 'S12R': {$pf = array( 864.567, 1292.598); break;}
  2449. // Common Newspaper Sizes
  2450. case 'NEWSPAPER_BROADSHEET': {$pf = array( 2125.984, 1700.787); break;}
  2451. case 'NEWSPAPER_BERLINER' : {$pf = array( 1332.283, 892.913); break;}
  2452. case 'NEWSPAPER_TABLOID':
  2453. case 'NEWSPAPER_COMPACT' : {$pf = array( 1218.898, 793.701); break;}
  2454. // Business Cards
  2455. case 'CREDIT_CARD':
  2456. case 'BUSINESS_CARD':
  2457. case 'BUSINESS_CARD_ISO7810': {$pf = array( 153.014, 242.646); break;}
  2458. case 'BUSINESS_CARD_ISO216' : {$pf = array( 147.402, 209.764); break;}
  2459. case 'BUSINESS_CARD_IT':
  2460. case 'BUSINESS_CARD_UK':
  2461. case 'BUSINESS_CARD_FR':
  2462. case 'BUSINESS_CARD_DE':
  2463. case 'BUSINESS_CARD_ES' : {$pf = array( 155.906, 240.945); break;}
  2464. case 'BUSINESS_CARD_CA':
  2465. case 'BUSINESS_CARD_US' : {$pf = array( 144.567, 252.283); break;}
  2466. case 'BUSINESS_CARD_JP' : {$pf = array( 155.906, 257.953); break;}
  2467. case 'BUSINESS_CARD_HK' : {$pf = array( 153.071, 255.118); break;}
  2468. case 'BUSINESS_CARD_AU':
  2469. case 'BUSINESS_CARD_DK':
  2470. case 'BUSINESS_CARD_SE' : {$pf = array( 155.906, 255.118); break;}
  2471. case 'BUSINESS_CARD_RU':
  2472. case 'BUSINESS_CARD_CZ':
  2473. case 'BUSINESS_CARD_FI':
  2474. case 'BUSINESS_CARD_HU':
  2475. case 'BUSINESS_CARD_IL' : {$pf = array( 141.732, 255.118); break;}
  2476. // Billboards
  2477. case '4SHEET' : {$pf = array( 2880.000, 4320.000); break;}
  2478. case '6SHEET' : {$pf = array( 3401.575, 5102.362); break;}
  2479. case '12SHEET': {$pf = array( 8640.000, 4320.000); break;}
  2480. case '16SHEET': {$pf = array( 5760.000, 8640.000); break;}
  2481. case '32SHEET': {$pf = array(11520.000, 8640.000); break;}
  2482. case '48SHEET': {$pf = array(17280.000, 8640.000); break;}
  2483. case '64SHEET': {$pf = array(23040.000, 8640.000); break;}
  2484. case '96SHEET': {$pf = array(34560.000, 8640.000); break;}
  2485. // Old European Sizes
  2486. // - Old Imperial English Sizes
  2487. case 'EN_EMPEROR' : {$pf = array( 3456.000, 5184.000); break;}
  2488. case 'EN_ANTIQUARIAN' : {$pf = array( 2232.000, 3816.000); break;}
  2489. case 'EN_GRAND_EAGLE' : {$pf = array( 2070.000, 3024.000); break;}
  2490. case 'EN_DOUBLE_ELEPHANT' : {$pf = array( 1926.000, 2880.000); break;}
  2491. case 'EN_ATLAS' : {$pf = array( 1872.000, 2448.000); break;}
  2492. case 'EN_COLOMBIER' : {$pf = array( 1692.000, 2484.000); break;}
  2493. case 'EN_ELEPHANT' : {$pf = array( 1656.000, 2016.000); break;}
  2494. case 'EN_DOUBLE_DEMY' : {$pf = array( 1620.000, 2556.000); break;}
  2495. case 'EN_IMPERIAL' : {$pf = array( 1584.000, 2160.000); break;}
  2496. case 'EN_PRINCESS' : {$pf = array( 1548.000, 2016.000); break;}
  2497. case 'EN_CARTRIDGE' : {$pf = array( 1512.000, 1872.000); break;}
  2498. case 'EN_DOUBLE_LARGE_POST': {$pf = array( 1512.000, 2376.000); break;}
  2499. case 'EN_ROYAL' : {$pf = array( 1440.000, 1800.000); break;}
  2500. case 'EN_SHEET':
  2501. case 'EN_HALF_POST' : {$pf = array( 1404.000, 1692.000); break;}
  2502. case 'EN_SUPER_ROYAL' : {$pf = array( 1368.000, 1944.000); break;}
  2503. case 'EN_DOUBLE_POST' : {$pf = array( 1368.000, 2196.000); break;}
  2504. case 'EN_MEDIUM' : {$pf = array( 1260.000, 1656.000); break;}
  2505. case 'EN_DEMY' : {$pf = array( 1260.000, 1620.000); break;}
  2506. case 'EN_LARGE_POST' : {$pf = array( 1188.000, 1512.000); break;}
  2507. case 'EN_COPY_DRAUGHT' : {$pf = array( 1152.000, 1440.000); break;}
  2508. case 'EN_POST' : {$pf = array( 1116.000, 1386.000); break;}
  2509. case 'EN_CROWN' : {$pf = array( 1080.000, 1440.000); break;}
  2510. case 'EN_PINCHED_POST' : {$pf = array( 1062.000, 1332.000); break;}
  2511. case 'EN_BRIEF' : {$pf = array( 972.000, 1152.000); break;}
  2512. case 'EN_FOOLSCAP' : {$pf = array( 972.000, 1224.000); break;}
  2513. case 'EN_SMALL_FOOLSCAP' : {$pf = array( 954.000, 1188.000); break;}
  2514. case 'EN_POTT' : {$pf = array( 900.000, 1080.000); break;}
  2515. // - Old Imperial Belgian Sizes
  2516. case 'BE_GRAND_AIGLE' : {$pf = array( 1984.252, 2948.031); break;}
  2517. case 'BE_COLOMBIER' : {$pf = array( 1757.480, 2409.449); break;}
  2518. case 'BE_DOUBLE_CARRE': {$pf = array( 1757.480, 2607.874); break;}
  2519. case 'BE_ELEPHANT' : {$pf = array( 1746.142, 2182.677); break;}
  2520. case 'BE_PETIT_AIGLE' : {$pf = array( 1700.787, 2381.102); break;}
  2521. case 'BE_GRAND_JESUS' : {$pf = array( 1559.055, 2069.291); break;}
  2522. case 'BE_JESUS' : {$pf = array( 1530.709, 2069.291); break;}
  2523. case 'BE_RAISIN' : {$pf = array( 1417.323, 1842.520); break;}
  2524. case 'BE_GRAND_MEDIAN': {$pf = array( 1303.937, 1714.961); break;}
  2525. case 'BE_DOUBLE_POSTE': {$pf = array( 1233.071, 1601.575); break;}
  2526. case 'BE_COQUILLE' : {$pf = array( 1218.898, 1587.402); break;}
  2527. case 'BE_PETIT_MEDIAN': {$pf = array( 1176.378, 1502.362); break;}
  2528. case 'BE_RUCHE' : {$pf = array( 1020.472, 1303.937); break;}
  2529. case 'BE_PROPATRIA' : {$pf = array( 977.953, 1218.898); break;}
  2530. case 'BE_LYS' : {$pf = array( 898.583, 1125.354); break;}
  2531. case 'BE_POT' : {$pf = array( 870.236, 1088.504); break;}
  2532. case 'BE_ROSETTE' : {$pf = array( 765.354, 983.622); break;}
  2533. // - Old Imperial French Sizes
  2534. case 'FR_UNIVERS' : {$pf = array( 2834.646, 3685.039); break;}
  2535. case 'FR_DOUBLE_COLOMBIER' : {$pf = array( 2551.181, 3571.654); break;}
  2536. case 'FR_GRANDE_MONDE' : {$pf = array( 2551.181, 3571.654); break;}
  2537. case 'FR_DOUBLE_SOLEIL' : {$pf = array( 2267.717, 3401.575); break;}
  2538. case 'FR_DOUBLE_JESUS' : {$pf = array( 2154.331, 3174.803); break;}
  2539. case 'FR_GRAND_AIGLE' : {$pf = array( 2125.984, 3004.724); break;}
  2540. case 'FR_PETIT_AIGLE' : {$pf = array( 1984.252, 2664.567); break;}
  2541. case 'FR_DOUBLE_RAISIN' : {$pf = array( 1842.520, 2834.646); break;}
  2542. case 'FR_JOURNAL' : {$pf = array( 1842.520, 2664.567); break;}
  2543. case 'FR_COLOMBIER_AFFICHE': {$pf = array( 1785.827, 2551.181); break;}
  2544. case 'FR_DOUBLE_CAVALIER' : {$pf = array( 1757.480, 2607.874); break;}
  2545. case 'FR_CLOCHE' : {$pf = array( 1700.787, 2267.717); break;}
  2546. case 'FR_SOLEIL' : {$pf = array( 1700.787, 2267.717); break;}
  2547. case 'FR_DOUBLE_CARRE' : {$pf = array( 1587.402, 2551.181); break;}
  2548. case 'FR_DOUBLE_COQUILLE' : {$pf = array( 1587.402, 2494.488); break;}
  2549. case 'FR_JESUS' : {$pf = array( 1587.402, 2154.331); break;}
  2550. case 'FR_RAISIN' : {$pf = array( 1417.323, 1842.520); break;}
  2551. case 'FR_CAVALIER' : {$pf = array( 1303.937, 1757.480); break;}
  2552. case 'FR_DOUBLE_COURONNE' : {$pf = array( 1303.937, 2040.945); break;}
  2553. case 'FR_CARRE' : {$pf = array( 1275.591, 1587.402); break;}
  2554. case 'FR_COQUILLE' : {$pf = array( 1247.244, 1587.402); break;}
  2555. case 'FR_DOUBLE_TELLIERE' : {$pf = array( 1247.244, 1927.559); break;}
  2556. case 'FR_DOUBLE_CLOCHE' : {$pf = array( 1133.858, 1700.787); break;}
  2557. case 'FR_DOUBLE_POT' : {$pf = array( 1133.858, 1757.480); break;}
  2558. case 'FR_ECU' : {$pf = array( 1133.858, 1474.016); break;}
  2559. case 'FR_COURONNE' : {$pf = array( 1020.472, 1303.937); break;}
  2560. case 'FR_TELLIERE' : {$pf = array( 963.780, 1247.244); break;}
  2561. case 'FR_POT' : {$pf = array( 878.740, 1133.858); break;}
  2562. // DEFAULT ISO A4
  2563. default: {$pf = array( 595.276, 841.890); break;}
  2564. }
  2565. return $pf;
  2566. }
  2567. /**
  2568. * Change the format of the current page
  2569. * @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>
  2570. * <li>['format'] = page format name (one of the above);</li>
  2571. * <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>
  2572. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  2573. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  2574. * <li>['MediaBox']['llx'] : lower-left x coordinate in points</li>
  2575. * <li>['MediaBox']['lly'] : lower-left y coordinate in points</li>
  2576. * <li>['MediaBox']['urx'] : upper-right x coordinate in points</li>
  2577. * <li>['MediaBox']['ury'] : upper-right y coordinate in points</li>
  2578. * <li>['CropBox'] : the visible region of default user space:</li>
  2579. * <li>['CropBox']['llx'] : lower-left x coordinate in points</li>
  2580. * <li>['CropBox']['lly'] : lower-left y coordinate in points</li>
  2581. * <li>['CropBox']['urx'] : upper-right x coordinate in points</li>
  2582. * <li>['CropBox']['ury'] : upper-right y coordinate in points</li>
  2583. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  2584. * <li>['BleedBox']['llx'] : lower-left x coordinate in points</li>
  2585. * <li>['BleedBox']['lly'] : lower-left y coordinate in points</li>
  2586. * <li>['BleedBox']['urx'] : upper-right x coordinate in points</li>
  2587. * <li>['BleedBox']['ury'] : upper-right y coordinate in points</li>
  2588. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  2589. * <li>['TrimBox']['llx'] : lower-left x coordinate in points</li>
  2590. * <li>['TrimBox']['lly'] : lower-left y coordinate in points</li>
  2591. * <li>['TrimBox']['urx'] : upper-right x coordinate in points</li>
  2592. * <li>['TrimBox']['ury'] : upper-right y coordinate in points</li>
  2593. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  2594. * <li>['ArtBox']['llx'] : lower-left x coordinate in points</li>
  2595. * <li>['ArtBox']['lly'] : lower-left y coordinate in points</li>
  2596. * <li>['ArtBox']['urx'] : upper-right x coordinate in points</li>
  2597. * <li>['ArtBox']['ury'] : upper-right y coordinate in points</li>
  2598. * <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>
  2599. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  2600. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  2601. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  2602. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  2603. * <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>
  2604. * <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>
  2605. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  2606. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  2607. * <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>
  2608. * <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>
  2609. * <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>
  2610. * <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>
  2611. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  2612. * </ul>
  2613. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  2614. * <li>P or Portrait (default)</li>
  2615. * <li>L or Landscape</li>
  2616. * <li>'' (empty string) for automatic orientation</li>
  2617. * </ul>
  2618. * @protected
  2619. * @since 3.0.015 (2008-06-06)
  2620. * @see getPageSizeFromFormat()
  2621. */
  2622. protected function setPageFormat($format, $orientation='P') {
  2623. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  2624. // remove inherited values
  2625. unset($this->pagedim[$this->page]);
  2626. }
  2627. if (is_string($format)) {
  2628. // get page measures from format name
  2629. $pf = $this->getPageSizeFromFormat($format);
  2630. $this->fwPt = $pf[0];
  2631. $this->fhPt = $pf[1];
  2632. } else {
  2633. // the boundaries of the physical medium on which the page shall be displayed or printed
  2634. if (isset($format['MediaBox'])) {
  2635. $this->setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false);
  2636. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  2637. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  2638. } else {
  2639. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  2640. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  2641. } else {
  2642. if (!isset($format['format'])) {
  2643. // default value
  2644. $format['format'] = 'A4';
  2645. }
  2646. $pf = $this->getPageSizeFromFormat($format['format']);
  2647. }
  2648. $this->fwPt = $pf[0];
  2649. $this->fhPt = $pf[1];
  2650. $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true);
  2651. }
  2652. // the visible region of default user space
  2653. if (isset($format['CropBox'])) {
  2654. $this->setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false);
  2655. }
  2656. // the region to which the contents of the page shall be clipped when output in a production environment
  2657. if (isset($format['BleedBox'])) {
  2658. $this->setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false);
  2659. }
  2660. // the intended dimensions of the finished page after trimming
  2661. if (isset($format['TrimBox'])) {
  2662. $this->setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false);
  2663. }
  2664. // the page's meaningful content (including potential white space)
  2665. if (isset($format['ArtBox'])) {
  2666. $this->setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false);
  2667. }
  2668. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  2669. if (isset($format['BoxColorInfo'])) {
  2670. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  2671. }
  2672. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  2673. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2674. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  2675. }
  2676. if (isset($format['PZ'])) {
  2677. // The page's preferred zoom (magnification) factor
  2678. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  2679. }
  2680. if (isset($format['trans'])) {
  2681. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  2682. if (isset($format['trans']['Dur'])) {
  2683. // The page's display duration
  2684. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  2685. }
  2686. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  2687. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  2688. // The transition style that shall be used when moving to this page from another during a presentation
  2689. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  2690. $valid_effect = array('Split', 'Blinds');
  2691. $valid_vals = array('H', 'V');
  2692. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  2693. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  2694. }
  2695. $valid_effect = array('Split', 'Box', 'Fly');
  2696. $valid_vals = array('I', 'O');
  2697. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  2698. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  2699. }
  2700. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  2701. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  2702. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  2703. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  2704. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  2705. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  2706. }
  2707. }
  2708. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  2709. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  2710. }
  2711. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  2712. $this->pagedim[$this->page]['trans']['B'] = 'true';
  2713. }
  2714. } else {
  2715. $this->pagedim[$this->page]['trans']['S'] = 'R';
  2716. }
  2717. if (isset($format['trans']['D'])) {
  2718. // The duration of the transition effect, in seconds
  2719. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  2720. } else {
  2721. $this->pagedim[$this->page]['trans']['D'] = 1;
  2722. }
  2723. }
  2724. }
  2725. $this->setPageOrientation($orientation);
  2726. }
  2727. /**
  2728. * Set page boundaries.
  2729. * @param $page (int) page number
  2730. * @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>
  2731. * @param $llx (float) lower-left x coordinate in user units
  2732. * @param $lly (float) lower-left y coordinate in user units
  2733. * @param $urx (float) upper-right x coordinate in user units
  2734. * @param $ury (float) upper-right y coordinate in user units
  2735. * @param $points (boolean) if true uses user units as unit of measure, otherwise uses PDF points
  2736. * @public
  2737. * @since 5.0.010 (2010-05-17)
  2738. */
  2739. public function setPageBoxes($page, $type, $llx, $lly, $urx, $ury, $points=false) {
  2740. if (!isset($this->pagedim[$page])) {
  2741. // initialize array
  2742. $this->pagedim[$page] = array();
  2743. }
  2744. $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  2745. if (!in_array($type, $pageboxes)) {
  2746. return;
  2747. }
  2748. if ($points) {
  2749. $k = 1;
  2750. } else {
  2751. $k = $this->k;
  2752. }
  2753. $this->pagedim[$page][$type]['llx'] = ($llx * $k);
  2754. $this->pagedim[$page][$type]['lly'] = ($lly * $k);
  2755. $this->pagedim[$page][$type]['urx'] = ($urx * $k);
  2756. $this->pagedim[$page][$type]['ury'] = ($ury * $k);
  2757. }
  2758. /**
  2759. * Swap X and Y coordinates of page boxes (change page boxes orientation).
  2760. * @param $page (int) page number
  2761. * @protected
  2762. * @since 5.0.010 (2010-05-17)
  2763. */
  2764. protected function swapPageBoxCoordinates($page) {
  2765. $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  2766. foreach ($pageboxes as $type) {
  2767. // swap X and Y coordinates
  2768. if (isset($this->pagedim[$page][$type])) {
  2769. $tmp = $this->pagedim[$page][$type]['llx'];
  2770. $this->pagedim[$page][$type]['llx'] = $this->pagedim[$page][$type]['lly'];
  2771. $this->pagedim[$page][$type]['lly'] = $tmp;
  2772. $tmp = $this->pagedim[$page][$type]['urx'];
  2773. $this->pagedim[$page][$type]['urx'] = $this->pagedim[$page][$type]['ury'];
  2774. $this->pagedim[$page][$type]['ury'] = $tmp;
  2775. }
  2776. }
  2777. }
  2778. /**
  2779. * Set page orientation.
  2780. * @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>
  2781. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  2782. * @param $bottommargin (float) bottom margin of the page.
  2783. * @public
  2784. * @since 3.0.015 (2008-06-06)
  2785. */
  2786. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  2787. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  2788. // the boundaries of the physical medium on which the page shall be displayed or printed
  2789. $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true);
  2790. }
  2791. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  2792. // the visible region of default user space
  2793. $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);
  2794. }
  2795. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  2796. // the region to which the contents of the page shall be clipped when output in a production environment
  2797. $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);
  2798. }
  2799. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  2800. // the intended dimensions of the finished page after trimming
  2801. $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);
  2802. }
  2803. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  2804. // the page's meaningful content (including potential white space)
  2805. $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);
  2806. }
  2807. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  2808. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2809. $this->pagedim[$this->page]['Rotate'] = 0;
  2810. }
  2811. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2812. // The page's preferred zoom (magnification) factor
  2813. $this->pagedim[$this->page]['PZ'] = 1;
  2814. }
  2815. if ($this->fwPt > $this->fhPt) {
  2816. // landscape
  2817. $default_orientation = 'L';
  2818. } else {
  2819. // portrait
  2820. $default_orientation = 'P';
  2821. }
  2822. $valid_orientations = array('P', 'L');
  2823. if (empty($orientation)) {
  2824. $orientation = $default_orientation;
  2825. } else {
  2826. $orientation = strtoupper($orientation{0});
  2827. }
  2828. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2829. $this->CurOrientation = $orientation;
  2830. $this->wPt = $this->fhPt;
  2831. $this->hPt = $this->fwPt;
  2832. } else {
  2833. $this->CurOrientation = $default_orientation;
  2834. $this->wPt = $this->fwPt;
  2835. $this->hPt = $this->fhPt;
  2836. }
  2837. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2838. // swap X and Y coordinates (change page orientation)
  2839. $this->swapPageBoxCoordinates($this->page);
  2840. }
  2841. $this->w = ($this->wPt / $this->k);
  2842. $this->h = ($this->hPt / $this->k);
  2843. if ($this->empty_string($autopagebreak)) {
  2844. if (isset($this->AutoPageBreak)) {
  2845. $autopagebreak = $this->AutoPageBreak;
  2846. } else {
  2847. $autopagebreak = true;
  2848. }
  2849. }
  2850. if ($this->empty_string($bottommargin)) {
  2851. if (isset($this->bMargin)) {
  2852. $bottommargin = $this->bMargin;
  2853. } else {
  2854. // default value = 2 cm
  2855. $bottommargin = 2 * 28.35 / $this->k;
  2856. }
  2857. }
  2858. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2859. // store page dimensions
  2860. $this->pagedim[$this->page]['w'] = $this->wPt;
  2861. $this->pagedim[$this->page]['h'] = $this->hPt;
  2862. $this->pagedim[$this->page]['wk'] = $this->w;
  2863. $this->pagedim[$this->page]['hk'] = $this->h;
  2864. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2865. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2866. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2867. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2868. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2869. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2870. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2871. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2872. }
  2873. /**
  2874. * Set regular expression to detect withespaces or word separators.
  2875. * The pattern delimiter must be the forward-slash character "/".
  2876. * Some example patterns are:
  2877. * <pre>
  2878. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2879. * Unicode and PCRE unicode support: "/[^\S\P{Z}\xa0]/u"
  2880. * Unicode and PCRE unicode support in Chinese mode: "/[^\S\P{Z}\P{Lo}\xa0]/u"
  2881. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2882. * "\p{Z}" or "\p{Separator}": any kind of Unicode whitespace or invisible separator.
  2883. * "\p{Lo}" or "\p{Other_Letter}": a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  2884. * "\p{Lo}" is needed for Chinese characters because are packed next to each other without spaces in between.
  2885. * </pre>
  2886. * @param $re (string) regular expression (leave empty for default).
  2887. * @public
  2888. * @since 4.6.016 (2009-06-15)
  2889. */
  2890. public function setSpacesRE($re='/[^\S\xa0]/') {
  2891. $this->re_spaces = $re;
  2892. $re_parts = explode('/', $re);
  2893. // get pattern parts
  2894. $this->re_space = array();
  2895. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2896. $this->re_space['p'] = $re_parts[1];
  2897. } else {
  2898. $this->re_space['p'] = '[\s]';
  2899. }
  2900. // set pattern modifiers
  2901. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2902. $this->re_space['m'] = $re_parts[2];
  2903. } else {
  2904. $this->re_space['m'] = '';
  2905. }
  2906. }
  2907. /**
  2908. * Enable or disable Right-To-Left language mode
  2909. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2910. * @param $resetx (Boolean) if true reset the X position on direction change.
  2911. * @public
  2912. * @since 2.0.000 (2008-01-03)
  2913. */
  2914. public function setRTL($enable, $resetx=true) {
  2915. $enable = $enable ? true : false;
  2916. $resetx = ($resetx AND ($enable != $this->rtl));
  2917. $this->rtl = $enable;
  2918. $this->tmprtl = false;
  2919. if ($resetx) {
  2920. $this->Ln(0);
  2921. }
  2922. }
  2923. /**
  2924. * Return the RTL status
  2925. * @return boolean
  2926. * @public
  2927. * @since 4.0.012 (2008-07-24)
  2928. */
  2929. public function getRTL() {
  2930. return $this->rtl;
  2931. }
  2932. /**
  2933. * Force temporary RTL language direction
  2934. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2935. * @public
  2936. * @since 2.1.000 (2008-01-09)
  2937. */
  2938. public function setTempRTL($mode) {
  2939. $newmode = false;
  2940. switch (strtoupper($mode)) {
  2941. case 'LTR':
  2942. case 'L': {
  2943. if ($this->rtl) {
  2944. $newmode = 'L';
  2945. }
  2946. break;
  2947. }
  2948. case 'RTL':
  2949. case 'R': {
  2950. if (!$this->rtl) {
  2951. $newmode = 'R';
  2952. }
  2953. break;
  2954. }
  2955. case false:
  2956. default: {
  2957. $newmode = false;
  2958. break;
  2959. }
  2960. }
  2961. $this->tmprtl = $newmode;
  2962. }
  2963. /**
  2964. * Return the current temporary RTL status
  2965. * @return boolean
  2966. * @public
  2967. * @since 4.8.014 (2009-11-04)
  2968. */
  2969. public function isRTLTextDir() {
  2970. return ($this->rtl OR ($this->tmprtl == 'R'));
  2971. }
  2972. /**
  2973. * Set the last cell height.
  2974. * @param $h (float) cell height.
  2975. * @author Nicola Asuni
  2976. * @public
  2977. * @since 1.53.0.TC034
  2978. */
  2979. public function setLastH($h) {
  2980. $this->lasth = $h;
  2981. }
  2982. /**
  2983. * Reset the last cell height.
  2984. * @public
  2985. * @since 5.9.000 (2010-10-03)
  2986. */
  2987. public function resetLastH() {
  2988. $this->lasth = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  2989. }
  2990. /**
  2991. * Get the last cell height.
  2992. * @return last cell height
  2993. * @public
  2994. * @since 4.0.017 (2008-08-05)
  2995. */
  2996. public function getLastH() {
  2997. return $this->lasth;
  2998. }
  2999. /**
  3000. * Set the adjusting factor to convert pixels to user units.
  3001. * @param $scale (float) adjusting factor to convert pixels to user units.
  3002. * @author Nicola Asuni
  3003. * @public
  3004. * @since 1.5.2
  3005. */
  3006. public function setImageScale($scale) {
  3007. $this->imgscale = $scale;
  3008. }
  3009. /**
  3010. * Returns the adjusting factor to convert pixels to user units.
  3011. * @return float adjusting factor to convert pixels to user units.
  3012. * @author Nicola Asuni
  3013. * @public
  3014. * @since 1.5.2
  3015. */
  3016. public function getImageScale() {
  3017. return $this->imgscale;
  3018. }
  3019. /**
  3020. * Returns an array of page dimensions:
  3021. * <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>
  3022. * @param $pagenum (int) page number (empty = current page)
  3023. * @return array of page dimensions.
  3024. * @author Nicola Asuni
  3025. * @public
  3026. * @since 4.5.027 (2009-03-16)
  3027. */
  3028. public function getPageDimensions($pagenum='') {
  3029. if (empty($pagenum)) {
  3030. $pagenum = $this->page;
  3031. }
  3032. return $this->pagedim[$pagenum];
  3033. }
  3034. /**
  3035. * Returns the page width in units.
  3036. * @param $pagenum (int) page number (empty = current page)
  3037. * @return int page width.
  3038. * @author Nicola Asuni
  3039. * @public
  3040. * @since 1.5.2
  3041. * @see getPageDimensions()
  3042. */
  3043. public function getPageWidth($pagenum='') {
  3044. if (empty($pagenum)) {
  3045. return $this->w;
  3046. }
  3047. return $this->pagedim[$pagenum]['w'];
  3048. }
  3049. /**
  3050. * Returns the page height in units.
  3051. * @param $pagenum (int) page number (empty = current page)
  3052. * @return int page height.
  3053. * @author Nicola Asuni
  3054. * @public
  3055. * @since 1.5.2
  3056. * @see getPageDimensions()
  3057. */
  3058. public function getPageHeight($pagenum='') {
  3059. if (empty($pagenum)) {
  3060. return $this->h;
  3061. }
  3062. return $this->pagedim[$pagenum]['h'];
  3063. }
  3064. /**
  3065. * Returns the page break margin.
  3066. * @param $pagenum (int) page number (empty = current page)
  3067. * @return int page break margin.
  3068. * @author Nicola Asuni
  3069. * @public
  3070. * @since 1.5.2
  3071. * @see getPageDimensions()
  3072. */
  3073. public function getBreakMargin($pagenum='') {
  3074. if (empty($pagenum)) {
  3075. return $this->bMargin;
  3076. }
  3077. return $this->pagedim[$pagenum]['bm'];
  3078. }
  3079. /**
  3080. * Returns the scale factor (number of points in user unit).
  3081. * @return int scale factor.
  3082. * @author Nicola Asuni
  3083. * @public
  3084. * @since 1.5.2
  3085. */
  3086. public function getScaleFactor() {
  3087. return $this->k;
  3088. }
  3089. /**
  3090. * Defines the left, top and right margins.
  3091. * @param $left (float) Left margin.
  3092. * @param $top (float) Top margin.
  3093. * @param $right (float) Right margin. Default value is the left one.
  3094. * @param $keepmargins (boolean) if true overwrites the default page margins
  3095. * @public
  3096. * @since 1.0
  3097. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  3098. */
  3099. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  3100. //Set left, top and right margins
  3101. $this->lMargin = $left;
  3102. $this->tMargin = $top;
  3103. if ($right == -1) {
  3104. $right = $left;
  3105. }
  3106. $this->rMargin = $right;
  3107. if ($keepmargins) {
  3108. // overwrite original values
  3109. $this->original_lMargin = $this->lMargin;
  3110. $this->original_rMargin = $this->rMargin;
  3111. }
  3112. }
  3113. /**
  3114. * 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.
  3115. * @param $margin (float) The margin.
  3116. * @public
  3117. * @since 1.4
  3118. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  3119. */
  3120. public function SetLeftMargin($margin) {
  3121. //Set left margin
  3122. $this->lMargin = $margin;
  3123. if (($this->page > 0) AND ($this->x < $margin)) {
  3124. $this->x = $margin;
  3125. }
  3126. }
  3127. /**
  3128. * Defines the top margin. The method can be called before creating the first page.
  3129. * @param $margin (float) The margin.
  3130. * @public
  3131. * @since 1.5
  3132. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  3133. */
  3134. public function SetTopMargin($margin) {
  3135. //Set top margin
  3136. $this->tMargin = $margin;
  3137. if (($this->page > 0) AND ($this->y < $margin)) {
  3138. $this->y = $margin;
  3139. }
  3140. }
  3141. /**
  3142. * Defines the right margin. The method can be called before creating the first page.
  3143. * @param $margin (float) The margin.
  3144. * @public
  3145. * @since 1.5
  3146. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  3147. */
  3148. public function SetRightMargin($margin) {
  3149. $this->rMargin = $margin;
  3150. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  3151. $this->x = $this->w - $margin;
  3152. }
  3153. }
  3154. /**
  3155. * Set the same internal Cell padding for top, right, bottom, left-
  3156. * @param $pad (float) internal padding.
  3157. * @public
  3158. * @since 2.1.000 (2008-01-09)
  3159. * @see getCellPaddings(), setCellPaddings()
  3160. */
  3161. public function SetCellPadding($pad) {
  3162. if ($pad >= 0) {
  3163. $this->cell_padding['L'] = $pad;
  3164. $this->cell_padding['T'] = $pad;
  3165. $this->cell_padding['R'] = $pad;
  3166. $this->cell_padding['B'] = $pad;
  3167. }
  3168. }
  3169. /**
  3170. * Set the internal Cell paddings.
  3171. * @param $left (float) left padding
  3172. * @param $top (float) top padding
  3173. * @param $right (float) right padding
  3174. * @param $bottom (float) bottom padding
  3175. * @public
  3176. * @since 5.9.000 (2010-10-03)
  3177. * @see getCellPaddings(), SetCellPadding()
  3178. */
  3179. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  3180. if (($left !== '') AND ($left >= 0)) {
  3181. $this->cell_padding['L'] = $left;
  3182. }
  3183. if (($top !== '') AND ($top >= 0)) {
  3184. $this->cell_padding['T'] = $top;
  3185. }
  3186. if (($right !== '') AND ($right >= 0)) {
  3187. $this->cell_padding['R'] = $right;
  3188. }
  3189. if (($bottom !== '') AND ($bottom >= 0)) {
  3190. $this->cell_padding['B'] = $bottom;
  3191. }
  3192. }
  3193. /**
  3194. * Get the internal Cell padding array.
  3195. * @return array of padding values
  3196. * @public
  3197. * @since 5.9.000 (2010-10-03)
  3198. * @see setCellPaddings(), SetCellPadding()
  3199. */
  3200. public function getCellPaddings() {
  3201. return $this->cell_padding;
  3202. }
  3203. /**
  3204. * Set the internal Cell margins.
  3205. * @param $left (float) left margin
  3206. * @param $top (float) top margin
  3207. * @param $right (float) right margin
  3208. * @param $bottom (float) bottom margin
  3209. * @public
  3210. * @since 5.9.000 (2010-10-03)
  3211. * @see getCellMargins()
  3212. */
  3213. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  3214. if (($left !== '') AND ($left >= 0)) {
  3215. $this->cell_margin['L'] = $left;
  3216. }
  3217. if (($top !== '') AND ($top >= 0)) {
  3218. $this->cell_margin['T'] = $top;
  3219. }
  3220. if (($right !== '') AND ($right >= 0)) {
  3221. $this->cell_margin['R'] = $right;
  3222. }
  3223. if (($bottom !== '') AND ($bottom >= 0)) {
  3224. $this->cell_margin['B'] = $bottom;
  3225. }
  3226. }
  3227. /**
  3228. * Get the internal Cell margin array.
  3229. * @return array of margin values
  3230. * @public
  3231. * @since 5.9.000 (2010-10-03)
  3232. * @see setCellMargins()
  3233. */
  3234. public function getCellMargins() {
  3235. return $this->cell_margin;
  3236. }
  3237. /**
  3238. * Adjust the internal Cell padding array to take account of the line width.
  3239. * @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)))
  3240. * @return array of adjustments
  3241. * @public
  3242. * @since 5.9.000 (2010-10-03)
  3243. */
  3244. protected function adjustCellPadding($brd=0) {
  3245. if (empty($brd)) {
  3246. return;
  3247. }
  3248. if (is_string($brd)) {
  3249. // convert string to array
  3250. $slen = strlen($brd);
  3251. $newbrd = array();
  3252. for ($i = 0; $i < $slen; ++$i) {
  3253. $newbrd[$brd[$i]] = true;
  3254. }
  3255. $brd = $newbrd;
  3256. } elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
  3257. $brd = array('LRTB' => true);
  3258. }
  3259. if (!is_array($brd)) {
  3260. return;
  3261. }
  3262. // store current cell padding
  3263. $cp = $this->cell_padding;
  3264. // select border mode
  3265. if (isset($brd['mode'])) {
  3266. $mode = $brd['mode'];
  3267. unset($brd['mode']);
  3268. } else {
  3269. $mode = 'normal';
  3270. }
  3271. // process borders
  3272. foreach ($brd as $border => $style) {
  3273. $line_width = $this->LineWidth;
  3274. if (is_array($style) AND isset($style['width'])) {
  3275. // get border width
  3276. $line_width = $style['width'];
  3277. }
  3278. $adj = 0; // line width inside the cell
  3279. switch ($mode) {
  3280. case 'ext': {
  3281. $adj = 0;
  3282. break;
  3283. }
  3284. case 'int': {
  3285. $adj = $line_width;
  3286. break;
  3287. }
  3288. case 'normal':
  3289. default: {
  3290. $adj = ($line_width / 2);
  3291. break;
  3292. }
  3293. }
  3294. // correct internal cell padding if required to avoid overlap between text and lines
  3295. if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
  3296. $this->cell_padding['T'] = $adj;
  3297. }
  3298. if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
  3299. $this->cell_padding['R'] = $adj;
  3300. }
  3301. if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
  3302. $this->cell_padding['B'] = $adj;
  3303. }
  3304. if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
  3305. $this->cell_padding['L'] = $adj;
  3306. }
  3307. }
  3308. 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']));
  3309. }
  3310. /**
  3311. * 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.
  3312. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  3313. * @param $margin (float) Distance from the bottom of the page.
  3314. * @public
  3315. * @since 1.0
  3316. * @see Cell(), MultiCell(), AcceptPageBreak()
  3317. */
  3318. public function SetAutoPageBreak($auto, $margin=0) {
  3319. $this->AutoPageBreak = $auto ? true : false;
  3320. $this->bMargin = $margin;
  3321. $this->PageBreakTrigger = $this->h - $margin;
  3322. }
  3323. /**
  3324. * Return the auto-page-break mode (true or false).
  3325. * @return boolean auto-page-break mode
  3326. * @public
  3327. * @since 5.9.088
  3328. */
  3329. public function getAutoPageBreak() {
  3330. return $this->AutoPageBreak;
  3331. }
  3332. /**
  3333. * Defines the way the document is to be displayed by the viewer.
  3334. * @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>
  3335. * @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>
  3336. * @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>
  3337. * @public
  3338. * @since 1.2
  3339. */
  3340. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  3341. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  3342. $this->ZoomMode = $zoom;
  3343. } else {
  3344. $this->Error('Incorrect zoom display mode: '.$zoom);
  3345. }
  3346. switch ($layout) {
  3347. case 'default':
  3348. case 'single':
  3349. case 'SinglePage': {
  3350. $this->LayoutMode = 'SinglePage';
  3351. break;
  3352. }
  3353. case 'continuous':
  3354. case 'OneColumn': {
  3355. $this->LayoutMode = 'OneColumn';
  3356. break;
  3357. }
  3358. case 'two':
  3359. case 'TwoColumnLeft': {
  3360. $this->LayoutMode = 'TwoColumnLeft';
  3361. break;
  3362. }
  3363. case 'TwoColumnRight': {
  3364. $this->LayoutMode = 'TwoColumnRight';
  3365. break;
  3366. }
  3367. case 'TwoPageLeft': {
  3368. $this->LayoutMode = 'TwoPageLeft';
  3369. break;
  3370. }
  3371. case 'TwoPageRight': {
  3372. $this->LayoutMode = 'TwoPageRight';
  3373. break;
  3374. }
  3375. default: {
  3376. $this->LayoutMode = 'SinglePage';
  3377. }
  3378. }
  3379. switch ($mode) {
  3380. case 'UseNone': {
  3381. $this->PageMode = 'UseNone';
  3382. break;
  3383. }
  3384. case 'UseOutlines': {
  3385. $this->PageMode = 'UseOutlines';
  3386. break;
  3387. }
  3388. case 'UseThumbs': {
  3389. $this->PageMode = 'UseThumbs';
  3390. break;
  3391. }
  3392. case 'FullScreen': {
  3393. $this->PageMode = 'FullScreen';
  3394. break;
  3395. }
  3396. case 'UseOC': {
  3397. $this->PageMode = 'UseOC';
  3398. break;
  3399. }
  3400. case '': {
  3401. $this->PageMode = 'UseAttachments';
  3402. break;
  3403. }
  3404. default: {
  3405. $this->PageMode = 'UseNone';
  3406. }
  3407. }
  3408. }
  3409. /**
  3410. * 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.
  3411. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  3412. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  3413. * @public
  3414. * @since 1.4
  3415. */
  3416. public function SetCompression($compress=true) {
  3417. if (function_exists('gzcompress')) {
  3418. $this->compress = $compress ? true : false;
  3419. } else {
  3420. $this->compress = false;
  3421. }
  3422. }
  3423. /**
  3424. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  3425. * @param $mode (boolean) If true force sRGB output intent.
  3426. * @public
  3427. * @since 5.9.121 (2011-09-28)
  3428. */
  3429. public function setSRGBmode($mode=false) {
  3430. $this->force_srgb = $mode ? true : false;
  3431. }
  3432. /**
  3433. * Turn on/off Unicode mode for document information dictionary (meta tags).
  3434. * This has effect only when unicode mode is set to false.
  3435. * @param $unicode (boolean) if true set the meta information in Unicode
  3436. * @since 5.9.027 (2010-12-01)
  3437. * @public
  3438. */
  3439. public function SetDocInfoUnicode($unicode=true) {
  3440. $this->docinfounicode = $unicode ? true : false;
  3441. }
  3442. /**
  3443. * Defines the title of the document.
  3444. * @param $title (string) The title.
  3445. * @public
  3446. * @since 1.2
  3447. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  3448. */
  3449. public function SetTitle($title) {
  3450. $this->title = $title;
  3451. }
  3452. /**
  3453. * Defines the subject of the document.
  3454. * @param $subject (string) The subject.
  3455. * @public
  3456. * @since 1.2
  3457. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  3458. */
  3459. public function SetSubject($subject) {
  3460. $this->subject = $subject;
  3461. }
  3462. /**
  3463. * Defines the author of the document.
  3464. * @param $author (string) The name of the author.
  3465. * @public
  3466. * @since 1.2
  3467. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  3468. */
  3469. public function SetAuthor($author) {
  3470. $this->author = $author;
  3471. }
  3472. /**
  3473. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  3474. * @param $keywords (string) The list of keywords.
  3475. * @public
  3476. * @since 1.2
  3477. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  3478. */
  3479. public function SetKeywords($keywords) {
  3480. $this->keywords = $keywords;
  3481. }
  3482. /**
  3483. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  3484. * @param $creator (string) The name of the creator.
  3485. * @public
  3486. * @since 1.2
  3487. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  3488. */
  3489. public function SetCreator($creator) {
  3490. $this->creator = $creator;
  3491. }
  3492. /**
  3493. * 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.
  3494. * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
  3495. * @param $msg (string) The error message
  3496. * @public
  3497. * @since 1.0
  3498. */
  3499. public function Error($msg) {
  3500. // unset all class variables
  3501. $this->_destroy(true);
  3502. // exit program and print error
  3503. die('<strong>TCPDF ERROR: </strong>'.$msg);
  3504. }
  3505. /**
  3506. * This method begins the generation of the PDF document.
  3507. * It is not necessary to call it explicitly because AddPage() does it automatically.
  3508. * Note: no page is created by this method
  3509. * @public
  3510. * @since 1.0
  3511. * @see AddPage(), Close()
  3512. */
  3513. public function Open() {
  3514. $this->state = 1;
  3515. }
  3516. /**
  3517. * Terminates the PDF document.
  3518. * It is not necessary to call this method explicitly because Output() does it automatically.
  3519. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  3520. * @public
  3521. * @since 1.0
  3522. * @see Open(), Output()
  3523. */
  3524. public function Close() {
  3525. if ($this->state == 3) {
  3526. return;
  3527. }
  3528. if ($this->page == 0) {
  3529. $this->AddPage();
  3530. }
  3531. $this->endLayer();
  3532. if ($this->tcpdflink) {
  3533. // save current graphic settings
  3534. $gvars = $this->getGraphicVars();
  3535. $this->setEqualColumns();
  3536. $this->lastpage(true);
  3537. $this->SetAutoPageBreak(false);
  3538. $this->x = 0;
  3539. $this->y = $this->h - (1 / $this->k);
  3540. $this->lMargin = 0;
  3541. $this->_out('q');
  3542. $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  3543. $this->SetFont($font, '', 1);
  3544. $this->setTextRenderingMode(0, false, false);
  3545. $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";
  3546. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  3547. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  3548. $this->_out('Q');
  3549. // restore graphic settings
  3550. $this->setGraphicVars($gvars);
  3551. }
  3552. // close page
  3553. $this->endPage();
  3554. // close document
  3555. $this->_enddoc();
  3556. // unset all class variables (except critical ones)
  3557. $this->_destroy(false);
  3558. }
  3559. /**
  3560. * Move pointer at the specified document page and update page dimensions.
  3561. * @param $pnum (int) page number (1 ... numpages)
  3562. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  3563. * @public
  3564. * @since 2.1.000 (2008-01-07)
  3565. * @see getPage(), lastpage(), getNumPages()
  3566. */
  3567. public function setPage($pnum, $resetmargins=false) {
  3568. if (($pnum == $this->page) AND ($this->state == 2)) {
  3569. return;
  3570. }
  3571. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  3572. $this->state = 2;
  3573. // save current graphic settings
  3574. //$gvars = $this->getGraphicVars();
  3575. $oldpage = $this->page;
  3576. $this->page = $pnum;
  3577. $this->wPt = $this->pagedim[$this->page]['w'];
  3578. $this->hPt = $this->pagedim[$this->page]['h'];
  3579. $this->w = $this->pagedim[$this->page]['wk'];
  3580. $this->h = $this->pagedim[$this->page]['hk'];
  3581. $this->tMargin = $this->pagedim[$this->page]['tm'];
  3582. $this->bMargin = $this->pagedim[$this->page]['bm'];
  3583. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  3584. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  3585. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  3586. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  3587. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  3588. // restore graphic settings
  3589. //$this->setGraphicVars($gvars);
  3590. if ($resetmargins) {
  3591. $this->lMargin = $this->pagedim[$this->page]['olm'];
  3592. $this->rMargin = $this->pagedim[$this->page]['orm'];
  3593. $this->SetY($this->tMargin);
  3594. } else {
  3595. // account for booklet mode
  3596. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  3597. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  3598. $this->lMargin += $deltam;
  3599. $this->rMargin -= $deltam;
  3600. }
  3601. }
  3602. } else {
  3603. $this->Error('Wrong page number on setPage() function: '.$pnum);
  3604. }
  3605. }
  3606. /**
  3607. * Reset pointer to the last document page.
  3608. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  3609. * @public
  3610. * @since 2.0.000 (2008-01-04)
  3611. * @see setPage(), getPage(), getNumPages()
  3612. */
  3613. public function lastPage($resetmargins=false) {
  3614. $this->setPage($this->getNumPages(), $resetmargins);
  3615. }
  3616. /**
  3617. * Get current document page number.
  3618. * @return int page number
  3619. * @public
  3620. * @since 2.1.000 (2008-01-07)
  3621. * @see setPage(), lastpage(), getNumPages()
  3622. */
  3623. public function getPage() {
  3624. return $this->page;
  3625. }
  3626. /**
  3627. * Get the total number of insered pages.
  3628. * @return int number of pages
  3629. * @public
  3630. * @since 2.1.000 (2008-01-07)
  3631. * @see setPage(), getPage(), lastpage()
  3632. */
  3633. public function getNumPages() {
  3634. return $this->numpages;
  3635. }
  3636. /**
  3637. * Adds a new TOC (Table Of Content) page to the document.
  3638. * @param $orientation (string) page orientation.
  3639. * @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().
  3640. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  3641. * @public
  3642. * @since 5.0.001 (2010-05-06)
  3643. * @see AddPage(), startPage(), endPage(), endTOCPage()
  3644. */
  3645. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  3646. $this->AddPage($orientation, $format, $keepmargins, true);
  3647. }
  3648. /**
  3649. * Terminate the current TOC (Table Of Content) page
  3650. * @public
  3651. * @since 5.0.001 (2010-05-06)
  3652. * @see AddPage(), startPage(), endPage(), addTOCPage()
  3653. */
  3654. public function endTOCPage() {
  3655. $this->endPage(true);
  3656. }
  3657. /**
  3658. * 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).
  3659. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  3660. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  3661. * @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().
  3662. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  3663. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  3664. * @public
  3665. * @since 1.0
  3666. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  3667. */
  3668. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  3669. if ($this->inxobj) {
  3670. // we are inside an XObject template
  3671. return;
  3672. }
  3673. if (!isset($this->original_lMargin) OR $keepmargins) {
  3674. $this->original_lMargin = $this->lMargin;
  3675. }
  3676. if (!isset($this->original_rMargin) OR $keepmargins) {
  3677. $this->original_rMargin = $this->rMargin;
  3678. }
  3679. // terminate previous page
  3680. $this->endPage();
  3681. // start new page
  3682. $this->startPage($orientation, $format, $tocpage);
  3683. }
  3684. /**
  3685. * Terminate the current page
  3686. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  3687. * @public
  3688. * @since 4.2.010 (2008-11-14)
  3689. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  3690. */
  3691. public function endPage($tocpage=false) {
  3692. // check if page is already closed
  3693. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  3694. return;
  3695. }
  3696. // print page footer
  3697. $this->setFooter();
  3698. // close page
  3699. $this->_endpage();
  3700. // mark page as closed
  3701. $this->pageopen[$this->page] = false;
  3702. if ($tocpage) {
  3703. $this->tocpage = false;
  3704. }
  3705. }
  3706. /**
  3707. * Starts a new page to the document. The page must be closed using the endPage() function.
  3708. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  3709. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  3710. * @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().
  3711. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  3712. * @since 4.2.010 (2008-11-14)
  3713. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  3714. * @public
  3715. */
  3716. public function startPage($orientation='', $format='', $tocpage=false) {
  3717. if ($tocpage) {
  3718. $this->tocpage = true;
  3719. }
  3720. // move page numbers of documents to be attached
  3721. if ($this->tocpage) {
  3722. // move reference to unexistent pages (used for page attachments)
  3723. // adjust outlines
  3724. $tmpoutlines = $this->outlines;
  3725. foreach ($tmpoutlines as $key => $outline) {
  3726. if ($outline['p'] > $this->numpages) {
  3727. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  3728. }
  3729. }
  3730. // adjust dests
  3731. $tmpdests = $this->dests;
  3732. foreach ($tmpdests as $key => $dest) {
  3733. if ($dest['p'] > $this->numpages) {
  3734. $this->dests[$key]['p'] = ($dest['p'] + 1);
  3735. }
  3736. }
  3737. // adjust links
  3738. $tmplinks = $this->links;
  3739. foreach ($tmplinks as $key => $link) {
  3740. if ($link[0] > $this->numpages) {
  3741. $this->links[$key][0] = ($link[0] + 1);
  3742. }
  3743. }
  3744. }
  3745. if ($this->numpages > $this->page) {
  3746. // this page has been already added
  3747. $this->setPage($this->page + 1);
  3748. $this->SetY($this->tMargin);
  3749. return;
  3750. }
  3751. // start a new page
  3752. if ($this->state == 0) {
  3753. $this->Open();
  3754. }
  3755. ++$this->numpages;
  3756. $this->swapMargins($this->booklet);
  3757. // save current graphic settings
  3758. $gvars = $this->getGraphicVars();
  3759. // start new page
  3760. $this->_beginpage($orientation, $format);
  3761. // mark page as open
  3762. $this->pageopen[$this->page] = true;
  3763. // restore graphic settings
  3764. $this->setGraphicVars($gvars);
  3765. // mark this point
  3766. $this->setPageMark();
  3767. // print page header
  3768. $this->setHeader();
  3769. // restore graphic settings
  3770. $this->setGraphicVars($gvars);
  3771. // mark this point
  3772. $this->setPageMark();
  3773. // print table header (if any)
  3774. $this->setTableHeader();
  3775. // set mark for empty page check
  3776. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  3777. }
  3778. /**
  3779. * Set start-writing mark on current page stream used to put borders and fills.
  3780. * Borders and fills are always created after content and inserted on the position marked by this method.
  3781. * This function must be called after calling Image() function for a background image.
  3782. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  3783. * @public
  3784. * @since 4.0.016 (2008-07-30)
  3785. */
  3786. public function setPageMark() {
  3787. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  3788. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  3789. $this->setContentMark();
  3790. }
  3791. /**
  3792. * Set start-writing mark on selected page.
  3793. * Borders and fills are always created after content and inserted on the position marked by this method.
  3794. * @param $page (int) page number (default is the current page)
  3795. * @protected
  3796. * @since 4.6.021 (2009-07-20)
  3797. */
  3798. protected function setContentMark($page=0) {
  3799. if ($page <= 0) {
  3800. $page = $this->page;
  3801. }
  3802. if (isset($this->footerlen[$page])) {
  3803. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  3804. } else {
  3805. $this->cntmrk[$page] = $this->pagelen[$page];
  3806. }
  3807. }
  3808. /**
  3809. * Set header data.
  3810. * @param $ln (string) header image logo
  3811. * @param $lw (string) header image logo width in mm
  3812. * @param $ht (string) string to print as title on document header
  3813. * @param $hs (string) string to print on document header
  3814. * @param $tc (array) RGB array color for text.
  3815. * @param $lc (array) RGB array color for line.
  3816. * @public
  3817. */
  3818. public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
  3819. $this->header_logo = $ln;
  3820. $this->header_logo_width = $lw;
  3821. $this->header_title = $ht;
  3822. $this->header_string = $hs;
  3823. $this->header_text_color = $tc;
  3824. $this->header_line_color = $lc;
  3825. }
  3826. /**
  3827. * Set footer data.
  3828. * @param $tc (array) RGB array color for text.
  3829. * @param $lc (array) RGB array color for line.
  3830. * @public
  3831. */
  3832. public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
  3833. $this->footer_text_color = $tc;
  3834. $this->footer_line_color = $lc;
  3835. }
  3836. /**
  3837. * Returns header data:
  3838. * <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>
  3839. * @return array()
  3840. * @public
  3841. * @since 4.0.012 (2008-07-24)
  3842. */
  3843. public function getHeaderData() {
  3844. $ret = array();
  3845. $ret['logo'] = $this->header_logo;
  3846. $ret['logo_width'] = $this->header_logo_width;
  3847. $ret['title'] = $this->header_title;
  3848. $ret['string'] = $this->header_string;
  3849. $ret['text_color'] = $this->header_text_color;
  3850. $ret['line_color'] = $this->header_line_color;
  3851. return $ret;
  3852. }
  3853. /**
  3854. * Set header margin.
  3855. * (minimum distance between header and top page margin)
  3856. * @param $hm (int) distance in user units
  3857. * @public
  3858. */
  3859. public function setHeaderMargin($hm=10) {
  3860. $this->header_margin = $hm;
  3861. }
  3862. /**
  3863. * Returns header margin in user units.
  3864. * @return float
  3865. * @since 4.0.012 (2008-07-24)
  3866. * @public
  3867. */
  3868. public function getHeaderMargin() {
  3869. return $this->header_margin;
  3870. }
  3871. /**
  3872. * Set footer margin.
  3873. * (minimum distance between footer and bottom page margin)
  3874. * @param $fm (int) distance in user units
  3875. * @public
  3876. */
  3877. public function setFooterMargin($fm=10) {
  3878. $this->footer_margin = $fm;
  3879. }
  3880. /**
  3881. * Returns footer margin in user units.
  3882. * @return float
  3883. * @since 4.0.012 (2008-07-24)
  3884. * @public
  3885. */
  3886. public function getFooterMargin() {
  3887. return $this->footer_margin;
  3888. }
  3889. /**
  3890. * Set a flag to print page header.
  3891. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3892. * @public
  3893. */
  3894. public function setPrintHeader($val=true) {
  3895. $this->print_header = $val ? true : false;
  3896. }
  3897. /**
  3898. * Set a flag to print page footer.
  3899. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3900. * @public
  3901. */
  3902. public function setPrintFooter($val=true) {
  3903. $this->print_footer = $val ? true : false;
  3904. }
  3905. /**
  3906. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3907. * @return float
  3908. * @public
  3909. */
  3910. public function getImageRBX() {
  3911. return $this->img_rb_x;
  3912. }
  3913. /**
  3914. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3915. * @return float
  3916. * @public
  3917. */
  3918. public function getImageRBY() {
  3919. return $this->img_rb_y;
  3920. }
  3921. /**
  3922. * Reset the xobject template used by Header() method.
  3923. * @public
  3924. */
  3925. public function resetHeaderTemplate() {
  3926. $this->header_xobjid = -1;
  3927. }
  3928. /**
  3929. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3930. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3931. * @public
  3932. */
  3933. public function setHeaderTemplateAutoreset($val=true) {
  3934. $this->header_xobj_autoreset = $val ? true : false;
  3935. }
  3936. /**
  3937. * This method is used to render the page header.
  3938. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3939. * @public
  3940. */
  3941. public function Header() {
  3942. if ($this->header_xobjid < 0) {
  3943. // start a new XObject Template
  3944. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3945. $headerfont = $this->getHeaderFont();
  3946. $headerdata = $this->getHeaderData();
  3947. $this->y = $this->header_margin;
  3948. if ($this->rtl) {
  3949. $this->x = $this->w - $this->original_rMargin;
  3950. } else {
  3951. $this->x = $this->original_lMargin;
  3952. }
  3953. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3954. $imgtype = $this->getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3955. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3956. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3957. } elseif ($imgtype == 'svg') {
  3958. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3959. } else {
  3960. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3961. }
  3962. $imgy = $this->getImageRBY();
  3963. } else {
  3964. $imgy = $this->y;
  3965. }
  3966. $cell_height = round(($this->cell_height_ratio * $headerfont[2]) / $this->k, 2);
  3967. // set starting margin for text data cell
  3968. if ($this->getRTL()) {
  3969. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3970. } else {
  3971. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3972. }
  3973. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3974. $this->SetTextColorArray($this->header_text_color);
  3975. // header title
  3976. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3977. $this->SetX($header_x);
  3978. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3979. // header string
  3980. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3981. $this->SetX($header_x);
  3982. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3983. // print an ending header line
  3984. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
  3985. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3986. if ($this->rtl) {
  3987. $this->SetX($this->original_rMargin);
  3988. } else {
  3989. $this->SetX($this->original_lMargin);
  3990. }
  3991. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3992. $this->endTemplate();
  3993. }
  3994. // print header template
  3995. $x = 0;
  3996. $dx = 0;
  3997. if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
  3998. // adjust margins for booklet mode
  3999. $dx = ($this->original_lMargin - $this->original_rMargin);
  4000. }
  4001. if ($this->rtl) {
  4002. $x = $this->w + $dx;
  4003. } else {
  4004. $x = 0 + $dx;
  4005. }
  4006. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  4007. if ($this->header_xobj_autoreset) {
  4008. // reset header xobject template at each page
  4009. $this->header_xobjid = -1;
  4010. }
  4011. }
  4012. /**
  4013. * This method is used to render the page footer.
  4014. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  4015. * @public
  4016. */
  4017. public function Footer() {
  4018. $cur_y = $this->y;
  4019. $this->SetTextColorArray($this->footer_text_color);
  4020. //set style for cell border
  4021. $line_width = (0.85 / $this->k);
  4022. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
  4023. //print document barcode
  4024. $barcode = $this->getBarcode();
  4025. if (!empty($barcode)) {
  4026. $this->Ln($line_width);
  4027. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  4028. $style = array(
  4029. 'position' => $this->rtl?'R':'L',
  4030. 'align' => $this->rtl?'R':'L',
  4031. 'stretch' => false,
  4032. 'fitwidth' => true,
  4033. 'cellfitalign' => '',
  4034. 'border' => false,
  4035. 'padding' => 0,
  4036. 'fgcolor' => array(0,0,0),
  4037. 'bgcolor' => false,
  4038. 'text' => false
  4039. );
  4040. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  4041. }
  4042. if (empty($this->pagegroups)) {
  4043. $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  4044. } else {
  4045. $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  4046. }
  4047. $this->SetY($cur_y);
  4048. //Print page number
  4049. if ($this->getRTL()) {
  4050. $this->SetX($this->original_rMargin);
  4051. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  4052. } else {
  4053. $this->SetX($this->original_lMargin);
  4054. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  4055. }
  4056. }
  4057. /**
  4058. * This method is used to render the page header.
  4059. * @protected
  4060. * @since 4.0.012 (2008-07-24)
  4061. */
  4062. protected function setHeader() {
  4063. if (!$this->print_header) {
  4064. return;
  4065. }
  4066. $this->InHeader = true;
  4067. $this->setGraphicVars($this->default_graphic_vars);
  4068. $temp_thead = $this->thead;
  4069. $temp_theadMargins = $this->theadMargins;
  4070. $lasth = $this->lasth;
  4071. $this->_out('q');
  4072. $this->rMargin = $this->original_rMargin;
  4073. $this->lMargin = $this->original_lMargin;
  4074. $this->SetCellPadding(0);
  4075. //set current position
  4076. if ($this->rtl) {
  4077. $this->SetXY($this->original_rMargin, $this->header_margin);
  4078. } else {
  4079. $this->SetXY($this->original_lMargin, $this->header_margin);
  4080. }
  4081. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  4082. $this->Header();
  4083. //restore position
  4084. if ($this->rtl) {
  4085. $this->SetXY($this->original_rMargin, $this->tMargin);
  4086. } else {
  4087. $this->SetXY($this->original_lMargin, $this->tMargin);
  4088. }
  4089. $this->_out('Q');
  4090. $this->lasth = $lasth;
  4091. $this->thead = $temp_thead;
  4092. $this->theadMargins = $temp_theadMargins;
  4093. $this->newline = false;
  4094. $this->InHeader = false;
  4095. }
  4096. /**
  4097. * This method is used to render the page footer.
  4098. * @protected
  4099. * @since 4.0.012 (2008-07-24)
  4100. */
  4101. protected function setFooter() {
  4102. //Page footer
  4103. $this->InFooter = true;
  4104. // save current graphic settings
  4105. $gvars = $this->getGraphicVars();
  4106. // mark this point
  4107. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  4108. $this->_out("\n");
  4109. if ($this->print_footer) {
  4110. $this->setGraphicVars($this->default_graphic_vars);
  4111. $this->current_column = 0;
  4112. $this->num_columns = 1;
  4113. $temp_thead = $this->thead;
  4114. $temp_theadMargins = $this->theadMargins;
  4115. $lasth = $this->lasth;
  4116. $this->_out('q');
  4117. $this->rMargin = $this->original_rMargin;
  4118. $this->lMargin = $this->original_lMargin;
  4119. $this->SetCellPadding(0);
  4120. //set current position
  4121. $footer_y = $this->h - $this->footer_margin;
  4122. if ($this->rtl) {
  4123. $this->SetXY($this->original_rMargin, $footer_y);
  4124. } else {
  4125. $this->SetXY($this->original_lMargin, $footer_y);
  4126. }
  4127. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  4128. $this->Footer();
  4129. //restore position
  4130. if ($this->rtl) {
  4131. $this->SetXY($this->original_rMargin, $this->tMargin);
  4132. } else {
  4133. $this->SetXY($this->original_lMargin, $this->tMargin);
  4134. }
  4135. $this->_out('Q');
  4136. $this->lasth = $lasth;
  4137. $this->thead = $temp_thead;
  4138. $this->theadMargins = $temp_theadMargins;
  4139. }
  4140. // restore graphic settings
  4141. $this->setGraphicVars($gvars);
  4142. $this->current_column = $gvars['current_column'];
  4143. $this->num_columns = $gvars['num_columns'];
  4144. // calculate footer length
  4145. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  4146. $this->InFooter = false;
  4147. }
  4148. /**
  4149. * Check if we are on the page body (excluding page header and footer).
  4150. * @return true if we are not in page header nor in page footer, false otherwise.
  4151. * @protected
  4152. * @since 5.9.091 (2011-06-15)
  4153. */
  4154. protected function inPageBody() {
  4155. return (($this->InHeader === false) AND ($this->InFooter === false));
  4156. }
  4157. /**
  4158. * This method is used to render the table header on new page (if any).
  4159. * @protected
  4160. * @since 4.5.030 (2009-03-25)
  4161. */
  4162. protected function setTableHeader() {
  4163. if ($this->num_columns > 1) {
  4164. // multi column mode
  4165. return;
  4166. }
  4167. if (isset($this->theadMargins['top'])) {
  4168. // restore the original top-margin
  4169. $this->tMargin = $this->theadMargins['top'];
  4170. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  4171. $this->y = $this->tMargin;
  4172. }
  4173. if (!$this->empty_string($this->thead) AND (!$this->inthead)) {
  4174. // set margins
  4175. $prev_lMargin = $this->lMargin;
  4176. $prev_rMargin = $this->rMargin;
  4177. $prev_cell_padding = $this->cell_padding;
  4178. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  4179. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  4180. $this->cell_padding = $this->theadMargins['cell_padding'];
  4181. if ($this->rtl) {
  4182. $this->x = $this->w - $this->rMargin;
  4183. } else {
  4184. $this->x = $this->lMargin;
  4185. }
  4186. // account for special "cell" mode
  4187. if ($this->theadMargins['cell']) {
  4188. if ($this->rtl) {
  4189. $this->x -= $this->cell_padding['R'];
  4190. } else {
  4191. $this->x += $this->cell_padding['L'];
  4192. }
  4193. }
  4194. // print table header
  4195. $this->writeHTML($this->thead, false, false, false, false, '');
  4196. // set new top margin to skip the table headers
  4197. if (!isset($this->theadMargins['top'])) {
  4198. $this->theadMargins['top'] = $this->tMargin;
  4199. }
  4200. // store end of header position
  4201. if (!isset($this->columns[0]['th'])) {
  4202. $this->columns[0]['th'] = array();
  4203. }
  4204. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  4205. $this->tMargin = $this->y;
  4206. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  4207. $this->lasth = 0;
  4208. $this->lMargin = $prev_lMargin;
  4209. $this->rMargin = $prev_rMargin;
  4210. $this->cell_padding = $prev_cell_padding;
  4211. }
  4212. }
  4213. /**
  4214. * Returns the current page number.
  4215. * @return int page number
  4216. * @public
  4217. * @since 1.0
  4218. * @see getAliasNbPages()
  4219. */
  4220. public function PageNo() {
  4221. return $this->page;
  4222. }
  4223. /**
  4224. * Defines a new spot color.
  4225. * It can be expressed in RGB components or gray scale.
  4226. * The method can be called before the first page is created and the value is retained from page to page.
  4227. * @param $name (string) Full name of the spot color.
  4228. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  4229. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  4230. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  4231. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  4232. * @public
  4233. * @since 4.0.024 (2008-09-12)
  4234. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  4235. */
  4236. public function AddSpotColor($name, $c, $m, $y, $k) {
  4237. if (!isset($this->spot_colors[$name])) {
  4238. $i = (1 + count($this->spot_colors));
  4239. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  4240. }
  4241. }
  4242. /**
  4243. * Return the Spot color array.
  4244. * @param $name (string) Name of the spot color.
  4245. * @return (array) Spot color array or false if not defined.
  4246. * @public
  4247. * @since 5.9.125 (2011-10-03)
  4248. */
  4249. public function getSpotColor($name) {
  4250. if (isset($this->spot_colors[$name])) {
  4251. return $this->spot_colors[$name];
  4252. }
  4253. $color = preg_replace('/[\s]*/', '', $name); // remove extra spaces
  4254. $color = strtolower($color);
  4255. if (isset($this->spotcolor[$color])) {
  4256. $this->AddSpotColor($this->spotcolor[$color][4], $this->spotcolor[$color][0], $this->spotcolor[$color][1], $this->spotcolor[$color][2], $this->spotcolor[$color][3]);
  4257. return $this->spot_colors[$this->spotcolor[$color][4]];
  4258. }
  4259. return false;
  4260. }
  4261. /**
  4262. * Set the spot color for the specified type ('draw', 'fill', 'text').
  4263. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  4264. * @param $name (string) Name of the spot color.
  4265. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4266. * @return (string) PDF color command.
  4267. * @public
  4268. * @since 5.9.125 (2011-10-03)
  4269. */
  4270. public function setSpotColor($type, $name, $tint=100) {
  4271. $spotcolor = $this->getSpotColor($name);
  4272. if ($spotcolor === false) {
  4273. $this->Error('Undefined spot color: '.$name.', you must add it on the spotcolors.php file.');
  4274. }
  4275. $tint = (max(0, min(100, $tint)) / 100);
  4276. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  4277. switch ($type) {
  4278. case 'draw': {
  4279. $pdfcolor .= sprintf('CS %F SCN', $tint);
  4280. $this->DrawColor = $pdfcolor;
  4281. $this->strokecolor = $spotcolor;
  4282. break;
  4283. }
  4284. case 'fill': {
  4285. $pdfcolor .= sprintf('cs %F scn', $tint);
  4286. $this->FillColor = $pdfcolor;
  4287. $this->bgcolor = $spotcolor;
  4288. break;
  4289. }
  4290. case 'text': {
  4291. $pdfcolor .= sprintf('cs %F scn', $tint);
  4292. $this->TextColor = $pdfcolor;
  4293. $this->fgcolor = $spotcolor;
  4294. break;
  4295. }
  4296. }
  4297. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  4298. if ($this->page > 0) {
  4299. $this->_out($pdfcolor);
  4300. }
  4301. if ($this->inxobj) {
  4302. // we are inside an XObject template
  4303. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  4304. }
  4305. return $pdfcolor;
  4306. }
  4307. /**
  4308. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  4309. * @param $name (string) Name of the spot color.
  4310. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4311. * @public
  4312. * @since 4.0.024 (2008-09-12)
  4313. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  4314. */
  4315. public function SetDrawSpotColor($name, $tint=100) {
  4316. $this->setSpotColor('draw', $name, $tint);
  4317. }
  4318. /**
  4319. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  4320. * @param $name (string) Name of the spot color.
  4321. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4322. * @public
  4323. * @since 4.0.024 (2008-09-12)
  4324. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  4325. */
  4326. public function SetFillSpotColor($name, $tint=100) {
  4327. $this->setSpotColor('fill', $name, $tint);
  4328. }
  4329. /**
  4330. * Defines the spot color used for text.
  4331. * @param $name (string) Name of the spot color.
  4332. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  4333. * @public
  4334. * @since 4.0.024 (2008-09-12)
  4335. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  4336. */
  4337. public function SetTextSpotColor($name, $tint=100) {
  4338. $this->setSpotColor('text', $name, $tint);
  4339. }
  4340. /**
  4341. * Set the color array for the specified type ('draw', 'fill', 'text').
  4342. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  4343. * The method can be called before the first page is created and the value is retained from page to page.
  4344. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  4345. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  4346. * @param $ret (boolean) If true do not send the PDF command.
  4347. * @return (string) The PDF command or empty string.
  4348. * @public
  4349. * @since 3.1.000 (2008-06-11)
  4350. */
  4351. public function setColorArray($type, $color, $ret=false) {
  4352. if (is_array($color)) {
  4353. $color = array_values($color);
  4354. // component: grey, RGB red or CMYK cyan
  4355. $c = isset($color[0]) ? $color[0] : -1;
  4356. // component: RGB green or CMYK magenta
  4357. $m = isset($color[1]) ? $color[1] : -1;
  4358. // component: RGB blue or CMYK yellow
  4359. $y = isset($color[2]) ? $color[2] : -1;
  4360. // component: CMYK black
  4361. $k = isset($color[3]) ? $color[3] : -1;
  4362. // color name
  4363. $name = isset($color[4]) ? $color[4] : '';
  4364. if ($c >= 0) {
  4365. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  4366. }
  4367. }
  4368. return '';
  4369. }
  4370. /**
  4371. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  4372. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  4373. * The method can be called before the first page is created and the value is retained from page to page.
  4374. * @param $color (array) Array of colors (1, 3 or 4 values).
  4375. * @param $ret (boolean) If true do not send the PDF command.
  4376. * @return string the PDF command
  4377. * @public
  4378. * @since 3.1.000 (2008-06-11)
  4379. * @see SetDrawColor()
  4380. */
  4381. public function SetDrawColorArray($color, $ret=false) {
  4382. return $this->setColorArray('draw', $color, $ret);
  4383. }
  4384. /**
  4385. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  4386. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  4387. * The method can be called before the first page is created and the value is retained from page to page.
  4388. * @param $color (array) Array of colors (1, 3 or 4 values).
  4389. * @param $ret (boolean) If true do not send the PDF command.
  4390. * @public
  4391. * @since 3.1.000 (2008-6-11)
  4392. * @see SetFillColor()
  4393. */
  4394. public function SetFillColorArray($color, $ret=false) {
  4395. return $this->setColorArray('fill', $color, $ret);
  4396. }
  4397. /**
  4398. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  4399. * The method can be called before the first page is created and the value is retained from page to page.
  4400. * @param $color (array) Array of colors (1, 3 or 4 values).
  4401. * @param $ret (boolean) If true do not send the PDF command.
  4402. * @public
  4403. * @since 3.1.000 (2008-6-11)
  4404. * @see SetFillColor()
  4405. */
  4406. public function SetTextColorArray($color, $ret=false) {
  4407. return $this->setColorArray('text', $color, $ret);
  4408. }
  4409. /**
  4410. * Defines the color used by the specified type ('draw', 'fill', 'text').
  4411. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  4412. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4413. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4414. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4415. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4416. * @param $ret (boolean) If true do not send the command.
  4417. * @param $name (string) spot color name (if any)
  4418. * @return (string) The PDF command or empty string.
  4419. * @public
  4420. * @since 5.9.125 (2011-10-03)
  4421. */
  4422. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4423. // set default values
  4424. if (!is_numeric($col1)) {
  4425. $col1 = 0;
  4426. }
  4427. if (!is_numeric($col2)) {
  4428. $col2 = -1;
  4429. }
  4430. if (!is_numeric($col3)) {
  4431. $col3 = -1;
  4432. }
  4433. if (!is_numeric($col4)) {
  4434. $col4 = -1;
  4435. }
  4436. // set color by case
  4437. $suffix = '';
  4438. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  4439. // Grey scale
  4440. $col1 = max(0, min(255, $col1));
  4441. $intcolor = array('G' => $col1);
  4442. $pdfcolor = sprintf('%F ', ($col1 / 255));
  4443. $suffix = 'g';
  4444. } elseif ($col4 == -1) {
  4445. // RGB
  4446. $col1 = max(0, min(255, $col1));
  4447. $col2 = max(0, min(255, $col2));
  4448. $col3 = max(0, min(255, $col3));
  4449. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  4450. $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  4451. $suffix = 'rg';
  4452. } else {
  4453. $col1 = max(0, min(100, $col1));
  4454. $col2 = max(0, min(100, $col2));
  4455. $col3 = max(0, min(100, $col3));
  4456. $col4 = max(0, min(100, $col4));
  4457. if (empty($name)) {
  4458. // CMYK
  4459. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  4460. $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  4461. $suffix = 'k';
  4462. } else {
  4463. // SPOT COLOR
  4464. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  4465. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  4466. $pdfcolor = $this->setSpotColor($type, $name, 100);
  4467. }
  4468. }
  4469. switch ($type) {
  4470. case 'draw': {
  4471. $pdfcolor .= strtoupper($suffix);
  4472. $this->DrawColor = $pdfcolor;
  4473. $this->strokecolor = $intcolor;
  4474. break;
  4475. }
  4476. case 'fill': {
  4477. $pdfcolor .= $suffix;
  4478. $this->FillColor = $pdfcolor;
  4479. $this->bgcolor = $intcolor;
  4480. break;
  4481. }
  4482. case 'text': {
  4483. $pdfcolor .= $suffix;
  4484. $this->TextColor = $pdfcolor;
  4485. $this->fgcolor = $intcolor;
  4486. break;
  4487. }
  4488. }
  4489. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  4490. if (($type != 'text') AND ($this->page > 0)) {
  4491. if (!$ret) {
  4492. $this->_out($pdfcolor);
  4493. }
  4494. return $pdfcolor;
  4495. }
  4496. return '';
  4497. }
  4498. /**
  4499. * Convert a color array into a string representation.
  4500. * @param $c (array) Array of colors.
  4501. * @return (string) The color array representation.
  4502. * @protected
  4503. * @since 5.9.137 (2011-12-01)
  4504. */
  4505. protected function getColorStringFromArray($c) {
  4506. $c = array_values($c);
  4507. $color = '[';
  4508. switch (count($c)) {
  4509. case 4: {
  4510. // CMYK
  4511. $color .= sprintf('%F %F %F %F', (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));
  4512. break;
  4513. }
  4514. case 3: {
  4515. // RGB
  4516. $color .= sprintf('%F %F %F', (max(0, min(255, floatval($c[0]))) / 255), (max(0, min(255, floatval($c[1]))) / 255), (max(0, min(255, floatval($c[2]))) / 255));
  4517. break;
  4518. }
  4519. case 1: {
  4520. // grayscale
  4521. $color .= sprintf('%F', (max(0, min(255, floatval($c[0]))) / 255));
  4522. break;
  4523. }
  4524. }
  4525. $color .= ']';
  4526. return $color;
  4527. }
  4528. /**
  4529. * 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.
  4530. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4531. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4532. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4533. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4534. * @param $ret (boolean) If true do not send the command.
  4535. * @param $name (string) spot color name (if any)
  4536. * @return string the PDF command
  4537. * @public
  4538. * @since 1.3
  4539. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  4540. */
  4541. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4542. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  4543. }
  4544. /**
  4545. * 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.
  4546. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4547. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4548. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4549. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4550. * @param $ret (boolean) If true do not send the command.
  4551. * @param $name (string) Spot color name (if any).
  4552. * @return (string) The PDF command.
  4553. * @public
  4554. * @since 1.3
  4555. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  4556. */
  4557. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4558. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  4559. }
  4560. /**
  4561. * 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.
  4562. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  4563. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  4564. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  4565. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  4566. * @param $ret (boolean) If true do not send the command.
  4567. * @param $name (string) Spot color name (if any).
  4568. * @return (string) Empty string.
  4569. * @public
  4570. * @since 1.3
  4571. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  4572. */
  4573. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  4574. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  4575. }
  4576. /**
  4577. * Returns the length of a string in user unit. A font must be selected.<br>
  4578. * @param $s (string) The string whose length is to be computed
  4579. * @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.
  4580. * @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.
  4581. * @param $fontsize (float) Font size in points. The default value is the current size.
  4582. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  4583. * @return mixed int total string length or array of characted widths
  4584. * @author Nicola Asuni
  4585. * @public
  4586. * @since 1.2
  4587. */
  4588. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  4589. return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize, $getarray);
  4590. }
  4591. /**
  4592. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  4593. * @param $sa (string) The array of chars whose total length is to be computed
  4594. * @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.
  4595. * @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.
  4596. * @param $fontsize (float) Font size in points. The default value is the current size.
  4597. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  4598. * @return mixed int total string length or array of characted widths
  4599. * @author Nicola Asuni
  4600. * @public
  4601. * @since 2.4.000 (2008-03-06)
  4602. */
  4603. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  4604. // store current values
  4605. if (!$this->empty_string($fontname)) {
  4606. $prev_FontFamily = $this->FontFamily;
  4607. $prev_FontStyle = $this->FontStyle;
  4608. $prev_FontSizePt = $this->FontSizePt;
  4609. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  4610. }
  4611. // convert UTF-8 array to Latin1 if required
  4612. $sa = $this->UTF8ArrToLatin1($sa);
  4613. $w = 0; // total width
  4614. $wa = array(); // array of characters widths
  4615. foreach ($sa as $ck => $char) {
  4616. // character width
  4617. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  4618. $wa[] = $cw;
  4619. $w += $cw;
  4620. }
  4621. // restore previous values
  4622. if (!$this->empty_string($fontname)) {
  4623. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  4624. }
  4625. if ($getarray) {
  4626. return $wa;
  4627. }
  4628. return $w;
  4629. }
  4630. /**
  4631. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
  4632. * @param $char (int) The char code whose length is to be returned
  4633. * @param $notlast (boolean) If false ignore the font-spacing.
  4634. * @return float char width
  4635. * @author Nicola Asuni
  4636. * @public
  4637. * @since 2.4.000 (2008-03-06)
  4638. */
  4639. public function GetCharWidth($char, $notlast=true) {
  4640. // get raw width
  4641. $chw = $this->getRawCharWidth($char);
  4642. if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
  4643. // increase/decrease font spacing
  4644. $chw += $this->font_spacing;
  4645. }
  4646. if ($this->font_stretching != 100) {
  4647. // fixed stretching mode
  4648. $chw *= ($this->font_stretching / 100);
  4649. }
  4650. return $chw;
  4651. }
  4652. /**
  4653. * Returns the length of the char in user unit for the current font.
  4654. * @param $char (int) The char code whose length is to be returned
  4655. * @return float char width
  4656. * @author Nicola Asuni
  4657. * @public
  4658. * @since 5.9.000 (2010-09-28)
  4659. */
  4660. public function getRawCharWidth($char) {
  4661. if ($char == 173) {
  4662. // SHY character will not be printed
  4663. return (0);
  4664. }
  4665. if (isset($this->CurrentFont['cw'][$char])) {
  4666. $w = $this->CurrentFont['cw'][$char];
  4667. } elseif (isset($this->CurrentFont['dw'])) {
  4668. // default width
  4669. $w = $this->CurrentFont['dw'];
  4670. } elseif (isset($this->CurrentFont['cw'][32])) {
  4671. // default width
  4672. $w = $this->CurrentFont['cw'][32];
  4673. } else {
  4674. $w = 600;
  4675. }
  4676. return ($w * $this->FontSize / 1000);
  4677. }
  4678. /**
  4679. * Returns the numbero of characters in a string.
  4680. * @param $s (string) The input string.
  4681. * @return int number of characters
  4682. * @public
  4683. * @since 2.0.0001 (2008-01-07)
  4684. */
  4685. public function GetNumChars($s) {
  4686. if ($this->isUnicodeFont()) {
  4687. return count($this->UTF8StringToArray($s));
  4688. }
  4689. return strlen($s);
  4690. }
  4691. /**
  4692. * Fill the list of available fonts ($this->fontlist).
  4693. * @protected
  4694. * @since 4.0.013 (2008-07-28)
  4695. */
  4696. protected function getFontsList() {
  4697. $fontsdir = opendir($this->_getfontpath());
  4698. while (($file = readdir($fontsdir)) !== false) {
  4699. if (substr($file, -4) == '.php') {
  4700. array_push($this->fontlist, strtolower(basename($file, '.php')));
  4701. }
  4702. }
  4703. closedir($fontsdir);
  4704. }
  4705. /**
  4706. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  4707. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  4708. * 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.
  4709. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  4710. * @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>
  4711. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4712. * @return array containing the font data, or false in case of error.
  4713. * @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.
  4714. * @public
  4715. * @since 1.5
  4716. * @see SetFont(), setFontSubsetting()
  4717. */
  4718. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  4719. if ($subset === 'default') {
  4720. $subset = $this->font_subsetting;
  4721. }
  4722. if ($this->pdfa_mode) {
  4723. $subset = false;
  4724. }
  4725. if ($this->empty_string($family)) {
  4726. if (!$this->empty_string($this->FontFamily)) {
  4727. $family = $this->FontFamily;
  4728. } else {
  4729. $this->Error('Empty font family');
  4730. }
  4731. }
  4732. // move embedded styles on $style
  4733. if (substr($family, -1) == 'I') {
  4734. $style .= 'I';
  4735. $family = substr($family, 0, -1);
  4736. }
  4737. if (substr($family, -1) == 'B') {
  4738. $style .= 'B';
  4739. $family = substr($family, 0, -1);
  4740. }
  4741. // normalize family name
  4742. $family = strtolower($family);
  4743. if ((!$this->isunicode) AND ($family == 'arial')) {
  4744. $family = 'helvetica';
  4745. }
  4746. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  4747. $style = '';
  4748. }
  4749. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  4750. // all fonts must be embedded
  4751. $family = 'pdfa'.$family;
  4752. }
  4753. $tempstyle = strtoupper($style);
  4754. $style = '';
  4755. // underline
  4756. if (strpos($tempstyle, 'U') !== false) {
  4757. $this->underline = true;
  4758. } else {
  4759. $this->underline = false;
  4760. }
  4761. // line-through (deleted)
  4762. if (strpos($tempstyle, 'D') !== false) {
  4763. $this->linethrough = true;
  4764. } else {
  4765. $this->linethrough = false;
  4766. }
  4767. // overline
  4768. if (strpos($tempstyle, 'O') !== false) {
  4769. $this->overline = true;
  4770. } else {
  4771. $this->overline = false;
  4772. }
  4773. // bold
  4774. if (strpos($tempstyle, 'B') !== false) {
  4775. $style .= 'B';
  4776. }
  4777. // oblique
  4778. if (strpos($tempstyle, 'I') !== false) {
  4779. $style .= 'I';
  4780. }
  4781. $bistyle = $style;
  4782. $fontkey = $family.$style;
  4783. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  4784. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  4785. // check if the font has been already added
  4786. $fb = $this->getFontBuffer($fontkey);
  4787. if ($fb !== false) {
  4788. if ($this->inxobj) {
  4789. // we are inside an XObject template
  4790. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  4791. }
  4792. return $fontdata;
  4793. }
  4794. if (isset($type)) {
  4795. unset($type);
  4796. }
  4797. if (isset($cw)) {
  4798. unset($cw);
  4799. }
  4800. // get specified font directory (if any)
  4801. $fontdir = false;
  4802. if (!$this->empty_string($fontfile)) {
  4803. $fontdir = dirname($fontfile);
  4804. if ($this->empty_string($fontdir) OR ($fontdir == '.')) {
  4805. $fontdir = '';
  4806. } else {
  4807. $fontdir .= '/';
  4808. }
  4809. }
  4810. $missing_style = false; // true when the font style variation is missing
  4811. // search and include font file
  4812. if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) {
  4813. // build a standard filenames for specified font
  4814. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  4815. // search files on various directories
  4816. if (($fontdir !== false) AND file_exists($fontdir.$tmp_fontfile)) {
  4817. $fontfile = $fontdir.$tmp_fontfile;
  4818. } elseif (file_exists($this->_getfontpath().$tmp_fontfile)) {
  4819. $fontfile = $this->_getfontpath().$tmp_fontfile;
  4820. } elseif (file_exists($tmp_fontfile)) {
  4821. $fontfile = $tmp_fontfile;
  4822. } elseif (!$this->empty_string($style)) {
  4823. $missing_style = true;
  4824. // try to remove the style part
  4825. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  4826. if (($fontdir !== false) AND file_exists($fontdir.$tmp_fontfile)) {
  4827. $fontfile = $fontdir.$tmp_fontfile;
  4828. } elseif (file_exists($this->_getfontpath().$tmp_fontfile)) {
  4829. $fontfile = $this->_getfontpath().$tmp_fontfile;
  4830. } else {
  4831. $fontfile = $tmp_fontfile;
  4832. }
  4833. }
  4834. }
  4835. // include font file
  4836. if (file_exists($fontfile)) {
  4837. include($fontfile);
  4838. } else {
  4839. $this->Error('Could not include font definition file: '.$family.'');
  4840. }
  4841. // check font parameters
  4842. if ((!isset($type)) OR (!isset($cw))) {
  4843. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  4844. }
  4845. // SET default parameters
  4846. if (!isset($file) OR $this->empty_string($file)) {
  4847. $file = '';
  4848. }
  4849. if (!isset($enc) OR $this->empty_string($enc)) {
  4850. $enc = '';
  4851. }
  4852. if (!isset($cidinfo) OR $this->empty_string($cidinfo)) {
  4853. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  4854. $cidinfo['uni2cid'] = array();
  4855. }
  4856. if (!isset($ctg) OR $this->empty_string($ctg)) {
  4857. $ctg = '';
  4858. }
  4859. if (!isset($desc) OR $this->empty_string($desc)) {
  4860. $desc = array();
  4861. }
  4862. if (!isset($up) OR $this->empty_string($up)) {
  4863. $up = -100;
  4864. }
  4865. if (!isset($ut) OR $this->empty_string($ut)) {
  4866. $ut = 50;
  4867. }
  4868. if (!isset($cw) OR $this->empty_string($cw)) {
  4869. $cw = array();
  4870. }
  4871. if (!isset($dw) OR $this->empty_string($dw)) {
  4872. // set default width
  4873. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  4874. $dw = $desc['MissingWidth'];
  4875. } elseif (isset($cw[32])) {
  4876. $dw = $cw[32];
  4877. } else {
  4878. $dw = 600;
  4879. }
  4880. }
  4881. ++$this->numfonts;
  4882. if ($type == 'core') {
  4883. $name = $this->CoreFonts[$fontkey];
  4884. $subset = false;
  4885. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  4886. $subset = false;
  4887. } elseif ($type == 'TrueTypeUnicode') {
  4888. $enc = 'Identity-H';
  4889. } elseif ($type == 'cidfont0') {
  4890. if ($this->pdfa_mode) {
  4891. $this->Error('All fonts must be embedded in PDF/A mode!');
  4892. }
  4893. } else {
  4894. $this->Error('Unknow font type: '.$type.'');
  4895. }
  4896. // set name if unset
  4897. if (!isset($name) OR empty($name)) {
  4898. $name = $fontkey;
  4899. }
  4900. // create artificial font style variations if missing (only works with non-embedded fonts)
  4901. if (($type != 'core') AND $missing_style) {
  4902. // style variations
  4903. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4904. $name .= $styles[$bistyle];
  4905. // artificial bold
  4906. if (strpos($bistyle, 'B') !== false) {
  4907. if (isset($desc['StemV'])) {
  4908. // from normal to bold
  4909. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4910. } else {
  4911. // bold
  4912. $desc['StemV'] = 123;
  4913. }
  4914. }
  4915. // artificial italic
  4916. if (strpos($bistyle, 'I') !== false) {
  4917. if (isset($desc['ItalicAngle'])) {
  4918. $desc['ItalicAngle'] -= 11;
  4919. } else {
  4920. $desc['ItalicAngle'] = -11;
  4921. }
  4922. if (isset($desc['Flags'])) {
  4923. $desc['Flags'] |= 64; //bit 7
  4924. } else {
  4925. $desc['Flags'] = 64;
  4926. }
  4927. }
  4928. }
  4929. // initialize subsetchars to contain default ASCII values (0-255)
  4930. $subsetchars = array_fill(0, 256, true);
  4931. $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));
  4932. if ($this->inxobj) {
  4933. // we are inside an XObject template
  4934. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4935. }
  4936. if (isset($diff) AND (!empty($diff))) {
  4937. //Search existing encodings
  4938. $d = 0;
  4939. $nb = count($this->diffs);
  4940. for ($i=1; $i <= $nb; ++$i) {
  4941. if ($this->diffs[$i] == $diff) {
  4942. $d = $i;
  4943. break;
  4944. }
  4945. }
  4946. if ($d == 0) {
  4947. $d = $nb + 1;
  4948. $this->diffs[$d] = $diff;
  4949. }
  4950. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4951. }
  4952. if (!$this->empty_string($file)) {
  4953. if (!isset($this->FontFiles[$file])) {
  4954. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4955. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4956. } elseif ($type != 'core') {
  4957. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4958. }
  4959. } else {
  4960. // update fontkeys that are sharing this font file
  4961. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4962. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4963. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4964. }
  4965. }
  4966. }
  4967. return $fontdata;
  4968. }
  4969. /**
  4970. * Sets the font used to print character strings.
  4971. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4972. * The method can be called before the first page is created and the font is retained from page to page.
  4973. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4974. * 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 />
  4975. * @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.
  4976. * @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.
  4977. * @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
  4978. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4979. * @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.
  4980. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4981. * @author Nicola Asuni
  4982. * @public
  4983. * @since 1.0
  4984. * @see AddFont(), SetFontSize()
  4985. */
  4986. public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
  4987. //Select a font; size given in points
  4988. if ($size === null) {
  4989. $size = $this->FontSizePt;
  4990. }
  4991. if ($size < 0) {
  4992. $size = 0;
  4993. }
  4994. // try to add font (if not already added)
  4995. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4996. $this->FontFamily = $fontdata['family'];
  4997. $this->FontStyle = $fontdata['style'];
  4998. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4999. $this->SetFontSize($size, $out);
  5000. }
  5001. /**
  5002. * Defines the size of the current font.
  5003. * @param $size (float) The font size in points.
  5004. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  5005. * @public
  5006. * @since 1.0
  5007. * @see SetFont()
  5008. */
  5009. public function SetFontSize($size, $out=true) {
  5010. // font size in points
  5011. $this->FontSizePt = $size;
  5012. // font size in user units
  5013. $this->FontSize = $size / $this->k;
  5014. // calculate some font metrics
  5015. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  5016. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  5017. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  5018. } else {
  5019. $font_height = $size * 1.219;
  5020. }
  5021. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  5022. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  5023. }
  5024. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  5025. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  5026. }
  5027. if (!isset($font_ascent) AND !isset($font_descent)) {
  5028. // core font
  5029. $font_ascent = 0.76 * $font_height;
  5030. $font_descent = $font_height - $font_ascent;
  5031. } elseif (!isset($font_descent)) {
  5032. $font_descent = $font_height - $font_ascent;
  5033. } elseif (!isset($font_ascent)) {
  5034. $font_ascent = $font_height - $font_descent;
  5035. }
  5036. $this->FontAscent = ($font_ascent / $this->k);
  5037. $this->FontDescent = ($font_descent / $this->k);
  5038. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i']))) {
  5039. $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  5040. }
  5041. }
  5042. /**
  5043. * Returns the bounding box of the current font in user units.
  5044. * @return array
  5045. * @public
  5046. * @since 5.9.152 (2012-03-23)
  5047. */
  5048. public function getFontBBox() {
  5049. $result = array();
  5050. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  5051. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  5052. foreach ($bbox as $v) {
  5053. $result[] = (intval($v) * $this->FontSize / 1000);
  5054. }
  5055. } else {
  5056. // Find max width
  5057. if (isset($this->CurrentFont['desc']['MaxWidth'])) {
  5058. $maxw = (intval($this->CurrentFont['desc']['MaxWidth']) * $this->FontSize / 1000);
  5059. } else {
  5060. $maxw = 0;
  5061. if (isset($this->CurrentFont['desc']['MissingWidth'])) {
  5062. $maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
  5063. }
  5064. if (isset($this->CurrentFont['desc']['AvgWidth'])) {
  5065. $maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
  5066. }
  5067. if (isset($this->CurrentFont['dw'])) {
  5068. $maxw = max($maxw, $this->CurrentFont['dw']);
  5069. }
  5070. foreach ($this->CurrentFont['cw'] as $char => $w) {
  5071. $maxw = max($maxw, $w);
  5072. }
  5073. if ($maxw == 0) {
  5074. $maxw = 600;
  5075. }
  5076. $maxw = ($maxw * $this->FontSize / 1000);
  5077. }
  5078. $result = array(0, -$this->FontDescent, $maxw, $this->FontAscent);
  5079. }
  5080. return $result;
  5081. }
  5082. /**
  5083. * Return the font descent value
  5084. * @param $font (string) font name
  5085. * @param $style (string) font style
  5086. * @param $size (float) The size (in points)
  5087. * @return int font descent
  5088. * @public
  5089. * @author Nicola Asuni
  5090. * @since 4.9.003 (2010-03-30)
  5091. */
  5092. public function getFontDescent($font, $style='', $size=0) {
  5093. $fontdata = $this->AddFont($font, $style);
  5094. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  5095. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  5096. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  5097. } else {
  5098. $descent = 1.219 * 0.24 * $size;
  5099. }
  5100. return ($descent / $this->k);
  5101. }
  5102. /**
  5103. * Return the font ascent value.
  5104. * @param $font (string) font name
  5105. * @param $style (string) font style
  5106. * @param $size (float) The size (in points)
  5107. * @return int font ascent
  5108. * @public
  5109. * @author Nicola Asuni
  5110. * @since 4.9.003 (2010-03-30)
  5111. */
  5112. public function getFontAscent($font, $style='', $size=0) {
  5113. $fontdata = $this->AddFont($font, $style);
  5114. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  5115. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  5116. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  5117. } else {
  5118. $ascent = 1.219 * 0.76 * $size;
  5119. }
  5120. return ($ascent / $this->k);
  5121. }
  5122. /**
  5123. * Return true in the character is present in the specified font.
  5124. * @param $char (mixed) Character to check (integer value or string)
  5125. * @param $font (string) Font name (family name).
  5126. * @param $style (string) Font style.
  5127. * @return (boolean) true if the char is defined, false otherwise.
  5128. * @public
  5129. * @since 5.9.153 (2012-03-28)
  5130. */
  5131. public function isCharDefined($char, $font='', $style='') {
  5132. if (is_string($char)) {
  5133. // get character code
  5134. $char = $this->UTF8StringToArray($char);
  5135. $char = $char[0];
  5136. }
  5137. if ($this->empty_string($font)) {
  5138. if ($this->empty_string($style)) {
  5139. return (isset($this->CurrentFont['cw'][intval($char)]));
  5140. }
  5141. $font = $this->FontFamily;
  5142. }
  5143. $fontdata = $this->AddFont($font, $style);
  5144. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  5145. return (isset($fontinfo['cw'][intval($char)]));
  5146. }
  5147. /**
  5148. * Replace missing font characters on selected font with specified substitutions.
  5149. * @param $text (string) Text to process.
  5150. * @param $font (string) Font name (family name).
  5151. * @param $style (string) Font style.
  5152. * @param $subs (array) Array of possible character substitutions. The key is the character to check (integer value) and the value is a single intege value or an array of possible substitutes.
  5153. * @return (string) Processed text.
  5154. * @public
  5155. * @since 5.9.153 (2012-03-28)
  5156. */
  5157. public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
  5158. if (empty($subs)) {
  5159. return $text;
  5160. }
  5161. if ($this->empty_string($font)) {
  5162. $font = $this->FontFamily;
  5163. }
  5164. $fontdata = $this->AddFont($font, $style);
  5165. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  5166. $uniarr = $this->UTF8StringToArray($text);
  5167. foreach ($uniarr as $k => $chr) {
  5168. if (!isset($fontinfo['cw'][$chr])) {
  5169. // this character is missing on the selected font
  5170. if (isset($subs[$chr])) {
  5171. // we have available substitutions
  5172. if (is_array($subs[$chr])) {
  5173. foreach($subs[$chr] as $s) {
  5174. if (isset($fontinfo['cw'][$s])) {
  5175. $uniarr[$k] = $s;
  5176. break;
  5177. }
  5178. }
  5179. } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
  5180. $uniarr[$k] = $subs[$chr];
  5181. }
  5182. }
  5183. }
  5184. }
  5185. return $this->UniArrSubString($this->UTF8ArrayToUniArray($uniarr));
  5186. }
  5187. /**
  5188. * Defines the default monospaced font.
  5189. * @param $font (string) Font name.
  5190. * @public
  5191. * @since 4.5.025
  5192. */
  5193. public function SetDefaultMonospacedFont($font) {
  5194. $this->default_monospaced_font = $font;
  5195. }
  5196. /**
  5197. * 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 />
  5198. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  5199. * @public
  5200. * @since 1.5
  5201. * @see Cell(), Write(), Image(), Link(), SetLink()
  5202. */
  5203. public function AddLink() {
  5204. //Create a new internal link
  5205. $n = count($this->links) + 1;
  5206. $this->links[$n] = array(0, 0);
  5207. return $n;
  5208. }
  5209. /**
  5210. * Defines the page and position a link points to.
  5211. * @param $link (int) The link identifier returned by AddLink()
  5212. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  5213. * @param $page (int) Number of target page; -1 indicates the current page. This is the default value
  5214. * @public
  5215. * @since 1.5
  5216. * @see AddLink()
  5217. */
  5218. public function SetLink($link, $y=0, $page=-1) {
  5219. if ($y == -1) {
  5220. $y = $this->y;
  5221. }
  5222. if ($page == -1) {
  5223. $page = $this->page;
  5224. }
  5225. $this->links[$link] = array($page, $y);
  5226. }
  5227. /**
  5228. * Puts a link on a rectangular area of the page.
  5229. * 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.
  5230. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  5231. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  5232. * @param $w (float) Width of the rectangle
  5233. * @param $h (float) Height of the rectangle
  5234. * @param $link (mixed) URL or identifier returned by AddLink()
  5235. * @param $spaces (int) number of spaces on the text to link
  5236. * @public
  5237. * @since 1.5
  5238. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  5239. */
  5240. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  5241. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  5242. }
  5243. /**
  5244. * Puts a markup annotation on a rectangular area of the page.
  5245. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  5246. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  5247. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  5248. * @param $w (float) Width of the rectangle
  5249. * @param $h (float) Height of the rectangle
  5250. * @param $text (string) annotation text or alternate content
  5251. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  5252. * @param $spaces (int) number of spaces on the text to link
  5253. * @public
  5254. * @since 4.0.018 (2008-08-06)
  5255. */
  5256. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  5257. if ($this->inxobj) {
  5258. // store parameters for later use on template
  5259. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  5260. return;
  5261. }
  5262. if ($x === '') {
  5263. $x = $this->x;
  5264. }
  5265. if ($y === '') {
  5266. $y = $this->y;
  5267. }
  5268. // check page for no-write regions and adapt page margins if necessary
  5269. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  5270. // recalculate coordinates to account for graphic transformations
  5271. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  5272. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  5273. $maxid = count($this->transfmatrix[$i]) - 1;
  5274. for ($j=$maxid; $j >= 0; --$j) {
  5275. $ctm = $this->transfmatrix[$i][$j];
  5276. if (isset($ctm['a'])) {
  5277. $x = $x * $this->k;
  5278. $y = ($this->h - $y) * $this->k;
  5279. $w = $w * $this->k;
  5280. $h = $h * $this->k;
  5281. // top left
  5282. $xt = $x;
  5283. $yt = $y;
  5284. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5285. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5286. // top right
  5287. $xt = $x + $w;
  5288. $yt = $y;
  5289. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5290. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5291. // bottom left
  5292. $xt = $x;
  5293. $yt = $y - $h;
  5294. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5295. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5296. // bottom right
  5297. $xt = $x + $w;
  5298. $yt = $y - $h;
  5299. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  5300. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  5301. // new coordinates (rectangle area)
  5302. $x = min($x1, $x2, $x3, $x4);
  5303. $y = max($y1, $y2, $y3, $y4);
  5304. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  5305. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  5306. $x = $x / $this->k;
  5307. $y = $this->h - ($y / $this->k);
  5308. }
  5309. }
  5310. }
  5311. }
  5312. if ($this->page <= 0) {
  5313. $page = 1;
  5314. } else {
  5315. $page = $this->page;
  5316. }
  5317. if (!isset($this->PageAnnots[$page])) {
  5318. $this->PageAnnots[$page] = array();
  5319. }
  5320. ++$this->n;
  5321. $this->PageAnnots[$page][] = array('n' => $this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  5322. if (!$this->pdfa_mode) {
  5323. 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'])]))) {
  5324. ++$this->n;
  5325. $this->embeddedfiles[basename($opt['FS'])] = array('n' => $this->n, 'file' => $opt['FS']);
  5326. }
  5327. }
  5328. // Add widgets annotation's icons
  5329. if (isset($opt['mk']['i']) AND file_exists($opt['mk']['i'])) {
  5330. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  5331. }
  5332. if (isset($opt['mk']['ri']) AND file_exists($opt['mk']['ri'])) {
  5333. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  5334. }
  5335. if (isset($opt['mk']['ix']) AND file_exists($opt['mk']['ix'])) {
  5336. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  5337. }
  5338. }
  5339. /**
  5340. * Embedd the attached files.
  5341. * @since 4.4.000 (2008-12-07)
  5342. * @protected
  5343. * @see Annotation()
  5344. */
  5345. protected function _putEmbeddedFiles() {
  5346. if ($this->pdfa_mode) {
  5347. // embedded files are not allowed in PDF/A mode
  5348. return;
  5349. }
  5350. reset($this->embeddedfiles);
  5351. foreach ($this->embeddedfiles as $filename => $filedata) {
  5352. $data = file_get_contents($filedata['file']);
  5353. $filter = '';
  5354. if ($this->compress) {
  5355. $data = gzcompress($data);
  5356. $filter = ' /Filter /FlateDecode';
  5357. }
  5358. $stream = $this->_getrawstream($data, $filedata['n']);
  5359. $out = $this->_getobj($filedata['n'])."\n";
  5360. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' >>';
  5361. $out .= ' stream'."\n".$stream."\n".'endstream';
  5362. $out .= "\n".'endobj';
  5363. $this->_out($out);
  5364. }
  5365. }
  5366. /**
  5367. * Prints a text cell at the specified position.
  5368. * This method allows to place a string precisely on the page.
  5369. * @param $x (float) Abscissa of the cell origin
  5370. * @param $y (float) Ordinate of the cell origin
  5371. * @param $txt (string) String to print
  5372. * @param $fstroke (int) outline size in user units (false = disable)
  5373. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  5374. * @param $ffill (boolean) if true fills the text
  5375. * @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)))
  5376. * @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.
  5377. * @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>
  5378. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5379. * @param $link (mixed) URL or identifier returned by AddLink().
  5380. * @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.
  5381. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  5382. * @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>
  5383. * @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>
  5384. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  5385. * @public
  5386. * @since 1.0
  5387. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  5388. */
  5389. 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) {
  5390. $textrendermode = $this->textrendermode;
  5391. $textstrokewidth = $this->textstrokewidth;
  5392. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  5393. $this->SetXY($x, $y, $rtloff);
  5394. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  5395. // restore previous rendering mode
  5396. $this->textrendermode = $textrendermode;
  5397. $this->textstrokewidth = $textstrokewidth;
  5398. }
  5399. /**
  5400. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  5401. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  5402. * This method is called automatically and should not be called directly by the application.
  5403. * @return boolean
  5404. * @public
  5405. * @since 1.4
  5406. * @see SetAutoPageBreak()
  5407. */
  5408. public function AcceptPageBreak() {
  5409. if ($this->num_columns > 1) {
  5410. // multi column mode
  5411. if ($this->current_column < ($this->num_columns - 1)) {
  5412. // go to next column
  5413. $this->selectColumn($this->current_column + 1);
  5414. } elseif ($this->AutoPageBreak) {
  5415. // add a new page
  5416. $this->AddPage();
  5417. // set first column
  5418. $this->selectColumn(0);
  5419. }
  5420. // avoid page breaking from checkPageBreak()
  5421. return false;
  5422. }
  5423. return $this->AutoPageBreak;
  5424. }
  5425. /**
  5426. * Add page if needed.
  5427. * @param $h (float) Cell height. Default value: 0.
  5428. * @param $y (mixed) starting y position, leave empty for current position.
  5429. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  5430. * @return boolean true in case of page break, false otherwise.
  5431. * @since 3.2.000 (2008-07-01)
  5432. * @protected
  5433. */
  5434. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  5435. if ($this->empty_string($y)) {
  5436. $y = $this->y;
  5437. }
  5438. $current_page = $this->page;
  5439. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  5440. if ($addpage) {
  5441. //Automatic page break
  5442. $x = $this->x;
  5443. $this->AddPage($this->CurOrientation);
  5444. $this->y = $this->tMargin;
  5445. $oldpage = $this->page - 1;
  5446. if ($this->rtl) {
  5447. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  5448. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  5449. } else {
  5450. $this->x = $x;
  5451. }
  5452. } else {
  5453. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  5454. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  5455. } else {
  5456. $this->x = $x;
  5457. }
  5458. }
  5459. }
  5460. return true;
  5461. }
  5462. if ($current_page != $this->page) {
  5463. // account for columns mode
  5464. return true;
  5465. }
  5466. return false;
  5467. }
  5468. /**
  5469. * Removes SHY characters from text.
  5470. * Unicode Data:<ul>
  5471. * <li>Name : SOFT HYPHEN, commonly abbreviated as SHY</li>
  5472. * <li>HTML Entity (decimal): "&amp;#173;"</li>
  5473. * <li>HTML Entity (hex): "&amp;#xad;"</li>
  5474. * <li>HTML Entity (named): "&amp;shy;"</li>
  5475. * <li>How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]</li>
  5476. * <li>UTF-8 (hex): 0xC2 0xAD (c2ad)</li>
  5477. * <li>UTF-8 character: chr(194).chr(173)</li>
  5478. * </ul>
  5479. * @param $txt (string) input string
  5480. * @return string without SHY characters.
  5481. * @public
  5482. * @since (4.5.019) 2009-02-28
  5483. */
  5484. public function removeSHY($txt='') {
  5485. $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
  5486. if (!$this->isunicode) {
  5487. $txt = preg_replace('/([\\xad]{1})/', '', $txt);
  5488. }
  5489. return $txt;
  5490. }
  5491. /**
  5492. * 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 />
  5493. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  5494. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  5495. * @param $h (float) Cell height. Default value: 0.
  5496. * @param $txt (string) String to print. Default value: empty string.
  5497. * @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)))
  5498. * @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.
  5499. * @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>
  5500. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5501. * @param $link (mixed) URL or identifier returned by AddLink().
  5502. * @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.
  5503. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  5504. * @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>
  5505. * @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>
  5506. * @public
  5507. * @since 1.0
  5508. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  5509. */
  5510. 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') {
  5511. $prev_cell_margin = $this->cell_margin;
  5512. $prev_cell_padding = $this->cell_padding;
  5513. $this->adjustCellPadding($border);
  5514. if (!$ignore_min_height) {
  5515. $min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  5516. if ($h < $min_cell_height) {
  5517. $h = $min_cell_height;
  5518. }
  5519. }
  5520. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  5521. // apply text shadow if enabled
  5522. if ($this->txtshadow['enabled']) {
  5523. // save data
  5524. $x = $this->x;
  5525. $y = $this->y;
  5526. $bc = $this->bgcolor;
  5527. $fc = $this->fgcolor;
  5528. $sc = $this->strokecolor;
  5529. $alpha = $this->alpha;
  5530. // print shadow
  5531. $this->x += $this->txtshadow['depth_w'];
  5532. $this->y += $this->txtshadow['depth_h'];
  5533. $this->SetFillColorArray($this->txtshadow['color']);
  5534. $this->SetTextColorArray($this->txtshadow['color']);
  5535. $this->SetDrawColorArray($this->txtshadow['color']);
  5536. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  5537. $this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
  5538. }
  5539. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  5540. //restore data
  5541. $this->x = $x;
  5542. $this->y = $y;
  5543. $this->SetFillColorArray($bc);
  5544. $this->SetTextColorArray($fc);
  5545. $this->SetDrawColorArray($sc);
  5546. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  5547. $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
  5548. }
  5549. }
  5550. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  5551. $this->cell_padding = $prev_cell_padding;
  5552. $this->cell_margin = $prev_cell_margin;
  5553. }
  5554. /**
  5555. * 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 />
  5556. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  5557. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  5558. * @param $h (float) Cell height. Default value: 0.
  5559. * @param $txt (string) String to print. Default value: empty string.
  5560. * @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)))
  5561. * @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.
  5562. * @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>
  5563. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5564. * @param $link (mixed) URL or identifier returned by AddLink().
  5565. * @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.
  5566. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  5567. * @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>
  5568. * @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>
  5569. * @return string containing cell code
  5570. * @protected
  5571. * @since 1.0
  5572. * @see Cell()
  5573. */
  5574. 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') {
  5575. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  5576. $txt = str_replace($this->unichr(160), ' ', $txt);
  5577. $prev_cell_margin = $this->cell_margin;
  5578. $prev_cell_padding = $this->cell_padding;
  5579. $txt = $this->removeSHY($txt);
  5580. $rs = ''; //string to be returned
  5581. $this->adjustCellPadding($border);
  5582. if (!$ignore_min_height) {
  5583. $min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  5584. if ($h < $min_cell_height) {
  5585. $h = $min_cell_height;
  5586. }
  5587. }
  5588. $k = $this->k;
  5589. // check page for no-write regions and adapt page margins if necessary
  5590. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5591. if ($this->rtl) {
  5592. $x = $this->x - $this->cell_margin['R'];
  5593. } else {
  5594. $x = $this->x + $this->cell_margin['L'];
  5595. }
  5596. $y = $this->y + $this->cell_margin['T'];
  5597. $prev_font_stretching = $this->font_stretching;
  5598. $prev_font_spacing = $this->font_spacing;
  5599. // cell vertical alignment
  5600. switch ($calign) {
  5601. case 'A': {
  5602. // font top
  5603. switch ($valign) {
  5604. case 'T': {
  5605. // top
  5606. $y -= $this->cell_padding['T'];
  5607. break;
  5608. }
  5609. case 'B': {
  5610. // bottom
  5611. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  5612. break;
  5613. }
  5614. default:
  5615. case 'C':
  5616. case 'M': {
  5617. // center
  5618. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  5619. break;
  5620. }
  5621. }
  5622. break;
  5623. }
  5624. case 'L': {
  5625. // font baseline
  5626. switch ($valign) {
  5627. case 'T': {
  5628. // top
  5629. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  5630. break;
  5631. }
  5632. case 'B': {
  5633. // bottom
  5634. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  5635. break;
  5636. }
  5637. default:
  5638. case 'C':
  5639. case 'M': {
  5640. // center
  5641. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  5642. break;
  5643. }
  5644. }
  5645. break;
  5646. }
  5647. case 'D': {
  5648. // font bottom
  5649. switch ($valign) {
  5650. case 'T': {
  5651. // top
  5652. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  5653. break;
  5654. }
  5655. case 'B': {
  5656. // bottom
  5657. $y -= ($h - $this->cell_padding['B']);
  5658. break;
  5659. }
  5660. default:
  5661. case 'C':
  5662. case 'M': {
  5663. // center
  5664. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  5665. break;
  5666. }
  5667. }
  5668. break;
  5669. }
  5670. case 'B': {
  5671. // cell bottom
  5672. $y -= $h;
  5673. break;
  5674. }
  5675. case 'C':
  5676. case 'M': {
  5677. // cell center
  5678. $y -= ($h / 2);
  5679. break;
  5680. }
  5681. default:
  5682. case 'T': {
  5683. // cell top
  5684. break;
  5685. }
  5686. }
  5687. // text vertical alignment
  5688. switch ($valign) {
  5689. case 'T': {
  5690. // top
  5691. $yt = $y + $this->cell_padding['T'];
  5692. break;
  5693. }
  5694. case 'B': {
  5695. // bottom
  5696. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  5697. break;
  5698. }
  5699. default:
  5700. case 'C':
  5701. case 'M': {
  5702. // center
  5703. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  5704. break;
  5705. }
  5706. }
  5707. $basefonty = $yt + $this->FontAscent;
  5708. if ($this->empty_string($w) OR ($w <= 0)) {
  5709. if ($this->rtl) {
  5710. $w = $x - $this->lMargin;
  5711. } else {
  5712. $w = $this->w - $this->rMargin - $x;
  5713. }
  5714. }
  5715. $s = '';
  5716. // fill and borders
  5717. if (is_string($border) AND (strlen($border) == 4)) {
  5718. // full border
  5719. $border = 1;
  5720. }
  5721. if ($fill OR ($border == 1)) {
  5722. if ($fill) {
  5723. $op = ($border == 1) ? 'B' : 'f';
  5724. } else {
  5725. $op = 'S';
  5726. }
  5727. if ($this->rtl) {
  5728. $xk = (($x - $w) * $k);
  5729. } else {
  5730. $xk = ($x * $k);
  5731. }
  5732. $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  5733. }
  5734. // draw borders
  5735. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  5736. if ($txt != '') {
  5737. $txt2 = $txt;
  5738. if ($this->isunicode) {
  5739. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  5740. $txt2 = $this->UTF8ToLatin1($txt2);
  5741. } else {
  5742. $unicode = $this->UTF8StringToArray($txt); // array of UTF-8 unicode values
  5743. $unicode = $this->utf8Bidi($unicode, '', $this->tmprtl);
  5744. // replace thai chars (if any)
  5745. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  5746. // number of chars
  5747. $numchars = count($unicode);
  5748. // po pla, for far, for fan
  5749. $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
  5750. // do chada, to patak
  5751. $lowtail = array(0x0e0e, 0x0e0f);
  5752. // mai hun arkad, sara i, sara ii, sara ue, sara uee
  5753. $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
  5754. // mai ek, mai tho, mai tri, mai chattawa, karan
  5755. $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
  5756. // sara u, sara uu, pinthu
  5757. $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
  5758. $output = array();
  5759. for ($i = 0; $i < $numchars; $i++) {
  5760. if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
  5761. $ch0 = $unicode[$i];
  5762. $ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
  5763. $ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
  5764. $chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
  5765. if (in_array($ch0, $tonemark)) {
  5766. if ($chn == 0x0e33) {
  5767. // sara um
  5768. if (in_array($ch1, $longtail)) {
  5769. // tonemark at upper left
  5770. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  5771. } else {
  5772. // tonemark at upper right (normal position)
  5773. $output[] = $ch0;
  5774. }
  5775. } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
  5776. // tonemark at lower left
  5777. $output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
  5778. } elseif (in_array($ch1, $upvowel)) {
  5779. if (in_array($ch2, $longtail)) {
  5780. // tonemark at upper left
  5781. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  5782. } else {
  5783. // tonemark at upper right (normal position)
  5784. $output[] = $ch0;
  5785. }
  5786. } else {
  5787. // tonemark at lower right
  5788. $output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
  5789. }
  5790. } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
  5791. // add lower left nikhahit and sara aa
  5792. if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
  5793. $output[] = 0xf711;
  5794. $this->CurrentFont['subsetchars'][0xf711] = true;
  5795. $output[] = 0x0e32;
  5796. $this->CurrentFont['subsetchars'][0x0e32] = true;
  5797. } else {
  5798. $output[] = $ch0;
  5799. }
  5800. } elseif (in_array($ch1, $longtail)) {
  5801. if ($ch0 == 0x0e31) {
  5802. // lower left mai hun arkad
  5803. $output[] = $this->replaceChar($ch0, 0xf710);
  5804. } elseif (in_array($ch0, $upvowel)) {
  5805. // lower left
  5806. $output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
  5807. } elseif ($ch0 == 0x0e47) {
  5808. // lower left mai tai koo
  5809. $output[] = $this->replaceChar($ch0, 0xf712);
  5810. } else {
  5811. // normal character
  5812. $output[] = $ch0;
  5813. }
  5814. } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
  5815. // lower vowel
  5816. $output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
  5817. } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
  5818. // yo ying without lower part
  5819. $output[] = $this->replaceChar($ch0, 0xf70f);
  5820. } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
  5821. // tho santan without lower part
  5822. $output[] = $this->replaceChar($ch0, 0xf700);
  5823. } else {
  5824. $output[] = $ch0;
  5825. }
  5826. } else {
  5827. // non-thai character
  5828. $output[] = $unicode[$i];
  5829. }
  5830. }
  5831. $unicode = $output;
  5832. // update font subsetchars
  5833. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  5834. } // end of K_THAI_TOPCHARS
  5835. $txt2 = $this->arrUTF8ToUTF16BE($unicode, false);
  5836. }
  5837. }
  5838. $txt2 = $this->_escape($txt2);
  5839. // get current text width (considering general font stretching and spacing)
  5840. $txwidth = $this->GetStringWidth($txt);
  5841. $width = $txwidth;
  5842. // check for stretch mode
  5843. if ($stretch > 0) {
  5844. // calculate ratio between cell width and text width
  5845. if ($width <= 0) {
  5846. $ratio = 1;
  5847. } else {
  5848. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  5849. }
  5850. // check if stretching is required
  5851. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5852. // the text will be stretched to fit cell width
  5853. if ($stretch > 2) {
  5854. // set new character spacing
  5855. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5856. } else {
  5857. // set new horizontal stretching
  5858. $this->font_stretching *= $ratio;
  5859. }
  5860. // recalculate text width (the text fills the entire cell)
  5861. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5862. // reset alignment
  5863. $align = '';
  5864. }
  5865. }
  5866. if ($this->font_stretching != 100) {
  5867. // apply font stretching
  5868. $rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
  5869. }
  5870. if ($this->font_spacing != 0) {
  5871. // increase/decrease font spacing
  5872. $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
  5873. }
  5874. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5875. $s .= 'q '.$this->TextColor.' ';
  5876. }
  5877. // rendering mode
  5878. $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
  5879. // count number of spaces
  5880. $ns = substr_count($txt, chr(32));
  5881. // Justification
  5882. $spacewidth = 0;
  5883. if (($align == 'J') AND ($ns > 0)) {
  5884. if ($this->isUnicodeFont()) {
  5885. // get string width without spaces
  5886. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5887. // calculate average space width
  5888. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / $this->FontSize;
  5889. if ($this->font_stretching != 100) {
  5890. // word spacing is affected by stretching
  5891. $spacewidth /= ($this->font_stretching / 100);
  5892. }
  5893. // set word position to be used with TJ operator
  5894. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
  5895. $unicode_justification = true;
  5896. } else {
  5897. // get string width
  5898. $width = $txwidth;
  5899. // new space width
  5900. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5901. if ($this->font_stretching != 100) {
  5902. // word spacing (Tw) is affected by stretching
  5903. $spacewidth /= ($this->font_stretching / 100);
  5904. }
  5905. // set word spacing
  5906. $rs .= sprintf('BT %F Tw ET ', $spacewidth);
  5907. }
  5908. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5909. }
  5910. // replace carriage return characters
  5911. $txt2 = str_replace("\r", ' ', $txt2);
  5912. switch ($align) {
  5913. case 'C': {
  5914. $dx = ($w - $width) / 2;
  5915. break;
  5916. }
  5917. case 'R': {
  5918. if ($this->rtl) {
  5919. $dx = $this->cell_padding['R'];
  5920. } else {
  5921. $dx = $w - $width - $this->cell_padding['R'];
  5922. }
  5923. break;
  5924. }
  5925. case 'L': {
  5926. if ($this->rtl) {
  5927. $dx = $w - $width - $this->cell_padding['L'];
  5928. } else {
  5929. $dx = $this->cell_padding['L'];
  5930. }
  5931. break;
  5932. }
  5933. case 'J':
  5934. default: {
  5935. if ($this->rtl) {
  5936. $dx = $this->cell_padding['R'];
  5937. } else {
  5938. $dx = $this->cell_padding['L'];
  5939. }
  5940. break;
  5941. }
  5942. }
  5943. if ($this->rtl) {
  5944. $xdx = $x - $dx - $width;
  5945. } else {
  5946. $xdx = $x + $dx;
  5947. }
  5948. $xdk = $xdx * $k;
  5949. // print text
  5950. $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5951. if (isset($uniblock)) {
  5952. // print overlapping characters as separate string
  5953. $xshift = 0; // horizontal shift
  5954. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5955. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5956. foreach ($uniblock as $uk => $uniarr) {
  5957. if (($uk % 2) == 0) {
  5958. // x space to skip
  5959. if ($spacewidth != 0) {
  5960. // justification shift
  5961. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5962. }
  5963. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5964. } else {
  5965. // character to print
  5966. $topchr = $this->arrUTF8ToUTF16BE($uniarr, false);
  5967. $topchr = $this->_escape($topchr);
  5968. $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5969. }
  5970. }
  5971. }
  5972. if ($this->underline) {
  5973. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5974. }
  5975. if ($this->linethrough) {
  5976. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5977. }
  5978. if ($this->overline) {
  5979. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5980. }
  5981. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5982. $s .= ' Q';
  5983. }
  5984. if ($link) {
  5985. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5986. }
  5987. }
  5988. // output cell
  5989. if ($s) {
  5990. // output cell
  5991. $rs .= $s;
  5992. if ($this->font_spacing != 0) {
  5993. // reset font spacing mode
  5994. $rs .= ' BT 0 Tc ET';
  5995. }
  5996. if ($this->font_stretching != 100) {
  5997. // reset font stretching mode
  5998. $rs .= ' BT 100 Tz ET';
  5999. }
  6000. }
  6001. // reset word spacing
  6002. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  6003. $rs .= ' BT 0 Tw ET';
  6004. }
  6005. // reset stretching and spacing
  6006. $this->font_stretching = $prev_font_stretching;
  6007. $this->font_spacing = $prev_font_spacing;
  6008. $this->lasth = $h;
  6009. if ($ln > 0) {
  6010. //Go to the beginning of the next line
  6011. $this->y = $y + $h + $this->cell_margin['B'];
  6012. if ($ln == 1) {
  6013. if ($this->rtl) {
  6014. $this->x = $this->w - $this->rMargin;
  6015. } else {
  6016. $this->x = $this->lMargin;
  6017. }
  6018. }
  6019. } else {
  6020. // go left or right by case
  6021. if ($this->rtl) {
  6022. $this->x = $x - $w - $this->cell_margin['L'];
  6023. } else {
  6024. $this->x = $x + $w + $this->cell_margin['R'];
  6025. }
  6026. }
  6027. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  6028. $rs = $gstyles.$rs;
  6029. $this->cell_padding = $prev_cell_padding;
  6030. $this->cell_margin = $prev_cell_margin;
  6031. return $rs;
  6032. }
  6033. /**
  6034. * Replace a char if is defined on the current font.
  6035. * @param $oldchar (int) Integer code (unicode) of the character to replace.
  6036. * @param $newchar (int) Integer code (unicode) of the new character.
  6037. * @return int the replaced char or the old char in case the new char i not defined
  6038. * @protected
  6039. * @since 5.9.167 (2012-06-22)
  6040. */
  6041. protected function replaceChar($oldchar, $newchar) {
  6042. if ($this->isCharDefined($newchar)) {
  6043. // add the new char on the subset list
  6044. $this->CurrentFont['subsetchars'][$newchar] = true;
  6045. // return the new character
  6046. return $newchar;
  6047. }
  6048. // return the old char
  6049. return $oldchar;
  6050. }
  6051. /**
  6052. * Returns the code to draw the cell border
  6053. * @param $x (float) X coordinate.
  6054. * @param $y (float) Y coordinate.
  6055. * @param $w (float) Cell width.
  6056. * @param $h (float) Cell height.
  6057. * @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)))
  6058. * @return string containing cell border code
  6059. * @protected
  6060. * @see SetLineStyle()
  6061. * @since 5.7.000 (2010-08-02)
  6062. */
  6063. protected function getCellBorder($x, $y, $w, $h, $brd) {
  6064. $s = ''; // string to be returned
  6065. if (empty($brd)) {
  6066. return $s;
  6067. }
  6068. if ($brd == 1) {
  6069. $brd = array('LRTB' => true);
  6070. }
  6071. // calculate coordinates for border
  6072. $k = $this->k;
  6073. if ($this->rtl) {
  6074. $xeL = ($x - $w) * $k;
  6075. $xeR = $x * $k;
  6076. } else {
  6077. $xeL = $x * $k;
  6078. $xeR = ($x + $w) * $k;
  6079. }
  6080. $yeL = (($this->h - ($y + $h)) * $k);
  6081. $yeT = (($this->h - $y) * $k);
  6082. $xeT = $xeL;
  6083. $xeB = $xeR;
  6084. $yeR = $yeT;
  6085. $yeB = $yeL;
  6086. if (is_string($brd)) {
  6087. // convert string to array
  6088. $slen = strlen($brd);
  6089. $newbrd = array();
  6090. for ($i = 0; $i < $slen; ++$i) {
  6091. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  6092. }
  6093. $brd = $newbrd;
  6094. }
  6095. if (isset($brd['mode'])) {
  6096. $mode = $brd['mode'];
  6097. unset($brd['mode']);
  6098. } else {
  6099. $mode = 'normal';
  6100. }
  6101. foreach ($brd as $border => $style) {
  6102. if (is_array($style) AND !empty($style)) {
  6103. // apply border style
  6104. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  6105. $s .= $this->SetLineStyle($style, true)."\n";
  6106. }
  6107. switch ($mode) {
  6108. case 'ext': {
  6109. $off = (($this->LineWidth / 2) * $k);
  6110. $xL = $xeL - $off;
  6111. $xR = $xeR + $off;
  6112. $yT = $yeT + $off;
  6113. $yL = $yeL - $off;
  6114. $xT = $xL;
  6115. $xB = $xR;
  6116. $yR = $yT;
  6117. $yB = $yL;
  6118. $w += $this->LineWidth;
  6119. $h += $this->LineWidth;
  6120. break;
  6121. }
  6122. case 'int': {
  6123. $off = ($this->LineWidth / 2) * $k;
  6124. $xL = $xeL + $off;
  6125. $xR = $xeR - $off;
  6126. $yT = $yeT - $off;
  6127. $yL = $yeL + $off;
  6128. $xT = $xL;
  6129. $xB = $xR;
  6130. $yR = $yT;
  6131. $yB = $yL;
  6132. $w -= $this->LineWidth;
  6133. $h -= $this->LineWidth;
  6134. break;
  6135. }
  6136. case 'normal':
  6137. default: {
  6138. $xL = $xeL;
  6139. $xT = $xeT;
  6140. $xB = $xeB;
  6141. $xR = $xeR;
  6142. $yL = $yeL;
  6143. $yT = $yeT;
  6144. $yB = $yeB;
  6145. $yR = $yeR;
  6146. break;
  6147. }
  6148. }
  6149. // draw borders by case
  6150. if (strlen($border) == 4) {
  6151. $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  6152. } elseif (strlen($border) == 3) {
  6153. if (strpos($border,'B') === false) { // LTR
  6154. $s .= sprintf('%F %F m ', $xL, $yL);
  6155. $s .= sprintf('%F %F l ', $xT, $yT);
  6156. $s .= sprintf('%F %F l ', $xR, $yR);
  6157. $s .= sprintf('%F %F l ', $xB, $yB);
  6158. $s .= 'S ';
  6159. } elseif (strpos($border,'L') === false) { // TRB
  6160. $s .= sprintf('%F %F m ', $xT, $yT);
  6161. $s .= sprintf('%F %F l ', $xR, $yR);
  6162. $s .= sprintf('%F %F l ', $xB, $yB);
  6163. $s .= sprintf('%F %F l ', $xL, $yL);
  6164. $s .= 'S ';
  6165. } elseif (strpos($border,'T') === false) { // RBL
  6166. $s .= sprintf('%F %F m ', $xR, $yR);
  6167. $s .= sprintf('%F %F l ', $xB, $yB);
  6168. $s .= sprintf('%F %F l ', $xL, $yL);
  6169. $s .= sprintf('%F %F l ', $xT, $yT);
  6170. $s .= 'S ';
  6171. } elseif (strpos($border,'R') === false) { // BLT
  6172. $s .= sprintf('%F %F m ', $xB, $yB);
  6173. $s .= sprintf('%F %F l ', $xL, $yL);
  6174. $s .= sprintf('%F %F l ', $xT, $yT);
  6175. $s .= sprintf('%F %F l ', $xR, $yR);
  6176. $s .= 'S ';
  6177. }
  6178. } elseif (strlen($border) == 2) {
  6179. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  6180. $s .= sprintf('%F %F m ', $xL, $yL);
  6181. $s .= sprintf('%F %F l ', $xT, $yT);
  6182. $s .= sprintf('%F %F l ', $xR, $yR);
  6183. $s .= 'S ';
  6184. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  6185. $s .= sprintf('%F %F m ', $xT, $yT);
  6186. $s .= sprintf('%F %F l ', $xR, $yR);
  6187. $s .= sprintf('%F %F l ', $xB, $yB);
  6188. $s .= 'S ';
  6189. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  6190. $s .= sprintf('%F %F m ', $xR, $yR);
  6191. $s .= sprintf('%F %F l ', $xB, $yB);
  6192. $s .= sprintf('%F %F l ', $xL, $yL);
  6193. $s .= 'S ';
  6194. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  6195. $s .= sprintf('%F %F m ', $xB, $yB);
  6196. $s .= sprintf('%F %F l ', $xL, $yL);
  6197. $s .= sprintf('%F %F l ', $xT, $yT);
  6198. $s .= 'S ';
  6199. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  6200. $s .= sprintf('%F %F m ', $xL, $yL);
  6201. $s .= sprintf('%F %F l ', $xT, $yT);
  6202. $s .= 'S ';
  6203. $s .= sprintf('%F %F m ', $xR, $yR);
  6204. $s .= sprintf('%F %F l ', $xB, $yB);
  6205. $s .= 'S ';
  6206. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  6207. $s .= sprintf('%F %F m ', $xT, $yT);
  6208. $s .= sprintf('%F %F l ', $xR, $yR);
  6209. $s .= 'S ';
  6210. $s .= sprintf('%F %F m ', $xB, $yB);
  6211. $s .= sprintf('%F %F l ', $xL, $yL);
  6212. $s .= 'S ';
  6213. }
  6214. } else { // strlen($border) == 1
  6215. if (strpos($border,'L') !== false) { // L
  6216. $s .= sprintf('%F %F m ', $xL, $yL);
  6217. $s .= sprintf('%F %F l ', $xT, $yT);
  6218. $s .= 'S ';
  6219. } elseif (strpos($border,'T') !== false) { // T
  6220. $s .= sprintf('%F %F m ', $xT, $yT);
  6221. $s .= sprintf('%F %F l ', $xR, $yR);
  6222. $s .= 'S ';
  6223. } elseif (strpos($border,'R') !== false) { // R
  6224. $s .= sprintf('%F %F m ', $xR, $yR);
  6225. $s .= sprintf('%F %F l ', $xB, $yB);
  6226. $s .= 'S ';
  6227. } elseif (strpos($border,'B') !== false) { // B
  6228. $s .= sprintf('%F %F m ', $xB, $yB);
  6229. $s .= sprintf('%F %F l ', $xL, $yL);
  6230. $s .= 'S ';
  6231. }
  6232. }
  6233. if (is_array($style) AND !empty($style)) {
  6234. // reset border style to previous value
  6235. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  6236. }
  6237. }
  6238. return $s;
  6239. }
  6240. /**
  6241. * This method allows printing text with line breaks.
  6242. * 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 />
  6243. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  6244. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  6245. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  6246. * @param $txt (string) String to print
  6247. * @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)))
  6248. * @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>
  6249. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  6250. * @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>
  6251. * @param $x (float) x position in user units
  6252. * @param $y (float) y position in user units
  6253. * @param $reseth (boolean) if true reset the last cell height (default true).
  6254. * @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.
  6255. * @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.
  6256. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  6257. * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
  6258. * @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.
  6259. * @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).
  6260. * @return int Return the number of cells or 1 for html mode.
  6261. * @public
  6262. * @since 1.3
  6263. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  6264. */
  6265. 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) {
  6266. $prev_cell_margin = $this->cell_margin;
  6267. $prev_cell_padding = $this->cell_padding;
  6268. // adjust internal padding
  6269. $this->adjustCellPadding($border);
  6270. $mc_padding = $this->cell_padding;
  6271. $mc_margin = $this->cell_margin;
  6272. $this->cell_padding['T'] = 0;
  6273. $this->cell_padding['B'] = 0;
  6274. $this->setCellMargins(0, 0, 0, 0);
  6275. if ($this->empty_string($this->lasth) OR $reseth) {
  6276. // reset row height
  6277. $this->resetLastH();
  6278. }
  6279. if (!$this->empty_string($y)) {
  6280. $this->SetY($y);
  6281. } else {
  6282. $y = $this->GetY();
  6283. }
  6284. $resth = 0;
  6285. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  6286. // spit cell in more pages/columns
  6287. $newh = ($this->PageBreakTrigger - $y);
  6288. $resth = ($h - $newh); // cell to be printed on the next page/column
  6289. $h = $newh;
  6290. }
  6291. // get current page number
  6292. $startpage = $this->page;
  6293. // get current column
  6294. $startcolumn = $this->current_column;
  6295. if (!$this->empty_string($x)) {
  6296. $this->SetX($x);
  6297. } else {
  6298. $x = $this->GetX();
  6299. }
  6300. // check page for no-write regions and adapt page margins if necessary
  6301. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  6302. // apply margins
  6303. $oy = $y + $mc_margin['T'];
  6304. if ($this->rtl) {
  6305. $ox = $this->w - $x - $mc_margin['R'];
  6306. } else {
  6307. $ox = $x + $mc_margin['L'];
  6308. }
  6309. $this->x = $ox;
  6310. $this->y = $oy;
  6311. // set width
  6312. if ($this->empty_string($w) OR ($w <= 0)) {
  6313. if ($this->rtl) {
  6314. $w = $this->x - $this->lMargin - $mc_margin['L'];
  6315. } else {
  6316. $w = $this->w - $this->x - $this->rMargin - $mc_margin['R'];
  6317. }
  6318. }
  6319. // store original margin values
  6320. $lMargin = $this->lMargin;
  6321. $rMargin = $this->rMargin;
  6322. if ($this->rtl) {
  6323. $this->rMargin = $this->w - $this->x;
  6324. $this->lMargin = $this->x - $w;
  6325. } else {
  6326. $this->lMargin = $this->x;
  6327. $this->rMargin = $this->w - $this->x - $w;
  6328. }
  6329. if ($autopadding) {
  6330. // add top padding
  6331. $this->y += $mc_padding['T'];
  6332. }
  6333. if ($ishtml) { // ******* Write HTML text
  6334. $this->writeHTML($txt, true, false, $reseth, true, $align);
  6335. $nl = 1;
  6336. } else { // ******* Write simple text
  6337. $prev_FontSizePt = $this->FontSizePt;
  6338. // vertical alignment
  6339. if ($maxh > 0) {
  6340. // get text height
  6341. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  6342. if ($fitcell) {
  6343. // try to reduce font size to fit text on cell (use a quick search algorithm)
  6344. $fmin = 1;
  6345. $fmax = $this->FontSizePt;
  6346. $prev_text_height = $text_height;
  6347. $maxit = 100; // max number of iterations
  6348. while ($maxit > 0) {
  6349. $fmid = (($fmax + $fmin) / 2);
  6350. $this->SetFontSize($fmid, false);
  6351. $this->resetLastH();
  6352. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  6353. if (($text_height == $maxh) OR (($text_height < $maxh) AND ($fmin >= ($fmax - 0.01)))) {
  6354. break;
  6355. } elseif ($text_height < $maxh) {
  6356. $fmin = $fmid;
  6357. } else {
  6358. $fmax = $fmid;
  6359. }
  6360. --$maxit;
  6361. }
  6362. $this->SetFontSize($this->FontSizePt);
  6363. }
  6364. if ($text_height < $maxh) {
  6365. if ($valign == 'M') {
  6366. // text vertically centered
  6367. $this->y += (($maxh - $text_height) / 2);
  6368. } elseif ($valign == 'B') {
  6369. // text vertically aligned on bottom
  6370. $this->y += ($maxh - $text_height);
  6371. }
  6372. }
  6373. }
  6374. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  6375. if ($fitcell) {
  6376. // restore font size
  6377. $this->SetFontSize($prev_FontSizePt);
  6378. }
  6379. }
  6380. if ($autopadding) {
  6381. // add bottom padding
  6382. $this->y += $mc_padding['B'];
  6383. }
  6384. // Get end-of-text Y position
  6385. $currentY = $this->y;
  6386. // get latest page number
  6387. $endpage = $this->page;
  6388. if ($resth > 0) {
  6389. $skip = ($endpage - $startpage);
  6390. $tmpresth = $resth;
  6391. while ($tmpresth > 0) {
  6392. if ($skip <= 0) {
  6393. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  6394. $this->checkPageBreak($this->PageBreakTrigger + 1);
  6395. }
  6396. if ($this->num_columns > 1) {
  6397. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  6398. } else {
  6399. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  6400. }
  6401. --$skip;
  6402. }
  6403. $currentY = $this->y;
  6404. $endpage = $this->page;
  6405. }
  6406. // get latest column
  6407. $endcolumn = $this->current_column;
  6408. if ($this->num_columns == 0) {
  6409. $this->num_columns = 1;
  6410. }
  6411. // get border modes
  6412. $border_start = $this->getBorderMode($border, $position='start');
  6413. $border_end = $this->getBorderMode($border, $position='end');
  6414. $border_middle = $this->getBorderMode($border, $position='middle');
  6415. // design borders around HTML cells.
  6416. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  6417. $ccode = '';
  6418. $this->setPage($page);
  6419. if ($this->num_columns < 2) {
  6420. // single-column mode
  6421. $this->SetX($x);
  6422. $this->y = $this->tMargin;
  6423. }
  6424. // account for margin changes
  6425. if ($page > $startpage) {
  6426. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  6427. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  6428. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  6429. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  6430. }
  6431. }
  6432. if ($startpage == $endpage) {
  6433. // single page
  6434. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  6435. $this->selectColumn($column);
  6436. if ($this->rtl) {
  6437. $this->x -= $mc_margin['R'];
  6438. } else {
  6439. $this->x += $mc_margin['L'];
  6440. }
  6441. if ($startcolumn == $endcolumn) { // single column
  6442. $cborder = $border;
  6443. $h = max($h, ($currentY - $oy));
  6444. $this->y = $oy;
  6445. } elseif ($column == $startcolumn) { // first column
  6446. $cborder = $border_start;
  6447. $this->y = $oy;
  6448. $h = $this->h - $this->y - $this->bMargin;
  6449. } elseif ($column == $endcolumn) { // end column
  6450. $cborder = $border_end;
  6451. $h = $currentY - $this->y;
  6452. if ($resth > $h) {
  6453. $h = $resth;
  6454. }
  6455. } else { // middle column
  6456. $cborder = $border_middle;
  6457. $h = $this->h - $this->y - $this->bMargin;
  6458. $resth -= $h;
  6459. }
  6460. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6461. } // end for each column
  6462. } elseif ($page == $startpage) { // first page
  6463. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  6464. $this->selectColumn($column);
  6465. if ($this->rtl) {
  6466. $this->x -= $mc_margin['R'];
  6467. } else {
  6468. $this->x += $mc_margin['L'];
  6469. }
  6470. if ($column == $startcolumn) { // first column
  6471. $cborder = $border_start;
  6472. $this->y = $oy;
  6473. $h = $this->h - $this->y - $this->bMargin;
  6474. } else { // middle column
  6475. $cborder = $border_middle;
  6476. $h = $this->h - $this->y - $this->bMargin;
  6477. $resth -= $h;
  6478. }
  6479. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6480. } // end for each column
  6481. } elseif ($page == $endpage) { // last page
  6482. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  6483. $this->selectColumn($column);
  6484. if ($this->rtl) {
  6485. $this->x -= $mc_margin['R'];
  6486. } else {
  6487. $this->x += $mc_margin['L'];
  6488. }
  6489. if ($column == $endcolumn) {
  6490. // end column
  6491. $cborder = $border_end;
  6492. $h = $currentY - $this->y;
  6493. if ($resth > $h) {
  6494. $h = $resth;
  6495. }
  6496. } else {
  6497. // middle column
  6498. $cborder = $border_middle;
  6499. $h = $this->h - $this->y - $this->bMargin;
  6500. $resth -= $h;
  6501. }
  6502. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6503. } // end for each column
  6504. } else { // middle page
  6505. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  6506. $this->selectColumn($column);
  6507. if ($this->rtl) {
  6508. $this->x -= $mc_margin['R'];
  6509. } else {
  6510. $this->x += $mc_margin['L'];
  6511. }
  6512. $cborder = $border_middle;
  6513. $h = $this->h - $this->y - $this->bMargin;
  6514. $resth -= $h;
  6515. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  6516. } // end for each column
  6517. }
  6518. if ($cborder OR $fill) {
  6519. $offsetlen = strlen($ccode);
  6520. // draw border and fill
  6521. if ($this->inxobj) {
  6522. // we are inside an XObject template
  6523. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  6524. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  6525. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  6526. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  6527. } else {
  6528. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  6529. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  6530. }
  6531. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  6532. $pstart = substr($pagebuff, 0, $pagemark);
  6533. $pend = substr($pagebuff, $pagemark);
  6534. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  6535. } else {
  6536. if (end($this->transfmrk[$this->page]) !== false) {
  6537. $pagemarkkey = key($this->transfmrk[$this->page]);
  6538. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  6539. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  6540. } elseif ($this->InFooter) {
  6541. $pagemark = $this->footerpos[$this->page];
  6542. $this->footerpos[$this->page] += $offsetlen;
  6543. } else {
  6544. $pagemark = $this->intmrk[$this->page];
  6545. $this->intmrk[$this->page] += $offsetlen;
  6546. }
  6547. $pagebuff = $this->getPageBuffer($this->page);
  6548. $pstart = substr($pagebuff, 0, $pagemark);
  6549. $pend = substr($pagebuff, $pagemark);
  6550. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  6551. }
  6552. }
  6553. } // end for each page
  6554. // Get end-of-cell Y position
  6555. $currentY = $this->GetY();
  6556. // restore previous values
  6557. if ($this->num_columns > 1) {
  6558. $this->selectColumn();
  6559. } else {
  6560. // restore original margins
  6561. $this->lMargin = $lMargin;
  6562. $this->rMargin = $rMargin;
  6563. if ($this->page > $startpage) {
  6564. // check for margin variations between pages (i.e. booklet mode)
  6565. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  6566. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  6567. if (($dl != 0) OR ($dr != 0)) {
  6568. $this->lMargin += $dl;
  6569. $this->rMargin += $dr;
  6570. }
  6571. }
  6572. }
  6573. if ($ln > 0) {
  6574. //Go to the beginning of the next line
  6575. $this->SetY($currentY + $mc_margin['B']);
  6576. if ($ln == 2) {
  6577. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  6578. }
  6579. } else {
  6580. // go left or right by case
  6581. $this->setPage($startpage);
  6582. $this->y = $y;
  6583. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  6584. }
  6585. $this->setContentMark();
  6586. $this->cell_padding = $prev_cell_padding;
  6587. $this->cell_margin = $prev_cell_margin;
  6588. return $nl;
  6589. }
  6590. /**
  6591. * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
  6592. * @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)))
  6593. * @param $position (string) multicell position: 'start', 'middle', 'end'
  6594. * @return border mode array
  6595. * @protected
  6596. * @since 4.4.002 (2008-12-09)
  6597. */
  6598. protected function getBorderMode($brd, $position='start') {
  6599. if ((!$this->opencell) OR empty($brd)) {
  6600. return $brd;
  6601. }
  6602. if ($brd == 1) {
  6603. $brd = 'LTRB';
  6604. }
  6605. if (is_string($brd)) {
  6606. // convert string to array
  6607. $slen = strlen($brd);
  6608. $newbrd = array();
  6609. for ($i = 0; $i < $slen; ++$i) {
  6610. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  6611. }
  6612. $brd = $newbrd;
  6613. }
  6614. foreach ($brd as $border => $style) {
  6615. switch ($position) {
  6616. case 'start': {
  6617. if (strpos($border, 'B') !== false) {
  6618. // remove bottom line
  6619. $newkey = str_replace('B', '', $border);
  6620. if (strlen($newkey) > 0) {
  6621. $brd[$newkey] = $style;
  6622. }
  6623. unset($brd[$border]);
  6624. }
  6625. break;
  6626. }
  6627. case 'middle': {
  6628. if (strpos($border, 'B') !== false) {
  6629. // remove bottom line
  6630. $newkey = str_replace('B', '', $border);
  6631. if (strlen($newkey) > 0) {
  6632. $brd[$newkey] = $style;
  6633. }
  6634. unset($brd[$border]);
  6635. $border = $newkey;
  6636. }
  6637. if (strpos($border, 'T') !== false) {
  6638. // remove bottom line
  6639. $newkey = str_replace('T', '', $border);
  6640. if (strlen($newkey) > 0) {
  6641. $brd[$newkey] = $style;
  6642. }
  6643. unset($brd[$border]);
  6644. }
  6645. break;
  6646. }
  6647. case 'end': {
  6648. if (strpos($border, 'T') !== false) {
  6649. // remove bottom line
  6650. $newkey = str_replace('T', '', $border);
  6651. if (strlen($newkey) > 0) {
  6652. $brd[$newkey] = $style;
  6653. }
  6654. unset($brd[$border]);
  6655. }
  6656. break;
  6657. }
  6658. }
  6659. }
  6660. return $brd;
  6661. }
  6662. /**
  6663. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  6664. * @param $txt (string) String for calculating his height
  6665. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  6666. * @param $reseth (boolean) if true reset the last cell height (default false).
  6667. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  6668. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  6669. * @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)))
  6670. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  6671. * @author Alexander Escalona Fernández, Nicola Asuni
  6672. * @public
  6673. * @since 4.5.011
  6674. */
  6675. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  6676. if ($txt === '') {
  6677. // empty string
  6678. return 1;
  6679. }
  6680. // adjust internal padding
  6681. $prev_cell_padding = $this->cell_padding;
  6682. $prev_lasth = $this->lasth;
  6683. if (is_array($cellpadding)) {
  6684. $this->cell_padding = $cellpadding;
  6685. }
  6686. $this->adjustCellPadding($border);
  6687. if ($this->empty_string($w) OR ($w <= 0)) {
  6688. if ($this->rtl) {
  6689. $w = $this->x - $this->lMargin;
  6690. } else {
  6691. $w = $this->w - $this->rMargin - $this->x;
  6692. }
  6693. }
  6694. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6695. if ($reseth) {
  6696. // reset row height
  6697. $this->resetLastH();
  6698. }
  6699. $lines = 1;
  6700. $sum = 0;
  6701. $chars = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl);
  6702. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  6703. $length = count($chars);
  6704. $lastSeparator = -1;
  6705. for ($i = 0; $i < $length; ++$i) {
  6706. $charWidth = $charsWidth[$i];
  6707. if (preg_match($this->re_spaces, $this->unichr($chars[$i]))) {
  6708. $lastSeparator = $i;
  6709. }
  6710. if ((($sum + $charWidth) > $wmax) OR ($chars[$i] == 10)) {
  6711. ++$lines;
  6712. if ($chars[$i] == 10) {
  6713. $lastSeparator = -1;
  6714. $sum = 0;
  6715. } elseif ($lastSeparator != -1) {
  6716. $i = $lastSeparator;
  6717. $lastSeparator = -1;
  6718. $sum = 0;
  6719. } else {
  6720. $sum = $charWidth;
  6721. }
  6722. } else {
  6723. $sum += $charWidth;
  6724. }
  6725. }
  6726. if ($chars[($length - 1)] == 10) {
  6727. --$lines;
  6728. }
  6729. $this->cell_padding = $prev_cell_padding;
  6730. $this->lasth = $prev_lasth;
  6731. return $lines;
  6732. }
  6733. /**
  6734. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  6735. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  6736. * @pre
  6737. * // store current object
  6738. * $pdf->startTransaction();
  6739. * // store starting values
  6740. * $start_y = $pdf->GetY();
  6741. * $start_page = $pdf->getPage();
  6742. * // call your printing functions with your parameters
  6743. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6744. * $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);
  6745. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6746. * // get the new Y
  6747. * $end_y = $pdf->GetY();
  6748. * $end_page = $pdf->getPage();
  6749. * // calculate height
  6750. * $height = 0;
  6751. * if ($end_page == $start_page) {
  6752. * $height = $end_y - $start_y;
  6753. * } else {
  6754. * for ($page=$start_page; $page <= $end_page; ++$page) {
  6755. * $this->setPage($page);
  6756. * if ($page == $start_page) {
  6757. * // first page
  6758. * $height = $this->h - $start_y - $this->bMargin;
  6759. * } elseif ($page == $end_page) {
  6760. * // last page
  6761. * $height = $end_y - $this->tMargin;
  6762. * } else {
  6763. * $height = $this->h - $this->tMargin - $this->bMargin;
  6764. * }
  6765. * }
  6766. * }
  6767. * // restore previous object
  6768. * $pdf = $pdf->rollbackTransaction();
  6769. *
  6770. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  6771. * @param $txt (string) String for calculating his height
  6772. * @param $reseth (boolean) if true reset the last cell height (default false).
  6773. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  6774. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  6775. * @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)))
  6776. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  6777. * @author Nicola Asuni, Alexander Escalona Fernández
  6778. * @public
  6779. */
  6780. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  6781. // adjust internal padding
  6782. $prev_cell_padding = $this->cell_padding;
  6783. $prev_lasth = $this->lasth;
  6784. if (is_array($cellpadding)) {
  6785. $this->cell_padding = $cellpadding;
  6786. }
  6787. $this->adjustCellPadding($border);
  6788. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  6789. $height = $lines * ($this->FontSize * $this->cell_height_ratio);
  6790. if ($autopadding) {
  6791. // add top and bottom padding
  6792. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  6793. }
  6794. $this->cell_padding = $prev_cell_padding;
  6795. $this->lasth = $prev_lasth;
  6796. return $height;
  6797. }
  6798. /**
  6799. * This method prints text from the current position.<br />
  6800. * @param $h (float) Line height
  6801. * @param $txt (string) String to print
  6802. * @param $link (mixed) URL or identifier returned by AddLink()
  6803. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  6804. * @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>
  6805. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  6806. * @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.
  6807. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  6808. * @param $firstblock (boolean) if true the string is the starting of a line.
  6809. * @param $maxh (float) maximum height. The remaining unprinted text will be returned. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
  6810. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  6811. * @param $margin (array) margin array of the parent container
  6812. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  6813. * @public
  6814. * @since 1.5
  6815. */
  6816. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  6817. // check page for no-write regions and adapt page margins if necessary
  6818. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  6819. if (strlen($txt) == 0) {
  6820. // fix empty text
  6821. $txt = ' ';
  6822. }
  6823. if ($margin === '') {
  6824. // set default margins
  6825. $margin = $this->cell_margin;
  6826. }
  6827. // remove carriage returns
  6828. $s = str_replace("\r", '', $txt);
  6829. // check if string contains arabic text
  6830. if (preg_match($this->unicode->uni_RE_PATTERN_ARABIC, $s)) {
  6831. $arabic = true;
  6832. } else {
  6833. $arabic = false;
  6834. }
  6835. // check if string contains RTL text
  6836. if ($arabic OR ($this->tmprtl == 'R') OR preg_match($this->unicode->uni_RE_PATTERN_RTL, $s)) {
  6837. $rtlmode = true;
  6838. } else {
  6839. $rtlmode = false;
  6840. }
  6841. // get a char width
  6842. $chrwidth = $this->GetCharWidth(46); // dot character
  6843. // get array of unicode values
  6844. $chars = $this->UTF8StringToArray($s);
  6845. // get array of chars
  6846. $uchars = $this->UTF8ArrayToUniArray($chars);
  6847. // get the number of characters
  6848. $nb = count($chars);
  6849. // replacement for SHY character (minus symbol)
  6850. $shy_replacement = 45;
  6851. $shy_replacement_char = $this->unichr($shy_replacement);
  6852. // widht for SHY replacement
  6853. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  6854. // max Y
  6855. $maxy = $this->y + $maxh - $h - $this->cell_padding['T'] - $this->cell_padding['B'];
  6856. // page width
  6857. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  6858. // calculate remaining line width ($w)
  6859. if ($this->rtl) {
  6860. $w = $this->x - $this->lMargin;
  6861. } else {
  6862. $w = $this->w - $this->rMargin - $this->x;
  6863. }
  6864. // max column width
  6865. $wmax = ($w - $wadj);
  6866. if (!$firstline) {
  6867. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  6868. }
  6869. if ((!$firstline) AND (($chrwidth > $wmax) OR ($this->GetCharWidth($chars[0]) > $wmax))) {
  6870. // a single character do not fit on column
  6871. return '';
  6872. }
  6873. // minimum row height
  6874. $row_height = max($h, $this->FontSize * $this->cell_height_ratio);
  6875. $start_page = $this->page;
  6876. $i = 0; // character position
  6877. $j = 0; // current starting position
  6878. $sep = -1; // position of the last blank space
  6879. $shy = false; // true if the last blank is a soft hypen (SHY)
  6880. $l = 0; // current string length
  6881. $nl = 0; //number of lines
  6882. $linebreak = false;
  6883. $pc = 0; // previous character
  6884. // for each character
  6885. while ($i < $nb) {
  6886. if (($maxh > 0) AND ($this->y >= $maxy) ) {
  6887. break;
  6888. }
  6889. //Get the current character
  6890. $c = $chars[$i];
  6891. if ($c == 10) { // 10 = "\n" = new line
  6892. //Explicit line break
  6893. if ($align == 'J') {
  6894. if ($this->rtl) {
  6895. $talign = 'R';
  6896. } else {
  6897. $talign = 'L';
  6898. }
  6899. } else {
  6900. $talign = $align;
  6901. }
  6902. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  6903. if ($firstline) {
  6904. $startx = $this->x;
  6905. $tmparr = array_slice($chars, $j, ($i - $j));
  6906. if ($rtlmode) {
  6907. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  6908. }
  6909. $linew = $this->GetArrStringWidth($tmparr);
  6910. unset($tmparr);
  6911. if ($this->rtl) {
  6912. $this->endlinex = $startx - $linew;
  6913. } else {
  6914. $this->endlinex = $startx + $linew;
  6915. }
  6916. $w = $linew;
  6917. $tmpcellpadding = $this->cell_padding;
  6918. if ($maxh == 0) {
  6919. $this->SetCellPadding(0);
  6920. }
  6921. }
  6922. if ($firstblock AND $this->isRTLTextDir()) {
  6923. $tmpstr = $this->stringRightTrim($tmpstr);
  6924. }
  6925. // Skip newlines at the begining of a page or column
  6926. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6927. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6928. }
  6929. unset($tmpstr);
  6930. if ($firstline) {
  6931. $this->cell_padding = $tmpcellpadding;
  6932. return ($this->UniArrSubString($uchars, $i));
  6933. }
  6934. ++$nl;
  6935. $j = $i + 1;
  6936. $l = 0;
  6937. $sep = -1;
  6938. $shy = false;
  6939. // account for margin changes
  6940. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6941. $this->AcceptPageBreak();
  6942. if ($this->rtl) {
  6943. $this->x -= $margin['R'];
  6944. } else {
  6945. $this->x += $margin['L'];
  6946. }
  6947. $this->lMargin += $margin['L'];
  6948. $this->rMargin += $margin['R'];
  6949. }
  6950. $w = $this->getRemainingWidth();
  6951. $wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
  6952. } else {
  6953. // 160 is the non-breaking space.
  6954. // 173 is SHY (Soft Hypen).
  6955. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6956. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6957. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6958. if (($c != 160)
  6959. AND (($c == 173)
  6960. OR preg_match($this->re_spaces, $this->unichr($c))
  6961. OR (($c == 45)
  6962. AND ($i < ($nb - 1))
  6963. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], $this->unichr($pc))
  6964. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], $this->unichr($chars[($i + 1)]))
  6965. )
  6966. )
  6967. ) {
  6968. // update last blank space position
  6969. $sep = $i;
  6970. // check if is a SHY
  6971. if (($c == 173) OR ($c == 45)) {
  6972. $shy = true;
  6973. if ($pc == 45) {
  6974. $tmp_shy_replacement_width = 0;
  6975. $tmp_shy_replacement_char = '';
  6976. } else {
  6977. $tmp_shy_replacement_width = $shy_replacement_width;
  6978. $tmp_shy_replacement_char = $shy_replacement_char;
  6979. }
  6980. } else {
  6981. $shy = false;
  6982. }
  6983. }
  6984. // update string length
  6985. if ($this->isUnicodeFont() AND ($arabic)) {
  6986. // with bidirectional algorithm some chars may be changed affecting the line length
  6987. // *** very slow ***
  6988. $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl));
  6989. } else {
  6990. $l += $this->GetCharWidth($c);
  6991. }
  6992. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) ) {
  6993. // we have reached the end of column
  6994. if ($sep == -1) {
  6995. // check if the line was already started
  6996. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
  6997. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
  6998. // print a void cell and go to next line
  6999. $this->Cell($w, $h, '', 0, 1);
  7000. $linebreak = true;
  7001. if ($firstline) {
  7002. return ($this->UniArrSubString($uchars, $j));
  7003. }
  7004. } else {
  7005. // truncate the word because do not fit on column
  7006. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  7007. if ($firstline) {
  7008. $startx = $this->x;
  7009. $tmparr = array_slice($chars, $j, ($i - $j));
  7010. if ($rtlmode) {
  7011. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  7012. }
  7013. $linew = $this->GetArrStringWidth($tmparr);
  7014. unset($tmparr);
  7015. if ($this->rtl) {
  7016. $this->endlinex = $startx - $linew;
  7017. } else {
  7018. $this->endlinex = $startx + $linew;
  7019. }
  7020. $w = $linew;
  7021. $tmpcellpadding = $this->cell_padding;
  7022. if ($maxh == 0) {
  7023. $this->SetCellPadding(0);
  7024. }
  7025. }
  7026. if ($firstblock AND $this->isRTLTextDir()) {
  7027. $tmpstr = $this->stringRightTrim($tmpstr);
  7028. }
  7029. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  7030. unset($tmpstr);
  7031. if ($firstline) {
  7032. $this->cell_padding = $tmpcellpadding;
  7033. return ($this->UniArrSubString($uchars, $i));
  7034. }
  7035. $j = $i;
  7036. --$i;
  7037. }
  7038. } else {
  7039. // word wrapping
  7040. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  7041. $endspace = 1;
  7042. } else {
  7043. $endspace = 0;
  7044. }
  7045. // check the length of the next string
  7046. $strrest = $this->UniArrSubString($uchars, ($sep + $endspace));
  7047. $nextstr = preg_split('/'.$this->re_space['p'].'/'.$this->re_space['m'], $this->stringTrim($strrest));
  7048. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  7049. // truncate the word because do not fit on a full page width
  7050. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  7051. if ($firstline) {
  7052. $startx = $this->x;
  7053. $tmparr = array_slice($chars, $j, ($i - $j));
  7054. if ($rtlmode) {
  7055. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  7056. }
  7057. $linew = $this->GetArrStringWidth($tmparr);
  7058. unset($tmparr);
  7059. if ($this->rtl) {
  7060. $this->endlinex = ($startx - $linew);
  7061. } else {
  7062. $this->endlinex = ($startx + $linew);
  7063. }
  7064. $w = $linew;
  7065. $tmpcellpadding = $this->cell_padding;
  7066. if ($maxh == 0) {
  7067. $this->SetCellPadding(0);
  7068. }
  7069. }
  7070. if ($firstblock AND $this->isRTLTextDir()) {
  7071. $tmpstr = $this->stringRightTrim($tmpstr);
  7072. }
  7073. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  7074. unset($tmpstr);
  7075. if ($firstline) {
  7076. $this->cell_padding = $tmpcellpadding;
  7077. return ($this->UniArrSubString($uchars, $i));
  7078. }
  7079. $j = $i;
  7080. --$i;
  7081. } else {
  7082. // word wrapping
  7083. if ($shy) {
  7084. // add hypen (minus symbol) at the end of the line
  7085. $shy_width = $tmp_shy_replacement_width;
  7086. if ($this->rtl) {
  7087. $shy_char_left = $tmp_shy_replacement_char;
  7088. $shy_char_right = '';
  7089. } else {
  7090. $shy_char_left = '';
  7091. $shy_char_right = $tmp_shy_replacement_char;
  7092. }
  7093. } else {
  7094. $shy_width = 0;
  7095. $shy_char_left = '';
  7096. $shy_char_right = '';
  7097. }
  7098. $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
  7099. if ($firstline) {
  7100. $startx = $this->x;
  7101. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  7102. if ($rtlmode) {
  7103. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  7104. }
  7105. $linew = $this->GetArrStringWidth($tmparr);
  7106. unset($tmparr);
  7107. if ($this->rtl) {
  7108. $this->endlinex = $startx - $linew - $shy_width;
  7109. } else {
  7110. $this->endlinex = $startx + $linew + $shy_width;
  7111. }
  7112. $w = $linew;
  7113. $tmpcellpadding = $this->cell_padding;
  7114. if ($maxh == 0) {
  7115. $this->SetCellPadding(0);
  7116. }
  7117. }
  7118. // print the line
  7119. if ($firstblock AND $this->isRTLTextDir()) {
  7120. $tmpstr = $this->stringRightTrim($tmpstr);
  7121. }
  7122. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  7123. unset($tmpstr);
  7124. if ($firstline) {
  7125. if ($chars[$sep] == 45) {
  7126. $endspace += 1;
  7127. }
  7128. // return the remaining text
  7129. $this->cell_padding = $tmpcellpadding;
  7130. return ($this->UniArrSubString($uchars, ($sep + $endspace)));
  7131. }
  7132. $i = $sep;
  7133. $sep = -1;
  7134. $shy = false;
  7135. $j = ($i + 1);
  7136. }
  7137. }
  7138. // account for margin changes
  7139. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  7140. $this->AcceptPageBreak();
  7141. if ($this->rtl) {
  7142. $this->x -= $margin['R'];
  7143. } else {
  7144. $this->x += $margin['L'];
  7145. }
  7146. $this->lMargin += $margin['L'];
  7147. $this->rMargin += $margin['R'];
  7148. }
  7149. $w = $this->getRemainingWidth();
  7150. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  7151. if ($linebreak) {
  7152. $linebreak = false;
  7153. } else {
  7154. ++$nl;
  7155. $l = 0;
  7156. }
  7157. }
  7158. }
  7159. // save last character
  7160. $pc = $c;
  7161. ++$i;
  7162. } // end while i < nb
  7163. // print last substring (if any)
  7164. if ($l > 0) {
  7165. switch ($align) {
  7166. case 'J':
  7167. case 'C': {
  7168. $w = $w;
  7169. break;
  7170. }
  7171. case 'L': {
  7172. if ($this->rtl) {
  7173. $w = $w;
  7174. } else {
  7175. $w = $l;
  7176. }
  7177. break;
  7178. }
  7179. case 'R': {
  7180. if ($this->rtl) {
  7181. $w = $l;
  7182. } else {
  7183. $w = $w;
  7184. }
  7185. break;
  7186. }
  7187. default: {
  7188. $w = $l;
  7189. break;
  7190. }
  7191. }
  7192. $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
  7193. if ($firstline) {
  7194. $startx = $this->x;
  7195. $tmparr = array_slice($chars, $j, ($nb - $j));
  7196. if ($rtlmode) {
  7197. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  7198. }
  7199. $linew = $this->GetArrStringWidth($tmparr);
  7200. unset($tmparr);
  7201. if ($this->rtl) {
  7202. $this->endlinex = $startx - $linew;
  7203. } else {
  7204. $this->endlinex = $startx + $linew;
  7205. }
  7206. $w = $linew;
  7207. $tmpcellpadding = $this->cell_padding;
  7208. if ($maxh == 0) {
  7209. $this->SetCellPadding(0);
  7210. }
  7211. }
  7212. if ($firstblock AND $this->isRTLTextDir()) {
  7213. $tmpstr = $this->stringRightTrim($tmpstr);
  7214. }
  7215. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  7216. unset($tmpstr);
  7217. if ($firstline) {
  7218. $this->cell_padding = $tmpcellpadding;
  7219. return ($this->UniArrSubString($uchars, $nb));
  7220. }
  7221. ++$nl;
  7222. }
  7223. if ($firstline) {
  7224. return '';
  7225. }
  7226. return $nl;
  7227. }
  7228. /**
  7229. * Returns the remaining width between the current position and margins.
  7230. * @return int Return the remaining width
  7231. * @protected
  7232. */
  7233. protected function getRemainingWidth() {
  7234. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  7235. if ($this->rtl) {
  7236. return ($this->x - $this->lMargin);
  7237. } else {
  7238. return ($this->w - $this->rMargin - $this->x);
  7239. }
  7240. }
  7241. /**
  7242. * Extract a slice of the $strarr array and return it as string.
  7243. * @param $strarr (string) The input array of characters.
  7244. * @param $start (int) the starting element of $strarr.
  7245. * @param $end (int) first element that will not be returned.
  7246. * @return Return part of a string
  7247. * @public
  7248. */
  7249. public function UTF8ArrSubString($strarr, $start='', $end='') {
  7250. if (strlen($start) == 0) {
  7251. $start = 0;
  7252. }
  7253. if (strlen($end) == 0) {
  7254. $end = count($strarr);
  7255. }
  7256. $string = '';
  7257. for ($i=$start; $i < $end; ++$i) {
  7258. $string .= $this->unichr($strarr[$i]);
  7259. }
  7260. return $string;
  7261. }
  7262. /**
  7263. * Extract a slice of the $uniarr array and return it as string.
  7264. * @param $uniarr (string) The input array of characters.
  7265. * @param $start (int) the starting element of $strarr.
  7266. * @param $end (int) first element that will not be returned.
  7267. * @return Return part of a string
  7268. * @public
  7269. * @since 4.5.037 (2009-04-07)
  7270. */
  7271. public function UniArrSubString($uniarr, $start='', $end='') {
  7272. if (strlen($start) == 0) {
  7273. $start = 0;
  7274. }
  7275. if (strlen($end) == 0) {
  7276. $end = count($uniarr);
  7277. }
  7278. $string = '';
  7279. for ($i=$start; $i < $end; ++$i) {
  7280. $string .= $uniarr[$i];
  7281. }
  7282. return $string;
  7283. }
  7284. /**
  7285. * Convert an array of UTF8 values to array of unicode characters
  7286. * @param $ta (string) The input array of UTF8 values.
  7287. * @return Return array of unicode characters
  7288. * @public
  7289. * @since 4.5.037 (2009-04-07)
  7290. */
  7291. public function UTF8ArrayToUniArray($ta) {
  7292. return array_map(array($this, 'unichr'), $ta);
  7293. }
  7294. /**
  7295. * Returns the unicode caracter specified by UTF-8 value
  7296. * @param $c (int) UTF-8 value
  7297. * @return Returns the specified character.
  7298. * @author Miguel Perez, Nicola Asuni
  7299. * @public
  7300. * @since 2.3.000 (2008-03-05)
  7301. */
  7302. public function unichr($c) {
  7303. if (!$this->isunicode) {
  7304. return chr($c);
  7305. } elseif ($c <= 0x7F) {
  7306. // one byte
  7307. return chr($c);
  7308. } elseif ($c <= 0x7FF) {
  7309. // two bytes
  7310. return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
  7311. } elseif ($c <= 0xFFFF) {
  7312. // three bytes
  7313. return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  7314. } elseif ($c <= 0x10FFFF) {
  7315. // four bytes
  7316. return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  7317. } else {
  7318. return '';
  7319. }
  7320. }
  7321. /**
  7322. * Return the image type given the file name or array returned by getimagesize() function.
  7323. * @param $imgfile (string) image file name
  7324. * @param $iminfo (array) array of image information returned by getimagesize() function.
  7325. * @return string image type
  7326. * @since 4.8.017 (2009-11-27)
  7327. */
  7328. public function getImageFileType($imgfile, $iminfo=array()) {
  7329. $type = '';
  7330. if (isset($iminfo['mime']) AND !empty($iminfo['mime'])) {
  7331. $mime = explode('/', $iminfo['mime']);
  7332. if ((count($mime) > 1) AND ($mime[0] == 'image') AND (!empty($mime[1]))) {
  7333. $type = strtolower(trim($mime[1]));
  7334. }
  7335. }
  7336. if (empty($type)) {
  7337. $fileinfo = pathinfo($imgfile);
  7338. if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
  7339. $type = strtolower(trim($fileinfo['extension']));
  7340. }
  7341. }
  7342. if ($type == 'jpg') {
  7343. $type = 'jpeg';
  7344. }
  7345. return $type;
  7346. }
  7347. /**
  7348. * Set the block dimensions accounting for page breaks and page/column fitting
  7349. * @param $w (float) width
  7350. * @param $h (float) height
  7351. * @param $x (float) X coordinate
  7352. * @param $y (float) Y coodiante
  7353. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  7354. * @return array($w, $h, $x, $y)
  7355. * @protected
  7356. * @since 5.5.009 (2010-07-05)
  7357. */
  7358. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  7359. if ($w <= 0) {
  7360. // set maximum width
  7361. $w = ($this->w - $this->lMargin - $this->rMargin);
  7362. }
  7363. if ($h <= 0) {
  7364. // set maximum height
  7365. $h = ($this->PageBreakTrigger - $this->tMargin);
  7366. }
  7367. // resize the block to be vertically contained on a single page or single column
  7368. if ($fitonpage OR $this->AutoPageBreak) {
  7369. $ratio_wh = ($w / $h);
  7370. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  7371. $h = $this->PageBreakTrigger - $this->tMargin;
  7372. $w = ($h * $ratio_wh);
  7373. }
  7374. // resize the block to be horizontally contained on a single page or single column
  7375. if ($fitonpage) {
  7376. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  7377. if ($w > $maxw) {
  7378. $w = $maxw;
  7379. $h = ($w / $ratio_wh);
  7380. }
  7381. }
  7382. }
  7383. // Check whether we need a new page or new column first as this does not fit
  7384. $prev_x = $this->x;
  7385. $prev_y = $this->y;
  7386. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  7387. $y = $this->y;
  7388. if ($this->rtl) {
  7389. $x += ($prev_x - $this->x);
  7390. } else {
  7391. $x += ($this->x - $prev_x);
  7392. }
  7393. $this->newline = true;
  7394. }
  7395. // resize the block to be contained on the remaining available page or column space
  7396. if ($fitonpage) {
  7397. $ratio_wh = ($w / $h);
  7398. if (($y + $h) > $this->PageBreakTrigger) {
  7399. $h = $this->PageBreakTrigger - $y;
  7400. $w = ($h * $ratio_wh);
  7401. }
  7402. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  7403. $w = $this->w - $this->rMargin - $x;
  7404. $h = ($w / $ratio_wh);
  7405. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  7406. $w = $x - $this->lMargin;
  7407. $h = ($w / $ratio_wh);
  7408. }
  7409. }
  7410. return array($w, $h, $x, $y);
  7411. }
  7412. /**
  7413. * Puts an image in the page.
  7414. * The upper-left corner must be given.
  7415. * The dimensions can be specified in different ways:<ul>
  7416. * <li>explicit width and height (expressed in user unit)</li>
  7417. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  7418. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  7419. * 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;
  7420. * The format can be specified explicitly or inferred from the file extension.<br />
  7421. * It is possible to put a link on the image.<br />
  7422. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  7423. * @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').
  7424. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  7425. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  7426. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  7427. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  7428. * @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.
  7429. * @param $link (mixed) URL or identifier returned by AddLink().
  7430. * @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>
  7431. * @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).
  7432. * @param $dpi (int) dot-per-inch resolution used on resize
  7433. * @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>
  7434. * @param $ismask (boolean) true if this image is a mask, false otherwise
  7435. * @param $imgmask (mixed) image object returned by this function or false
  7436. * @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)))
  7437. * @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).
  7438. * @param $hidden (boolean) If true do not display the image.
  7439. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  7440. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  7441. * @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.
  7442. * @return image information
  7443. * @public
  7444. * @since 1.1
  7445. */
  7446. 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()) {
  7447. if ($x === '') {
  7448. $x = $this->x;
  7449. }
  7450. if ($y === '') {
  7451. $y = $this->y;
  7452. }
  7453. // check page for no-write regions and adapt page margins if necessary
  7454. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  7455. $cached_file = false; // true when the file is cached
  7456. $exurl = ''; // external streams
  7457. // check if we are passing an image as file or string
  7458. if ($file[0] === '@') {
  7459. // image from string
  7460. $imgdata = substr($file, 1);
  7461. $file = $this->getObjFilename('img');
  7462. $fp = fopen($file, 'w');
  7463. fwrite($fp, $imgdata);
  7464. fclose($fp);
  7465. unset($imgdata);
  7466. $cached_file = true;
  7467. $imsize = @getimagesize($file);
  7468. if ($imsize === FALSE) {
  7469. unlink($file);
  7470. $cached_file = false;
  7471. }
  7472. } else { // image file
  7473. if ($file{0} === '*') {
  7474. // image as external stream
  7475. $file = substr($file, 1);
  7476. $exurl = $file;
  7477. }
  7478. // check if is local file
  7479. if (!@file_exists($file)) {
  7480. // encode spaces on filename (file is probably an URL)
  7481. $file = str_replace(' ', '%20', $file);
  7482. }
  7483. if (@file_exists($file)) {
  7484. // get image dimensions
  7485. $imsize = @getimagesize($file);
  7486. } else {
  7487. $imsize = false;
  7488. }
  7489. if ($imsize === FALSE) {
  7490. if (function_exists('curl_init')) {
  7491. // try to get remote file data using cURL
  7492. $cs = curl_init(); // curl session
  7493. curl_setopt($cs, CURLOPT_URL, $file);
  7494. curl_setopt($cs, CURLOPT_BINARYTRANSFER, true);
  7495. curl_setopt($cs, CURLOPT_FAILONERROR, true);
  7496. curl_setopt($cs, CURLOPT_RETURNTRANSFER, true);
  7497. if ((ini_get('open_basedir') == '') AND (ini_get('safe_mode') == 'Off')) {
  7498. curl_setopt($cs, CURLOPT_FOLLOWLOCATION, true);
  7499. }
  7500. curl_setopt($cs, CURLOPT_CONNECTTIMEOUT, 5);
  7501. curl_setopt($cs, CURLOPT_TIMEOUT, 30);
  7502. curl_setopt($cs, CURLOPT_SSL_VERIFYPEER, false);
  7503. curl_setopt($cs, CURLOPT_SSL_VERIFYHOST, false);
  7504. curl_setopt($cs, CURLOPT_USERAGENT, 'TCPDF');
  7505. $imgdata = curl_exec($cs);
  7506. curl_close($cs);
  7507. if ($imgdata !== FALSE) {
  7508. // copy image to cache
  7509. $file = $this->getObjFilename('img');
  7510. $fp = fopen($file, 'w');
  7511. fwrite($fp, $imgdata);
  7512. fclose($fp);
  7513. unset($imgdata);
  7514. $cached_file = true;
  7515. $imsize = @getimagesize($file);
  7516. if ($imsize === FALSE) {
  7517. unlink($file);
  7518. $cached_file = false;
  7519. }
  7520. }
  7521. } elseif (($w > 0) AND ($h > 0)) {
  7522. // get measures from specified data
  7523. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7524. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7525. $imsize = array($pw, $ph);
  7526. }
  7527. }
  7528. }
  7529. if ($imsize === FALSE) {
  7530. if (substr($file, 0, -34) == K_PATH_CACHE.'msk') { // mask file
  7531. // get measures from specified data
  7532. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7533. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  7534. $imsize = array($pw, $ph);
  7535. } else {
  7536. $this->Error('[Image] Unable to get image: '.$file);
  7537. }
  7538. }
  7539. // file hash
  7540. $filehash = md5($this->file_id.$file);
  7541. // get original image width and height in pixels
  7542. list($pixw, $pixh) = $imsize;
  7543. // calculate image width and height on document
  7544. if (($w <= 0) AND ($h <= 0)) {
  7545. // convert image size to document unit
  7546. $w = $this->pixelsToUnits($pixw);
  7547. $h = $this->pixelsToUnits($pixh);
  7548. } elseif ($w <= 0) {
  7549. $w = $h * $pixw / $pixh;
  7550. } elseif ($h <= 0) {
  7551. $h = $w * $pixh / $pixw;
  7552. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  7553. if (strlen($fitbox) !== 2) {
  7554. // set default alignment
  7555. $fitbox = '--';
  7556. }
  7557. // scale image dimensions proportionally to fit within the ($w, $h) box
  7558. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  7559. // store current height
  7560. $oldh = $h;
  7561. // calculate new height
  7562. $h = $w * $pixh / $pixw;
  7563. // height difference
  7564. $hdiff = ($oldh - $h);
  7565. // vertical alignment
  7566. switch (strtoupper($fitbox{1})) {
  7567. case 'T': {
  7568. break;
  7569. }
  7570. case 'M': {
  7571. $y += ($hdiff / 2);
  7572. break;
  7573. }
  7574. case 'B': {
  7575. $y += $hdiff;
  7576. break;
  7577. }
  7578. }
  7579. } else {
  7580. // store current width
  7581. $oldw = $w;
  7582. // calculate new width
  7583. $w = $h * $pixw / $pixh;
  7584. // width difference
  7585. $wdiff = ($oldw - $w);
  7586. // horizontal alignment
  7587. switch (strtoupper($fitbox{0})) {
  7588. case 'L': {
  7589. if ($this->rtl) {
  7590. $x -= $wdiff;
  7591. }
  7592. break;
  7593. }
  7594. case 'C': {
  7595. if ($this->rtl) {
  7596. $x -= ($wdiff / 2);
  7597. } else {
  7598. $x += ($wdiff / 2);
  7599. }
  7600. break;
  7601. }
  7602. case 'R': {
  7603. if (!$this->rtl) {
  7604. $x += $wdiff;
  7605. }
  7606. break;
  7607. }
  7608. }
  7609. }
  7610. }
  7611. // fit the image on available space
  7612. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  7613. // calculate new minimum dimensions in pixels
  7614. $neww = round($w * $this->k * $dpi / $this->dpi);
  7615. $newh = round($h * $this->k * $dpi / $this->dpi);
  7616. // check if resize is necessary (resize is used only to reduce the image)
  7617. $newsize = ($neww * $newh);
  7618. $pixsize = ($pixw * $pixh);
  7619. if (intval($resize) == 2) {
  7620. $resize = true;
  7621. } elseif ($newsize >= $pixsize) {
  7622. $resize = false;
  7623. }
  7624. // check if image has been already added on document
  7625. $newimage = true;
  7626. if (in_array($file, $this->imagekeys)) {
  7627. $newimage = false;
  7628. // get existing image data
  7629. $info = $this->getImageBuffer($file);
  7630. if (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
  7631. // check if the newer image is larger
  7632. $oldsize = ($info['w'] * $info['h']);
  7633. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  7634. $newimage = true;
  7635. }
  7636. }
  7637. } elseif (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
  7638. // check for cached images with alpha channel
  7639. $tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
  7640. $tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
  7641. if (in_array($tempfile_plain, $this->imagekeys)) {
  7642. // get existing image data
  7643. $info = $this->getImageBuffer($tempfile_plain);
  7644. // check if the newer image is larger
  7645. $oldsize = ($info['w'] * $info['h']);
  7646. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  7647. $newimage = true;
  7648. } else {
  7649. $newimage = false;
  7650. // embed mask image
  7651. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  7652. // embed image, masked with previously embedded mask
  7653. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  7654. }
  7655. }
  7656. }
  7657. if ($newimage) {
  7658. //First use of image, get info
  7659. $type = strtolower($type);
  7660. if ($type == '') {
  7661. $type = $this->getImageFileType($file, $imsize);
  7662. } elseif ($type == 'jpg') {
  7663. $type = 'jpeg';
  7664. }
  7665. $mqr = $this->get_mqr();
  7666. $this->set_mqr(false);
  7667. // Specific image handlers
  7668. $mtd = '_parse'.$type;
  7669. // GD image handler function
  7670. $gdfunction = 'imagecreatefrom'.$type;
  7671. $info = false;
  7672. if ((method_exists($this, $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  7673. // TCPDF image functions
  7674. $info = $this->$mtd($file);
  7675. if ($info == 'pngalpha') {
  7676. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  7677. }
  7678. }
  7679. if (!$info) {
  7680. if (function_exists($gdfunction)) {
  7681. // GD library
  7682. $img = $gdfunction($file);
  7683. if ($resize) {
  7684. $imgr = imagecreatetruecolor($neww, $newh);
  7685. if (($type == 'gif') OR ($type == 'png')) {
  7686. $imgr = $this->_setGDImageTransparency($imgr, $img);
  7687. }
  7688. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  7689. if (($type == 'gif') OR ($type == 'png')) {
  7690. $info = $this->_toPNG($imgr);
  7691. } else {
  7692. $info = $this->_toJPEG($imgr);
  7693. }
  7694. } else {
  7695. if (($type == 'gif') OR ($type == 'png')) {
  7696. $info = $this->_toPNG($img);
  7697. } else {
  7698. $info = $this->_toJPEG($img);
  7699. }
  7700. }
  7701. } elseif (extension_loaded('imagick')) {
  7702. // ImageMagick library
  7703. $img = new Imagick();
  7704. if ($type == 'SVG') {
  7705. // get SVG file content
  7706. $svgimg = file_get_contents($file);
  7707. // get width and height
  7708. $regs = array();
  7709. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  7710. $svgtag = $regs[1];
  7711. $tmp = array();
  7712. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  7713. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  7714. $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
  7715. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  7716. } else {
  7717. $ow = $w;
  7718. }
  7719. $tmp = array();
  7720. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  7721. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  7722. $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
  7723. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  7724. } else {
  7725. $oh = $h;
  7726. }
  7727. $tmp = array();
  7728. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  7729. $vbw = ($ow * $this->imgscale * $this->k);
  7730. $vbh = ($oh * $this->imgscale * $this->k);
  7731. $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
  7732. $svgtag = $vbox.$svgtag;
  7733. }
  7734. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  7735. }
  7736. $img->readImageBlob($svgimg);
  7737. } else {
  7738. $img->readImage($file);
  7739. }
  7740. if ($resize) {
  7741. $img->resizeImage($neww, $newh, 10, 1, false);
  7742. }
  7743. $img->setCompressionQuality($this->jpeg_quality);
  7744. $img->setImageFormat('jpeg');
  7745. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  7746. $img->writeImage($tempname);
  7747. $info = $this->_parsejpeg($tempname);
  7748. unlink($tempname);
  7749. $img->destroy();
  7750. } else {
  7751. return;
  7752. }
  7753. }
  7754. if ($info === false) {
  7755. //If false, we cannot process image
  7756. return;
  7757. }
  7758. $this->set_mqr($mqr);
  7759. if ($ismask) {
  7760. // force grayscale
  7761. $info['cs'] = 'DeviceGray';
  7762. }
  7763. $info['i'] = $this->numimages;
  7764. if (!in_array($file, $this->imagekeys)) {
  7765. ++$info['i'];
  7766. }
  7767. if ($imgmask !== false) {
  7768. $info['masked'] = $imgmask;
  7769. }
  7770. if (!empty($exurl)) {
  7771. $info['exurl'] = $exurl;
  7772. }
  7773. // array of alternative images
  7774. $info['altimgs'] = $altimgs;
  7775. // add image to document
  7776. $this->setImageBuffer($file, $info);
  7777. }
  7778. if ($cached_file) {
  7779. // remove cached file
  7780. unlink($file);
  7781. }
  7782. // set alignment
  7783. $this->img_rb_y = $y + $h;
  7784. // set alignment
  7785. if ($this->rtl) {
  7786. if ($palign == 'L') {
  7787. $ximg = $this->lMargin;
  7788. } elseif ($palign == 'C') {
  7789. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  7790. } elseif ($palign == 'R') {
  7791. $ximg = $this->w - $this->rMargin - $w;
  7792. } else {
  7793. $ximg = $x - $w;
  7794. }
  7795. $this->img_rb_x = $ximg;
  7796. } else {
  7797. if ($palign == 'L') {
  7798. $ximg = $this->lMargin;
  7799. } elseif ($palign == 'C') {
  7800. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  7801. } elseif ($palign == 'R') {
  7802. $ximg = $this->w - $this->rMargin - $w;
  7803. } else {
  7804. $ximg = $x;
  7805. }
  7806. $this->img_rb_x = $ximg + $w;
  7807. }
  7808. if ($ismask OR $hidden) {
  7809. // image is not displayed
  7810. return $info['i'];
  7811. }
  7812. $xkimg = $ximg * $this->k;
  7813. if (!$alt) {
  7814. // only non-alternative immages will be set
  7815. $this->_out(sprintf('q %F 0 0 %F %F %F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
  7816. }
  7817. if (!empty($border)) {
  7818. $bx = $this->x;
  7819. $by = $this->y;
  7820. $this->x = $ximg;
  7821. if ($this->rtl) {
  7822. $this->x += $w;
  7823. }
  7824. $this->y = $y;
  7825. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  7826. $this->x = $bx;
  7827. $this->y = $by;
  7828. }
  7829. if ($link) {
  7830. $this->Link($ximg, $y, $w, $h, $link, 0);
  7831. }
  7832. // set pointer to align the next text/objects
  7833. switch($align) {
  7834. case 'T': {
  7835. $this->y = $y;
  7836. $this->x = $this->img_rb_x;
  7837. break;
  7838. }
  7839. case 'M': {
  7840. $this->y = $y + round($h/2);
  7841. $this->x = $this->img_rb_x;
  7842. break;
  7843. }
  7844. case 'B': {
  7845. $this->y = $this->img_rb_y;
  7846. $this->x = $this->img_rb_x;
  7847. break;
  7848. }
  7849. case 'N': {
  7850. $this->SetY($this->img_rb_y);
  7851. break;
  7852. }
  7853. default:{
  7854. break;
  7855. }
  7856. }
  7857. $this->endlinex = $this->img_rb_x;
  7858. if ($this->inxobj) {
  7859. // we are inside an XObject template
  7860. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  7861. }
  7862. return $info['i'];
  7863. }
  7864. /**
  7865. * Sets the current active configuration setting of magic_quotes_runtime (if the set_magic_quotes_runtime function exist)
  7866. * @param $mqr (boolean) FALSE for off, TRUE for on.
  7867. * @since 4.6.025 (2009-08-17)
  7868. */
  7869. public function set_mqr($mqr) {
  7870. if (!defined('PHP_VERSION_ID')) {
  7871. $version = PHP_VERSION;
  7872. define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4}));
  7873. }
  7874. if (PHP_VERSION_ID < 50300) {
  7875. @set_magic_quotes_runtime($mqr);
  7876. }
  7877. }
  7878. /**
  7879. * Gets the current active configuration setting of magic_quotes_runtime (if the get_magic_quotes_runtime function exist)
  7880. * @return Returns 0 if magic quotes runtime is off or get_magic_quotes_runtime doesn't exist, 1 otherwise.
  7881. * @since 4.6.025 (2009-08-17)
  7882. */
  7883. public function get_mqr() {
  7884. if (!defined('PHP_VERSION_ID')) {
  7885. $version = PHP_VERSION;
  7886. define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4}));
  7887. }
  7888. if (PHP_VERSION_ID < 50300) {
  7889. return @get_magic_quotes_runtime();
  7890. }
  7891. return 0;
  7892. }
  7893. /**
  7894. * Convert the loaded image to a JPEG and then return a structure for the PDF creator.
  7895. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
  7896. * @param $image (image) Image object.
  7897. * return image JPEG image object.
  7898. * @protected
  7899. */
  7900. protected function _toJPEG($image) {
  7901. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  7902. imagejpeg($image, $tempname, $this->jpeg_quality);
  7903. imagedestroy($image);
  7904. $retvars = $this->_parsejpeg($tempname);
  7905. // tidy up by removing temporary image
  7906. unlink($tempname);
  7907. return $retvars;
  7908. }
  7909. /**
  7910. * Convert the loaded image to a PNG and then return a structure for the PDF creator.
  7911. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
  7912. * @param $image (image) Image object.
  7913. * return image PNG image object.
  7914. * @protected
  7915. * @since 4.9.016 (2010-04-20)
  7916. */
  7917. protected function _toPNG($image) {
  7918. // set temporary image file name
  7919. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  7920. // turn off interlaced mode
  7921. imageinterlace($image, 0);
  7922. // create temporary PNG image
  7923. imagepng($image, $tempname);
  7924. // remove image from memory
  7925. imagedestroy($image);
  7926. // get PNG image data
  7927. $retvars = $this->_parsepng($tempname);
  7928. // tidy up by removing temporary image
  7929. unlink($tempname);
  7930. return $retvars;
  7931. }
  7932. /**
  7933. * Set the transparency for the given GD image.
  7934. * @param $new_image (image) GD image object
  7935. * @param $image (image) GD image object.
  7936. * return GD image object.
  7937. * @protected
  7938. * @since 4.9.016 (2010-04-20)
  7939. */
  7940. protected function _setGDImageTransparency($new_image, $image) {
  7941. // transparency index
  7942. $tid = imagecolortransparent($image);
  7943. // default transparency color
  7944. $tcol = array('red' => 255, 'green' => 255, 'blue' => 255);
  7945. if ($tid >= 0) {
  7946. // get the colors for the transparency index
  7947. $tcol = imagecolorsforindex($image, $tid);
  7948. }
  7949. $tid = imagecolorallocate($new_image, $tcol['red'], $tcol['green'], $tcol['blue']);
  7950. imagefill($new_image, 0, 0, $tid);
  7951. imagecolortransparent($new_image, $tid);
  7952. return $new_image;
  7953. }
  7954. /**
  7955. * Extract info from a JPEG file without using the GD library.
  7956. * @param $file (string) image file to parse
  7957. * @return array structure containing the image data
  7958. * @protected
  7959. */
  7960. protected function _parsejpeg($file) {
  7961. $a = getimagesize($file);
  7962. if (empty($a)) {
  7963. $this->Error('Missing or incorrect image file: '.$file);
  7964. }
  7965. if ($a[2] != 2) {
  7966. $this->Error('Not a JPEG file: '.$file);
  7967. }
  7968. // bits per pixel
  7969. $bpc = isset($a['bits']) ? intval($a['bits']) : 8;
  7970. // number of image channels
  7971. if (!isset($a['channels'])) {
  7972. $channels = 3;
  7973. } else {
  7974. $channels = intval($a['channels']);
  7975. }
  7976. // default colour space
  7977. switch ($channels) {
  7978. case 1: {
  7979. $colspace = 'DeviceGray';
  7980. break;
  7981. }
  7982. case 3: {
  7983. $colspace = 'DeviceRGB';
  7984. break;
  7985. }
  7986. case 4: {
  7987. $colspace = 'DeviceCMYK';
  7988. break;
  7989. }
  7990. default: {
  7991. $channels = 3;
  7992. $colspace = 'DeviceRGB';
  7993. break;
  7994. }
  7995. }
  7996. // get file content
  7997. $data = file_get_contents($file);
  7998. // check for embedded ICC profile
  7999. $icc = array();
  8000. $offset = 0;
  8001. while (($pos = strpos($data, "ICC_PROFILE\0", $offset)) !== false) {
  8002. // get ICC sequence length
  8003. $length = ($this->_getUSHORT($data, ($pos - 2)) - 16);
  8004. // marker sequence number
  8005. $msn = max(1, ord($data[($pos + 12)]));
  8006. // number of markers (total of APP2 used)
  8007. $nom = max(1, ord($data[($pos + 13)]));
  8008. // get sequence segment
  8009. $icc[($msn - 1)] = substr($data, ($pos + 14), $length);
  8010. // move forward to next sequence
  8011. $offset = ($pos + 14 + $length);
  8012. }
  8013. // order and compact ICC segments
  8014. if (count($icc) > 0) {
  8015. ksort($icc);
  8016. $icc = implode('', $icc);
  8017. if ((ord($icc{36}) != 0x61) OR (ord($icc{37}) != 0x63) OR (ord($icc{38}) != 0x73) OR (ord($icc{39}) != 0x70)) {
  8018. // invalid ICC profile
  8019. $icc = false;
  8020. }
  8021. } else {
  8022. $icc = false;
  8023. }
  8024. return array('w' => $a[0], 'h' => $a[1], 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
  8025. }
  8026. /**
  8027. * Extract info from a PNG file without using the GD library.
  8028. * @param $file (string) image file to parse
  8029. * @return array structure containing the image data
  8030. * @protected
  8031. */
  8032. protected function _parsepng($file) {
  8033. $f = fopen($file, 'rb');
  8034. if ($f === false) {
  8035. $this->Error('Can\'t open image file: '.$file);
  8036. }
  8037. //Check signature
  8038. if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
  8039. $this->Error('Not a PNG file: '.$file);
  8040. }
  8041. //Read header chunk
  8042. fread($f, 4);
  8043. if (fread($f, 4) != 'IHDR') {
  8044. $this->Error('Incorrect PNG file: '.$file);
  8045. }
  8046. $w = $this->_freadint($f);
  8047. $h = $this->_freadint($f);
  8048. $bpc = ord(fread($f, 1));
  8049. if ($bpc > 8) {
  8050. //$this->Error('16-bit depth not supported: '.$file);
  8051. fclose($f);
  8052. return false;
  8053. }
  8054. $ct = ord(fread($f, 1));
  8055. if ($ct == 0) {
  8056. $colspace = 'DeviceGray';
  8057. } elseif ($ct == 2) {
  8058. $colspace = 'DeviceRGB';
  8059. } elseif ($ct == 3) {
  8060. $colspace = 'Indexed';
  8061. } else {
  8062. // alpha channel
  8063. fclose($f);
  8064. return 'pngalpha';
  8065. }
  8066. if (ord(fread($f, 1)) != 0) {
  8067. //$this->Error('Unknown compression method: '.$file);
  8068. fclose($f);
  8069. return false;
  8070. }
  8071. if (ord(fread($f, 1)) != 0) {
  8072. //$this->Error('Unknown filter method: '.$file);
  8073. fclose($f);
  8074. return false;
  8075. }
  8076. if (ord(fread($f, 1)) != 0) {
  8077. //$this->Error('Interlacing not supported: '.$file);
  8078. fclose($f);
  8079. return false;
  8080. }
  8081. fread($f, 4);
  8082. $channels = ($ct == 2 ? 3 : 1);
  8083. $parms = '/DecodeParms << /Predictor 15 /Colors '.$channels.' /BitsPerComponent '.$bpc.' /Columns '.$w.' >>';
  8084. //Scan chunks looking for palette, transparency and image data
  8085. $pal = '';
  8086. $trns = '';
  8087. $data = '';
  8088. $icc = false;
  8089. do {
  8090. $n = $this->_freadint($f);
  8091. $type = fread($f, 4);
  8092. if ($type == 'PLTE') {
  8093. // read palette
  8094. $pal = $this->rfread($f, $n);
  8095. fread($f, 4);
  8096. } elseif ($type == 'tRNS') {
  8097. // read transparency info
  8098. $t = $this->rfread($f, $n);
  8099. if ($ct == 0) {
  8100. $trns = array(ord($t{1}));
  8101. } elseif ($ct == 2) {
  8102. $trns = array(ord($t{1}), ord($t{3}), ord($t{5}));
  8103. } else {
  8104. $pos = strpos($t, chr(0));
  8105. if ($pos !== false) {
  8106. $trns = array($pos);
  8107. }
  8108. }
  8109. fread($f, 4);
  8110. } elseif ($type == 'IDAT') {
  8111. // read image data block
  8112. $data .= $this->rfread($f, $n);
  8113. fread($f, 4);
  8114. } elseif ($type == 'iCCP') {
  8115. // skip profile name
  8116. $len = 0;
  8117. while ((ord(fread($f, 1)) > 0) AND ($len < 80)) {
  8118. ++$len;
  8119. }
  8120. // skip null separator
  8121. fread($f, 1);
  8122. // get compression method
  8123. if (ord(fread($f, 1)) != 0) {
  8124. //$this->Error('Unknown filter method: '.$file);
  8125. fclose($f);
  8126. return false;
  8127. }
  8128. // read ICC Color Profile
  8129. $icc = $this->rfread($f, ($n - $len - 2));
  8130. // decompress profile
  8131. $icc = gzuncompress($icc);
  8132. fread($f, 4);
  8133. } elseif ($type == 'IEND') {
  8134. break;
  8135. } else {
  8136. $this->rfread($f, $n + 4);
  8137. }
  8138. } while ($n);
  8139. if (($colspace == 'Indexed') AND (empty($pal))) {
  8140. //$this->Error('Missing palette in '.$file);
  8141. fclose($f);
  8142. return false;
  8143. }
  8144. fclose($f);
  8145. return array('w' => $w, 'h' => $h, 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
  8146. }
  8147. /**
  8148. * Binary-safe and URL-safe file read.
  8149. * 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.
  8150. * @param $handle (resource)
  8151. * @param $length (int)
  8152. * @return Returns the read string or FALSE in case of error.
  8153. * @author Nicola Asuni
  8154. * @protected
  8155. * @since 4.5.027 (2009-03-16)
  8156. */
  8157. protected function rfread($handle, $length) {
  8158. $data = fread($handle, $length);
  8159. if ($data === false) {
  8160. return false;
  8161. }
  8162. $rest = $length - strlen($data);
  8163. if ($rest > 0) {
  8164. $data .= $this->rfread($handle, $rest);
  8165. }
  8166. return $data;
  8167. }
  8168. /**
  8169. * Extract info from a PNG image with alpha channel using the GD library.
  8170. * @param $file (string) Name of the file containing the image.
  8171. * @param $x (float) Abscissa of the upper-left corner.
  8172. * @param $y (float) Ordinate of the upper-left corner.
  8173. * @param $wpx (float) Original width of the image in pixels.
  8174. * @param $hpx (float) original height of the image in pixels.
  8175. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  8176. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  8177. * @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.
  8178. * @param $link (mixed) URL or identifier returned by AddLink().
  8179. * @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>
  8180. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  8181. * @param $dpi (int) dot-per-inch resolution used on resize
  8182. * @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>
  8183. * @param $filehash (string) File hash used to build unique file names.
  8184. * @author Nicola Asuni
  8185. * @protected
  8186. * @since 4.3.007 (2008-12-04)
  8187. * @see Image()
  8188. */
  8189. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  8190. if (empty($filehash)) {
  8191. $filehash = md5($this->file_id.$file);
  8192. }
  8193. // create temp image file (without alpha channel)
  8194. $tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
  8195. // create temp alpha file
  8196. $tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
  8197. if (extension_loaded('imagick')) { // ImageMagick extension
  8198. // ImageMagick library
  8199. $img = new Imagick();
  8200. $img->readImage($file);
  8201. // clone image object
  8202. $imga = $this->objclone($img);
  8203. // extract alpha channel
  8204. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  8205. $img->negateImage(true);
  8206. $img->setImageFormat('png');
  8207. $img->writeImage($tempfile_alpha);
  8208. // remove alpha channel
  8209. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  8210. $imga->setImageFormat('png');
  8211. $imga->writeImage($tempfile_plain);
  8212. } elseif (function_exists('imagecreatefrompng')) { // GD extension
  8213. // generate images
  8214. $img = imagecreatefrompng($file);
  8215. $imgalpha = imagecreate($wpx, $hpx);
  8216. // generate gray scale palette (0 -> 255)
  8217. for ($c = 0; $c < 256; ++$c) {
  8218. ImageColorAllocate($imgalpha, $c, $c, $c);
  8219. }
  8220. // extract alpha channel
  8221. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  8222. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  8223. $color = imagecolorat($img, $xpx, $ypx);
  8224. $alpha = $this->getGDgamma($color); // correct gamma
  8225. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  8226. }
  8227. }
  8228. imagepng($imgalpha, $tempfile_alpha);
  8229. imagedestroy($imgalpha);
  8230. // extract image without alpha channel
  8231. $imgplain = imagecreatetruecolor($wpx, $hpx);
  8232. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  8233. imagepng($imgplain, $tempfile_plain);
  8234. imagedestroy($imgplain);
  8235. } else {
  8236. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  8237. }
  8238. // embed mask image
  8239. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  8240. // embed image, masked with previously embedded mask
  8241. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  8242. // remove temp files
  8243. unlink($tempfile_alpha);
  8244. unlink($tempfile_plain);
  8245. }
  8246. /**
  8247. * Get the GD-corrected PNG gamma value from alpha color
  8248. * @param $c (int) alpha color
  8249. * @protected
  8250. * @since 4.3.007 (2008-12-04)
  8251. */
  8252. protected function getGDgamma($c) {
  8253. if (!isset($this->gdgammacache["'".$c."'"])) {
  8254. // shifts off the first 24 bits (where 8x3 are used for each color),
  8255. // and returns the remaining 7 allocated bits (commonly used for alpha)
  8256. $alpha = ($c >> 24);
  8257. // GD alpha is only 7 bit (0 -> 127)
  8258. $alpha = (((127 - $alpha) / 127) * 255);
  8259. // correct gamma
  8260. $this->gdgammacache["'".$c."'"] = (pow(($alpha / 255), 2.2) * 255);
  8261. // store the latest values on cache to improve performances
  8262. if (count($this->gdgammacache) > 8) {
  8263. // remove one element from the cache array
  8264. array_shift($this->gdgammacache);
  8265. }
  8266. }
  8267. return $this->gdgammacache["'".$c."'"];
  8268. }
  8269. /**
  8270. * Performs a line break.
  8271. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  8272. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  8273. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  8274. * @public
  8275. * @since 1.0
  8276. * @see Cell()
  8277. */
  8278. public function Ln($h='', $cell=false) {
  8279. 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'])) {
  8280. // revove vertical space from the top of the column
  8281. return;
  8282. }
  8283. if ($cell) {
  8284. if ($this->rtl) {
  8285. $cellpadding = $this->cell_padding['R'];
  8286. } else {
  8287. $cellpadding = $this->cell_padding['L'];
  8288. }
  8289. } else {
  8290. $cellpadding = 0;
  8291. }
  8292. if ($this->rtl) {
  8293. $this->x = $this->w - $this->rMargin - $cellpadding;
  8294. } else {
  8295. $this->x = $this->lMargin + $cellpadding;
  8296. }
  8297. if (is_string($h)) {
  8298. $this->y += $this->lasth;
  8299. } else {
  8300. $this->y += $h;
  8301. }
  8302. $this->newline = true;
  8303. }
  8304. /**
  8305. * Returns the relative X value of current position.
  8306. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  8307. * @return float
  8308. * @public
  8309. * @since 1.2
  8310. * @see SetX(), GetY(), SetY()
  8311. */
  8312. public function GetX() {
  8313. //Get x position
  8314. if ($this->rtl) {
  8315. return ($this->w - $this->x);
  8316. } else {
  8317. return $this->x;
  8318. }
  8319. }
  8320. /**
  8321. * Returns the absolute X value of current position.
  8322. * @return float
  8323. * @public
  8324. * @since 1.2
  8325. * @see SetX(), GetY(), SetY()
  8326. */
  8327. public function GetAbsX() {
  8328. return $this->x;
  8329. }
  8330. /**
  8331. * Returns the ordinate of the current position.
  8332. * @return float
  8333. * @public
  8334. * @since 1.0
  8335. * @see SetY(), GetX(), SetX()
  8336. */
  8337. public function GetY() {
  8338. return $this->y;
  8339. }
  8340. /**
  8341. * Defines the abscissa of the current position.
  8342. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  8343. * @param $x (float) The value of the abscissa.
  8344. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  8345. * @public
  8346. * @since 1.2
  8347. * @see GetX(), GetY(), SetY(), SetXY()
  8348. */
  8349. public function SetX($x, $rtloff=false) {
  8350. if (!$rtloff AND $this->rtl) {
  8351. if ($x >= 0) {
  8352. $this->x = $this->w - $x;
  8353. } else {
  8354. $this->x = abs($x);
  8355. }
  8356. } else {
  8357. if ($x >= 0) {
  8358. $this->x = $x;
  8359. } else {
  8360. $this->x = $this->w + $x;
  8361. }
  8362. }
  8363. if ($this->x < 0) {
  8364. $this->x = 0;
  8365. }
  8366. if ($this->x > $this->w) {
  8367. $this->x = $this->w;
  8368. }
  8369. }
  8370. /**
  8371. * Moves the current abscissa back to the left margin and sets the ordinate.
  8372. * If the passed value is negative, it is relative to the bottom of the page.
  8373. * @param $y (float) The value of the ordinate.
  8374. * @param $resetx (bool) if true (default) reset the X position.
  8375. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  8376. * @public
  8377. * @since 1.0
  8378. * @see GetX(), GetY(), SetY(), SetXY()
  8379. */
  8380. public function SetY($y, $resetx=true, $rtloff=false) {
  8381. if ($resetx) {
  8382. //reset x
  8383. if (!$rtloff AND $this->rtl) {
  8384. $this->x = $this->w - $this->rMargin;
  8385. } else {
  8386. $this->x = $this->lMargin;
  8387. }
  8388. }
  8389. if ($y >= 0) {
  8390. $this->y = $y;
  8391. } else {
  8392. $this->y = $this->h + $y;
  8393. }
  8394. if ($this->y < 0) {
  8395. $this->y = 0;
  8396. }
  8397. if ($this->y > $this->h) {
  8398. $this->y = $this->h;
  8399. }
  8400. }
  8401. /**
  8402. * Defines the abscissa and ordinate of the current position.
  8403. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  8404. * @param $x (float) The value of the abscissa.
  8405. * @param $y (float) The value of the ordinate.
  8406. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  8407. * @public
  8408. * @since 1.2
  8409. * @see SetX(), SetY()
  8410. */
  8411. public function SetXY($x, $y, $rtloff=false) {
  8412. $this->SetY($y, false, $rtloff);
  8413. $this->SetX($x, $rtloff);
  8414. }
  8415. /**
  8416. * Ouput input data and compress it if possible.
  8417. * @param $data (string) Data to output.
  8418. * @param $length (int) Data length in bytes.
  8419. * @protected
  8420. * @since 5.9.086
  8421. */
  8422. protected function sendOutputData($data, $length) {
  8423. if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) OR empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
  8424. // the content length may vary if the server is using compression
  8425. header('Content-Length: '.$length);
  8426. }
  8427. echo $data;
  8428. }
  8429. /**
  8430. * Send the document to a given destination: string, local file or browser.
  8431. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  8432. * The method first calls Close() if necessary to terminate the document.
  8433. * @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.
  8434. * @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>
  8435. * @public
  8436. * @since 1.0
  8437. * @see Close()
  8438. */
  8439. public function Output($name='doc.pdf', $dest='I') {
  8440. //Output PDF to some destination
  8441. //Finish document if necessary
  8442. if ($this->state < 3) {
  8443. $this->Close();
  8444. }
  8445. //Normalize parameters
  8446. if (is_bool($dest)) {
  8447. $dest = $dest ? 'D' : 'F';
  8448. }
  8449. $dest = strtoupper($dest);
  8450. if ($dest{0} != 'F') {
  8451. $name = preg_replace('/[\s]+/', '_', $name);
  8452. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  8453. }
  8454. if ($this->sign) {
  8455. // *** apply digital signature to the document ***
  8456. // get the document content
  8457. $pdfdoc = $this->getBuffer();
  8458. // remove last newline
  8459. $pdfdoc = substr($pdfdoc, 0, -1);
  8460. // Remove the original buffer
  8461. if (isset($this->diskcache) AND $this->diskcache) {
  8462. // remove buffer file from cache
  8463. unlink($this->buffer);
  8464. }
  8465. unset($this->buffer);
  8466. // remove filler space
  8467. $byterange_string_len = strlen($this->byterange_string);
  8468. // define the ByteRange
  8469. $byte_range = array();
  8470. $byte_range[0] = 0;
  8471. $byte_range[1] = strpos($pdfdoc, $this->byterange_string) + $byterange_string_len + 10;
  8472. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  8473. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  8474. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  8475. // replace the ByteRange
  8476. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  8477. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  8478. $pdfdoc = str_replace($this->byterange_string, $byterange, $pdfdoc);
  8479. // write the document to a temporary folder
  8480. $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
  8481. $f = fopen($tempdoc, 'wb');
  8482. if (!$f) {
  8483. $this->Error('Unable to create temporary file: '.$tempdoc);
  8484. }
  8485. $pdfdoc_length = strlen($pdfdoc);
  8486. fwrite($f, $pdfdoc, $pdfdoc_length);
  8487. fclose($f);
  8488. // get digital signature via openssl library
  8489. $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
  8490. if (empty($this->signature_data['extracerts'])) {
  8491. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  8492. } else {
  8493. 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']);
  8494. }
  8495. unlink($tempdoc);
  8496. // read signature
  8497. $signature = file_get_contents($tempsign);
  8498. unlink($tempsign);
  8499. // extract signature
  8500. $signature = substr($signature, $pdfdoc_length);
  8501. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  8502. $tmparr = explode("\n\n", $signature);
  8503. $signature = $tmparr[1];
  8504. unset($tmparr);
  8505. // decode signature
  8506. $signature = base64_decode(trim($signature));
  8507. // convert signature to hex
  8508. $signature = current(unpack('H*', $signature));
  8509. $signature = str_pad($signature, $this->signature_max_length, '0');
  8510. // disable disk caching
  8511. $this->diskcache = false;
  8512. // Add signature to the document
  8513. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  8514. $this->bufferlen = strlen($this->buffer);
  8515. }
  8516. switch($dest) {
  8517. case 'I': {
  8518. // Send PDF to the standard output
  8519. if (ob_get_contents()) {
  8520. $this->Error('Some data has already been output, can\'t send PDF file');
  8521. }
  8522. if (php_sapi_name() != 'cli') {
  8523. // send output to a browser
  8524. header('Content-Type: application/pdf');
  8525. if (headers_sent()) {
  8526. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  8527. }
  8528. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8529. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  8530. header('Pragma: public');
  8531. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8532. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8533. header('Content-Disposition: inline; filename="'.basename($name).'"');
  8534. $this->sendOutputData($this->getBuffer(), $this->bufferlen);
  8535. } else {
  8536. echo $this->getBuffer();
  8537. }
  8538. break;
  8539. }
  8540. case 'D': {
  8541. // download PDF as file
  8542. if (ob_get_contents()) {
  8543. $this->Error('Some data has already been output, can\'t send PDF file');
  8544. }
  8545. header('Content-Description: File Transfer');
  8546. if (headers_sent()) {
  8547. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  8548. }
  8549. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8550. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  8551. header('Pragma: public');
  8552. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8553. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8554. // force download dialog
  8555. if (strpos(php_sapi_name(), 'cgi') === false) {
  8556. header('Content-Type: application/force-download');
  8557. header('Content-Type: application/octet-stream', false);
  8558. header('Content-Type: application/download', false);
  8559. header('Content-Type: application/pdf', false);
  8560. } else {
  8561. header('Content-Type: application/pdf');
  8562. }
  8563. // use the Content-Disposition header to supply a recommended filename
  8564. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  8565. header('Content-Transfer-Encoding: binary');
  8566. $this->sendOutputData($this->getBuffer(), $this->bufferlen);
  8567. break;
  8568. }
  8569. case 'F':
  8570. case 'FI':
  8571. case 'FD': {
  8572. // save PDF to a local file
  8573. if ($this->diskcache) {
  8574. copy($this->buffer, $name);
  8575. } else {
  8576. $f = fopen($name, 'wb');
  8577. if (!$f) {
  8578. $this->Error('Unable to create output file: '.$name);
  8579. }
  8580. fwrite($f, $this->getBuffer(), $this->bufferlen);
  8581. fclose($f);
  8582. }
  8583. if ($dest == 'FI') {
  8584. // send headers to browser
  8585. header('Content-Type: application/pdf');
  8586. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8587. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  8588. header('Pragma: public');
  8589. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8590. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8591. header('Content-Disposition: inline; filename="'.basename($name).'"');
  8592. $this->sendOutputData(file_get_contents($name), filesize($name));
  8593. } elseif ($dest == 'FD') {
  8594. // send headers to browser
  8595. if (ob_get_contents()) {
  8596. $this->Error('Some data has already been output, can\'t send PDF file');
  8597. }
  8598. header('Content-Description: File Transfer');
  8599. if (headers_sent()) {
  8600. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  8601. }
  8602. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  8603. header('Pragma: public');
  8604. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  8605. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  8606. // force download dialog
  8607. if (strpos(php_sapi_name(), 'cgi') === false) {
  8608. header('Content-Type: application/force-download');
  8609. header('Content-Type: application/octet-stream', false);
  8610. header('Content-Type: application/download', false);
  8611. header('Content-Type: application/pdf', false);
  8612. } else {
  8613. header('Content-Type: application/pdf');
  8614. }
  8615. // use the Content-Disposition header to supply a recommended filename
  8616. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  8617. header('Content-Transfer-Encoding: binary');
  8618. $this->sendOutputData(file_get_contents($name), filesize($name));
  8619. }
  8620. break;
  8621. }
  8622. case 'E': {
  8623. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  8624. $retval = 'Content-Type: application/pdf;'."\r\n";
  8625. $retval .= ' name="'.$name.'"'."\r\n";
  8626. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  8627. $retval .= 'Content-Disposition: attachment;'."\r\n";
  8628. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  8629. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  8630. return $retval;
  8631. }
  8632. case 'S': {
  8633. // returns PDF as a string
  8634. return $this->getBuffer();
  8635. }
  8636. default: {
  8637. $this->Error('Incorrect output destination: '.$dest);
  8638. }
  8639. }
  8640. return '';
  8641. }
  8642. /**
  8643. * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
  8644. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  8645. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  8646. * @public
  8647. * @since 4.5.016 (2009-02-24)
  8648. */
  8649. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  8650. if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
  8651. // remove buffer file from cache
  8652. unlink($this->buffer);
  8653. }
  8654. foreach (array_keys(get_object_vars($this)) as $val) {
  8655. if ($destroyall OR (
  8656. ($val != 'internal_encoding')
  8657. AND ($val != 'state')
  8658. AND ($val != 'bufferlen')
  8659. AND ($val != 'buffer')
  8660. AND ($val != 'diskcache')
  8661. AND ($val != 'sign')
  8662. AND ($val != 'signature_data')
  8663. AND ($val != 'signature_max_length')
  8664. AND ($val != 'byterange_string')
  8665. )) {
  8666. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND isset($this->$val)) {
  8667. unset($this->$val);
  8668. }
  8669. }
  8670. }
  8671. }
  8672. /**
  8673. * Check for locale-related bug
  8674. * @protected
  8675. */
  8676. protected function _dochecks() {
  8677. //Check for locale-related bug
  8678. if (1.1 == 1) {
  8679. $this->Error('Don\'t alter the locale before including class file');
  8680. }
  8681. //Check for decimal separator
  8682. if (sprintf('%.1F', 1.0) != '1.0') {
  8683. setlocale(LC_NUMERIC, 'C');
  8684. }
  8685. }
  8686. /**
  8687. * Return fonts path
  8688. * @return string
  8689. * @protected
  8690. */
  8691. protected function _getfontpath() {
  8692. if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
  8693. define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
  8694. }
  8695. return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
  8696. }
  8697. /**
  8698. * Return an array containing variations for the basic page number alias.
  8699. * @param $a (string) Base alias.
  8700. * @return array of page number aliases
  8701. * @protected
  8702. */
  8703. protected function getInternalPageNumberAliases($a= '') {
  8704. $alias = array();
  8705. // build array of Unicode + ASCII variants (the order is important)
  8706. $alias = array('u' => array(), 'a' => array());
  8707. $u = '{'.$a.'}';
  8708. $alias['u'][] = $this->_escape($u);
  8709. if ($this->isunicode) {
  8710. $alias['u'][] = $this->_escape($this->UTF8ToLatin1($u));
  8711. $alias['u'][] = $this->_escape($this->utf8StrRev($u, false, $this->tmprtl));
  8712. $alias['a'][] = $this->_escape($this->UTF8ToLatin1($a));
  8713. $alias['a'][] = $this->_escape($this->utf8StrRev($a, false, $this->tmprtl));
  8714. }
  8715. $alias['a'][] = $this->_escape($a);
  8716. return $alias;
  8717. }
  8718. /**
  8719. * Return an array containing all internal page aliases.
  8720. * @return array of page number aliases
  8721. * @protected
  8722. */
  8723. protected function getAllInternalPageNumberAliases() {
  8724. $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);
  8725. $pnalias = array();
  8726. foreach($basic_alias as $k => $a) {
  8727. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  8728. }
  8729. return $pnalias;
  8730. }
  8731. /**
  8732. * Replace page number aliases with number.
  8733. * @param $page (string) Page content.
  8734. * @param $replace (array) Array of replacements (array keys are replacement strings, values are alias arrays).
  8735. * @param $diff (int) If passed, this will be set to the total char number difference between alias and replacements.
  8736. * @return replaced page content and updated $diff parameter as array.
  8737. * @protected
  8738. */
  8739. protected function replacePageNumAliases($page, $replace, $diff=0) {
  8740. foreach ($replace as $rep) {
  8741. foreach ($rep[3] as $a) {
  8742. if (strpos($page, $a) !== false) {
  8743. $page = str_replace($a, $rep[0], $page);
  8744. $diff += ($rep[2] - $rep[1]);
  8745. }
  8746. }
  8747. }
  8748. return array($page, $diff);
  8749. }
  8750. /**
  8751. * Replace right shift page number aliases with spaces to correct right alignment.
  8752. * This works perfectly only when using monospaced fonts.
  8753. * @param $page (string) Page content.
  8754. * @param $aliases (array) Array of page aliases.
  8755. * @param $diff (int) initial difference to add.
  8756. * @return replaced page content.
  8757. * @protected
  8758. */
  8759. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  8760. foreach ($aliases as $type => $alias) {
  8761. foreach ($alias as $a) {
  8762. // find position of compensation factor
  8763. $startnum = (strpos($a, ':') + 1);
  8764. $a = substr($a, 0, $startnum);
  8765. if (($pos = strpos($page, $a)) !== false) {
  8766. // end of alias
  8767. $endnum = strpos($page, '}', $pos);
  8768. // string to be replaced
  8769. $aa = substr($page, $pos, ($endnum - $pos + 1));
  8770. // get compensation factor
  8771. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  8772. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  8773. $ratio = floatval($ratio);
  8774. if ($type == 'u') {
  8775. $chrdiff = floor(($diff + 12) * $ratio);
  8776. $shift = str_repeat(' ', $chrdiff);
  8777. $shift = $this->UTF8ToUTF16BE($shift, false);
  8778. } else {
  8779. $chrdiff = floor(($diff + 11) * $ratio);
  8780. $shift = str_repeat(' ', $chrdiff);
  8781. }
  8782. $page = str_replace($aa, $shift, $page);
  8783. }
  8784. }
  8785. }
  8786. return $page;
  8787. }
  8788. /**
  8789. * Set page boxes to be included on page descriptions.
  8790. * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
  8791. * @protected
  8792. */
  8793. protected function setPageBoxTypes($boxes) {
  8794. $validboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  8795. $this->page_boxes = array();
  8796. foreach ($boxes as $box) {
  8797. if (in_array($box, $validboxes)) {
  8798. $this->page_boxes[] = $box;
  8799. }
  8800. }
  8801. }
  8802. /**
  8803. * Output pages (and replace page number aliases).
  8804. * @protected
  8805. */
  8806. protected function _putpages() {
  8807. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8808. // get internal aliases for page numbers
  8809. $pnalias = $this->getAllInternalPageNumberAliases();
  8810. $num_pages = $this->numpages;
  8811. $ptpa = $this->formatPageNumber(($this->starting_page_number + $num_pages - 1));
  8812. $ptpu = $this->UTF8ToUTF16BE($ptpa, false);
  8813. $ptp_num_chars = $this->GetNumChars($ptpa);
  8814. $pagegroupnum = 0;
  8815. $groupnum = 0;
  8816. $ptgu = 1;
  8817. $ptga = 1;
  8818. for ($n = 1; $n <= $num_pages; ++$n) {
  8819. // get current page
  8820. $temppage = $this->getPageBuffer($n);
  8821. $pagelen = strlen($temppage);
  8822. // set replacements for total pages number
  8823. $pnpa = $this->formatPageNumber(($this->starting_page_number + $n - 1));
  8824. $pnpu = $this->UTF8ToUTF16BE($pnpa, false);
  8825. $pnp_num_chars = $this->GetNumChars($pnpa);
  8826. $pdiff = 0; // difference used for right shift alignment of page numbers
  8827. $gdiff = 0; // difference used for right shift alignment of page group numbers
  8828. if (!empty($this->pagegroups)) {
  8829. if (isset($this->newpagegroup[$n])) {
  8830. $pagegroupnum = 0;
  8831. ++$groupnum;
  8832. $ptga = $this->formatPageNumber($this->pagegroups[$groupnum]);
  8833. $ptgu = $this->UTF8ToUTF16BE($ptga, false);
  8834. $ptg_num_chars = $this->GetNumChars($ptga);
  8835. }
  8836. ++$pagegroupnum;
  8837. $pnga = $this->formatPageNumber($pagegroupnum);
  8838. $pngu = $this->UTF8ToUTF16BE($pnga, false);
  8839. $png_num_chars = $this->GetNumChars($pnga);
  8840. // replace page numbers
  8841. $replace = array();
  8842. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  8843. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  8844. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  8845. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  8846. list($temppage, $gdiff) = $this->replacePageNumAliases($temppage, $replace, $gdiff);
  8847. }
  8848. // replace page numbers
  8849. $replace = array();
  8850. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  8851. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  8852. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  8853. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  8854. list($temppage, $pdiff) = $this->replacePageNumAliases($temppage, $replace, $pdiff);
  8855. // replace right shift alias
  8856. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  8857. // replace EPS marker
  8858. $temppage = str_replace($this->epsmarker, '', $temppage);
  8859. //Page
  8860. $this->page_obj_id[$n] = $this->_newobj();
  8861. $out = '<<';
  8862. $out .= ' /Type /Page';
  8863. $out .= ' /Parent 1 0 R';
  8864. $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
  8865. $out .= ' /Resources 2 0 R';
  8866. foreach ($this->page_boxes as $box) {
  8867. $out .= ' /'.$box;
  8868. $out .= sprintf(' [%F %F %F %F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']);
  8869. }
  8870. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  8871. $out .= ' /BoxColorInfo <<';
  8872. foreach ($this->page_boxes as $box) {
  8873. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  8874. $out .= ' /'.$box.' <<';
  8875. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  8876. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  8877. $out .= ' /C [';
  8878. $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  8879. $out .= ' ]';
  8880. }
  8881. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  8882. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  8883. }
  8884. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  8885. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  8886. }
  8887. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  8888. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  8889. $out .= ' /D [';
  8890. foreach ($dashes as $dash) {
  8891. $out .= sprintf(' %F', ($dash * $this->k));
  8892. }
  8893. $out .= ' ]';
  8894. }
  8895. $out .= ' >>';
  8896. }
  8897. }
  8898. $out .= ' >>';
  8899. }
  8900. $out .= ' /Contents '.($this->n + 1).' 0 R';
  8901. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  8902. if (!$this->pdfa_mode) {
  8903. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  8904. }
  8905. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  8906. // page transitions
  8907. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  8908. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  8909. }
  8910. $out .= ' /Trans <<';
  8911. $out .= ' /Type /Trans';
  8912. if (isset($this->pagedim[$n]['trans']['S'])) {
  8913. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  8914. }
  8915. if (isset($this->pagedim[$n]['trans']['D'])) {
  8916. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  8917. }
  8918. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  8919. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  8920. }
  8921. if (isset($this->pagedim[$n]['trans']['M'])) {
  8922. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  8923. }
  8924. if (isset($this->pagedim[$n]['trans']['Di'])) {
  8925. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  8926. }
  8927. if (isset($this->pagedim[$n]['trans']['SS'])) {
  8928. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  8929. }
  8930. if (isset($this->pagedim[$n]['trans']['B'])) {
  8931. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  8932. }
  8933. $out .= ' >>';
  8934. }
  8935. $out .= $this->_getannotsrefs($n);
  8936. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  8937. $out .= ' >>';
  8938. $out .= "\n".'endobj';
  8939. $this->_out($out);
  8940. //Page content
  8941. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  8942. $this->_newobj();
  8943. $p = $this->_getrawstream($p);
  8944. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  8945. if ($this->diskcache) {
  8946. // remove temporary files
  8947. unlink($this->pages[$n]);
  8948. }
  8949. }
  8950. //Pages root
  8951. $out = $this->_getobj(1)."\n";
  8952. $out .= '<< /Type /Pages /Kids [';
  8953. foreach($this->page_obj_id as $page_obj) {
  8954. $out .= ' '.$page_obj.' 0 R';
  8955. }
  8956. $out .= ' ] /Count '.$num_pages.' >>';
  8957. $out .= "\n".'endobj';
  8958. $this->_out($out);
  8959. }
  8960. /**
  8961. * Output references to page annotations
  8962. * @param $n (int) page number
  8963. * @protected
  8964. * @author Nicola Asuni
  8965. * @since 4.7.000 (2008-08-29)
  8966. * @deprecated
  8967. */
  8968. protected function _putannotsrefs($n) {
  8969. $this->_out($this->_getannotsrefs($n));
  8970. }
  8971. /**
  8972. * Get references to page annotations.
  8973. * @param $n (int) page number
  8974. * @return string
  8975. * @protected
  8976. * @author Nicola Asuni
  8977. * @since 5.0.010 (2010-05-17)
  8978. */
  8979. protected function _getannotsrefs($n) {
  8980. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  8981. return '';
  8982. }
  8983. $out = ' /Annots [';
  8984. if (isset($this->PageAnnots[$n])) {
  8985. foreach ($this->PageAnnots[$n] as $key => $val) {
  8986. if (!in_array($val['n'], $this->radio_groups)) {
  8987. $out .= ' '.$val['n'].' 0 R';
  8988. }
  8989. }
  8990. // add radiobutton groups
  8991. if (isset($this->radiobutton_groups[$n])) {
  8992. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  8993. if (isset($data['n'])) {
  8994. $out .= ' '.$data['n'].' 0 R';
  8995. }
  8996. }
  8997. }
  8998. }
  8999. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  9000. // set reference for signature object
  9001. $out .= ' '.$this->sig_obj_id.' 0 R';
  9002. }
  9003. if (!empty($this->empty_signature_appearance)) {
  9004. foreach ($this->empty_signature_appearance as $esa) {
  9005. if ($esa['page'] == $n) {
  9006. // set reference for empty signature objects
  9007. $out .= ' '.$esa['objid'].' 0 R';
  9008. }
  9009. }
  9010. }
  9011. $out .= ' ]';
  9012. return $out;
  9013. }
  9014. /**
  9015. * Output annotations objects for all pages.
  9016. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  9017. * See section 12.5 of PDF 32000_2008 reference.
  9018. * @protected
  9019. * @author Nicola Asuni
  9020. * @since 4.0.018 (2008-08-06)
  9021. */
  9022. protected function _putannotsobjs() {
  9023. // reset object counter
  9024. for ($n=1; $n <= $this->numpages; ++$n) {
  9025. if (isset($this->PageAnnots[$n])) {
  9026. // set page annotations
  9027. foreach ($this->PageAnnots[$n] as $key => $pl) {
  9028. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  9029. // create annotation object for grouping radiobuttons
  9030. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  9031. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  9032. $annots = '<<';
  9033. $annots .= ' /Type /Annot';
  9034. $annots .= ' /Subtype /Widget';
  9035. $annots .= ' /Rect [0 0 0 0]';
  9036. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  9037. // read only
  9038. $annots .= ' /F 68';
  9039. $annots .= ' /Ff 49153';
  9040. } else {
  9041. $annots .= ' /F 4'; // default print for PDF/A
  9042. $annots .= ' /Ff 49152';
  9043. }
  9044. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  9045. $annots .= ' /FT /Btn';
  9046. $annots .= ' /Kids [';
  9047. $defval = '';
  9048. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  9049. if (isset($data['kid'])) {
  9050. $annots .= ' '.$data['kid'].' 0 R';
  9051. if ($data['def'] !== 'Off') {
  9052. $defval = $data['def'];
  9053. }
  9054. }
  9055. }
  9056. $annots .= ' ]';
  9057. if (!empty($defval)) {
  9058. $annots .= ' /V /'.$defval;
  9059. }
  9060. $annots .= ' >>';
  9061. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  9062. $this->form_obj_id[] = $radio_button_obj_id;
  9063. // store object id to be used on Parent entry of Kids
  9064. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  9065. }
  9066. $formfield = false;
  9067. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  9068. $a = $pl['x'] * $this->k;
  9069. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  9070. $c = $pl['w'] * $this->k;
  9071. $d = $pl['h'] * $this->k;
  9072. $rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
  9073. // create new annotation object
  9074. $annots = '<</Type /Annot';
  9075. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  9076. $annots .= ' /Rect ['.$rect.']';
  9077. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  9078. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  9079. $annots .= ' /FT /'.$pl['opt']['ft'];
  9080. $formfield = true;
  9081. }
  9082. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  9083. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  9084. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  9085. $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
  9086. if (isset($pl['opt']['f'])) {
  9087. $fval = 0;
  9088. if (is_array($pl['opt']['f'])) {
  9089. foreach ($pl['opt']['f'] as $f) {
  9090. switch (strtolower($f)) {
  9091. case 'invisible': {
  9092. $fval += 1 << 0;
  9093. break;
  9094. }
  9095. case 'hidden': {
  9096. $fval += 1 << 1;
  9097. break;
  9098. }
  9099. case 'print': {
  9100. $fval += 1 << 2;
  9101. break;
  9102. }
  9103. case 'nozoom': {
  9104. $fval += 1 << 3;
  9105. break;
  9106. }
  9107. case 'norotate': {
  9108. $fval += 1 << 4;
  9109. break;
  9110. }
  9111. case 'noview': {
  9112. $fval += 1 << 5;
  9113. break;
  9114. }
  9115. case 'readonly': {
  9116. $fval += 1 << 6;
  9117. break;
  9118. }
  9119. case 'locked': {
  9120. $fval += 1 << 8;
  9121. break;
  9122. }
  9123. case 'togglenoview': {
  9124. $fval += 1 << 9;
  9125. break;
  9126. }
  9127. case 'lockedcontents': {
  9128. $fval += 1 << 10;
  9129. break;
  9130. }
  9131. default: {
  9132. break;
  9133. }
  9134. }
  9135. }
  9136. } else {
  9137. $fval = intval($pl['opt']['f']);
  9138. }
  9139. } else {
  9140. $fval = 4;
  9141. }
  9142. if ($this->pdfa_mode) {
  9143. // force print flag for PDF/A mode
  9144. $fval |= 4;
  9145. }
  9146. $annots .= ' /F '.intval($fval);
  9147. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  9148. $annots .= ' /AS /'.$pl['opt']['as'];
  9149. }
  9150. if (isset($pl['opt']['ap'])) {
  9151. // appearance stream
  9152. $annots .= ' /AP <<';
  9153. if (is_array($pl['opt']['ap'])) {
  9154. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  9155. // $apmode can be: n = normal; r = rollover; d = down;
  9156. $annots .= ' /'.strtoupper($apmode);
  9157. if (is_array($apdef)) {
  9158. $annots .= ' <<';
  9159. foreach ($apdef as $apstate => $stream) {
  9160. // reference to XObject that define the appearance for this mode-state
  9161. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  9162. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  9163. }
  9164. $annots .= ' >>';
  9165. } else {
  9166. // reference to XObject that define the appearance for this mode
  9167. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  9168. $annots .= ' '.$apsobjid.' 0 R';
  9169. }
  9170. }
  9171. } else {
  9172. $annots .= $pl['opt']['ap'];
  9173. }
  9174. $annots .= ' >>';
  9175. }
  9176. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  9177. $annots .= ' /BS <<';
  9178. $annots .= ' /Type /Border';
  9179. if (isset($pl['opt']['bs']['w'])) {
  9180. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  9181. }
  9182. $bstyles = array('S', 'D', 'B', 'I', 'U');
  9183. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  9184. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  9185. }
  9186. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  9187. $annots .= ' /D [';
  9188. foreach ($pl['opt']['bs']['d'] as $cord) {
  9189. $annots .= ' '.intval($cord);
  9190. }
  9191. $annots .= ']';
  9192. }
  9193. $annots .= ' >>';
  9194. } else {
  9195. $annots .= ' /Border [';
  9196. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  9197. $annots .= intval($pl['opt']['border'][0]).' ';
  9198. $annots .= intval($pl['opt']['border'][1]).' ';
  9199. $annots .= intval($pl['opt']['border'][2]);
  9200. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  9201. $annots .= ' [';
  9202. foreach ($pl['opt']['border'][3] as $dash) {
  9203. $annots .= intval($dash).' ';
  9204. }
  9205. $annots .= ']';
  9206. }
  9207. } else {
  9208. $annots .= '0 0 0';
  9209. }
  9210. $annots .= ']';
  9211. }
  9212. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  9213. $annots .= ' /BE <<';
  9214. $bstyles = array('S', 'C');
  9215. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
  9216. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  9217. } else {
  9218. $annots .= ' /S /S';
  9219. }
  9220. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  9221. $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
  9222. }
  9223. $annots .= '>>';
  9224. }
  9225. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  9226. $annots .= ' /C '.$this->getColorStringFromArray($pl['opt']['c']);
  9227. }
  9228. //$annots .= ' /StructParent ';
  9229. //$annots .= ' /OC ';
  9230. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  9231. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  9232. // this is a markup type
  9233. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  9234. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  9235. }
  9236. //$annots .= ' /Popup ';
  9237. if (isset($pl['opt']['ca'])) {
  9238. $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
  9239. }
  9240. if (isset($pl['opt']['rc'])) {
  9241. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  9242. }
  9243. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
  9244. //$annots .= ' /IRT ';
  9245. if (isset($pl['opt']['subj'])) {
  9246. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  9247. }
  9248. //$annots .= ' /RT ';
  9249. //$annots .= ' /IT ';
  9250. //$annots .= ' /ExData ';
  9251. }
  9252. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  9253. // Annotation types
  9254. switch (strtolower($pl['opt']['subtype'])) {
  9255. case 'text': {
  9256. if (isset($pl['opt']['open'])) {
  9257. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  9258. }
  9259. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  9260. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  9261. $annots .= ' /Name /'.$pl['opt']['name'];
  9262. } else {
  9263. $annots .= ' /Name /Note';
  9264. }
  9265. $statemodels = array('Marked', 'Review');
  9266. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  9267. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  9268. } else {
  9269. $pl['opt']['statemodel'] = 'Marked';
  9270. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  9271. }
  9272. if ($pl['opt']['statemodel'] == 'Marked') {
  9273. $states = array('Accepted', 'Unmarked');
  9274. } else {
  9275. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  9276. }
  9277. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  9278. $annots .= ' /State /'.$pl['opt']['state'];
  9279. } else {
  9280. if ($pl['opt']['statemodel'] == 'Marked') {
  9281. $annots .= ' /State /Unmarked';
  9282. } else {
  9283. $annots .= ' /State /None';
  9284. }
  9285. }
  9286. break;
  9287. }
  9288. case 'link': {
  9289. if (is_string($pl['txt'])) {
  9290. // external URI link
  9291. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  9292. } else {
  9293. // internal link
  9294. if (isset($this->links[$pl['txt']])) {
  9295. $l = $this->links[$pl['txt']];
  9296. if (isset($this->page_obj_id[($l[0])])) {
  9297. $annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l[0])], ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
  9298. }
  9299. }
  9300. }
  9301. $hmodes = array('N', 'I', 'O', 'P');
  9302. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  9303. $annots .= ' /H /'.$pl['opt']['h'];
  9304. } else {
  9305. $annots .= ' /H /I';
  9306. }
  9307. //$annots .= ' /PA ';
  9308. //$annots .= ' /Quadpoints ';
  9309. break;
  9310. }
  9311. case 'freetext': {
  9312. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  9313. $annots .= ' /DA ('.$pl['opt']['da'].')';
  9314. }
  9315. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  9316. $annots .= ' /Q '.intval($pl['opt']['q']);
  9317. }
  9318. if (isset($pl['opt']['rc'])) {
  9319. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  9320. }
  9321. if (isset($pl['opt']['ds'])) {
  9322. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  9323. }
  9324. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  9325. $annots .= ' /CL [';
  9326. foreach ($pl['opt']['cl'] as $cl) {
  9327. $annots .= sprintf('%F ', $cl * $this->k);
  9328. }
  9329. $annots .= ']';
  9330. }
  9331. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  9332. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  9333. $annots .= ' /IT /'.$pl['opt']['it'];
  9334. }
  9335. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  9336. $l = $pl['opt']['rd'][0] * $this->k;
  9337. $r = $pl['opt']['rd'][1] * $this->k;
  9338. $t = $pl['opt']['rd'][2] * $this->k;
  9339. $b = $pl['opt']['rd'][3] * $this->k;
  9340. $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
  9341. }
  9342. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  9343. $annots .= ' /LE /'.$pl['opt']['le'];
  9344. }
  9345. break;
  9346. }
  9347. case 'line': {
  9348. break;
  9349. }
  9350. case 'square': {
  9351. break;
  9352. }
  9353. case 'circle': {
  9354. break;
  9355. }
  9356. case 'polygon': {
  9357. break;
  9358. }
  9359. case 'polyline': {
  9360. break;
  9361. }
  9362. case 'highlight': {
  9363. break;
  9364. }
  9365. case 'underline': {
  9366. break;
  9367. }
  9368. case 'squiggly': {
  9369. break;
  9370. }
  9371. case 'strikeout': {
  9372. break;
  9373. }
  9374. case 'stamp': {
  9375. break;
  9376. }
  9377. case 'caret': {
  9378. break;
  9379. }
  9380. case 'ink': {
  9381. break;
  9382. }
  9383. case 'popup': {
  9384. break;
  9385. }
  9386. case 'fileattachment': {
  9387. if ($this->pdfa_mode) {
  9388. // embedded files are not allowed in PDF/A mode
  9389. break;
  9390. }
  9391. if (!isset($pl['opt']['fs'])) {
  9392. break;
  9393. }
  9394. $filename = basename($pl['opt']['fs']);
  9395. if (isset($this->embeddedfiles[$filename]['n'])) {
  9396. $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
  9397. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  9398. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  9399. $annots .= ' /Name /'.$pl['opt']['name'];
  9400. } else {
  9401. $annots .= ' /Name /PushPin';
  9402. }
  9403. }
  9404. break;
  9405. }
  9406. case 'sound': {
  9407. if (!isset($pl['opt']['fs'])) {
  9408. break;
  9409. }
  9410. $filename = basename($pl['opt']['fs']);
  9411. if (isset($this->embeddedfiles[$filename]['n'])) {
  9412. // ... TO BE COMPLETED ...
  9413. // /R /C /B /E /CO /CP
  9414. $annots .= ' /Sound <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
  9415. $iconsapp = array('Speaker', 'Mic');
  9416. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  9417. $annots .= ' /Name /'.$pl['opt']['name'];
  9418. } else {
  9419. $annots .= ' /Name /Speaker';
  9420. }
  9421. }
  9422. break;
  9423. }
  9424. case 'movie': {
  9425. break;
  9426. }
  9427. case 'widget': {
  9428. $hmode = array('N', 'I', 'O', 'P', 'T');
  9429. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  9430. $annots .= ' /H /'.$pl['opt']['h'];
  9431. }
  9432. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  9433. $annots .= ' /MK <<';
  9434. if (isset($pl['opt']['mk']['r'])) {
  9435. $annots .= ' /R '.$pl['opt']['mk']['r'];
  9436. }
  9437. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  9438. $annots .= ' /BC '.$this->getColorStringFromArray($pl['opt']['mk']['bc']);
  9439. }
  9440. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  9441. $annots .= ' /BG '.$this->getColorStringFromArray($pl['opt']['mk']['bg']);
  9442. }
  9443. if (isset($pl['opt']['mk']['ca'])) {
  9444. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  9445. }
  9446. if (isset($pl['opt']['mk']['rc'])) {
  9447. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  9448. }
  9449. if (isset($pl['opt']['mk']['ac'])) {
  9450. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  9451. }
  9452. if (isset($pl['opt']['mk']['i'])) {
  9453. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  9454. if ($info !== false) {
  9455. $annots .= ' /I '.$info['n'].' 0 R';
  9456. }
  9457. }
  9458. if (isset($pl['opt']['mk']['ri'])) {
  9459. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  9460. if ($info !== false) {
  9461. $annots .= ' /RI '.$info['n'].' 0 R';
  9462. }
  9463. }
  9464. if (isset($pl['opt']['mk']['ix'])) {
  9465. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  9466. if ($info !== false) {
  9467. $annots .= ' /IX '.$info['n'].' 0 R';
  9468. }
  9469. }
  9470. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  9471. $annots .= ' /IF <<';
  9472. $if_sw = array('A', 'B', 'S', 'N');
  9473. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  9474. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  9475. }
  9476. $if_s = array('A', 'P');
  9477. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  9478. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  9479. }
  9480. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  9481. $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  9482. }
  9483. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  9484. $annots .= ' /FB true';
  9485. }
  9486. $annots .= '>>';
  9487. }
  9488. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  9489. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  9490. }
  9491. $annots .= '>>';
  9492. } // end MK
  9493. // --- Entries for field dictionaries ---
  9494. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  9495. // set parent
  9496. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  9497. }
  9498. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  9499. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  9500. }
  9501. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  9502. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  9503. }
  9504. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  9505. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  9506. }
  9507. if (isset($pl['opt']['ff'])) {
  9508. if (is_array($pl['opt']['ff'])) {
  9509. // array of bit settings
  9510. $flag = 0;
  9511. foreach($pl['opt']['ff'] as $val) {
  9512. $flag += 1 << ($val - 1);
  9513. }
  9514. } else {
  9515. $flag = intval($pl['opt']['ff']);
  9516. }
  9517. $annots .= ' /Ff '.$flag;
  9518. }
  9519. if (isset($pl['opt']['maxlen'])) {
  9520. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  9521. }
  9522. if (isset($pl['opt']['v'])) {
  9523. $annots .= ' /V';
  9524. if (is_array($pl['opt']['v'])) {
  9525. foreach ($pl['opt']['v'] AS $optval) {
  9526. if (is_float($optval)) {
  9527. $optval = sprintf('%F', $optval);
  9528. }
  9529. $annots .= ' '.$optval;
  9530. }
  9531. } else {
  9532. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  9533. }
  9534. }
  9535. if (isset($pl['opt']['dv'])) {
  9536. $annots .= ' /DV';
  9537. if (is_array($pl['opt']['dv'])) {
  9538. foreach ($pl['opt']['dv'] AS $optval) {
  9539. if (is_float($optval)) {
  9540. $optval = sprintf('%F', $optval);
  9541. }
  9542. $annots .= ' '.$optval;
  9543. }
  9544. } else {
  9545. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  9546. }
  9547. }
  9548. if (isset($pl['opt']['rv'])) {
  9549. $annots .= ' /RV';
  9550. if (is_array($pl['opt']['rv'])) {
  9551. foreach ($pl['opt']['rv'] AS $optval) {
  9552. if (is_float($optval)) {
  9553. $optval = sprintf('%F', $optval);
  9554. }
  9555. $annots .= ' '.$optval;
  9556. }
  9557. } else {
  9558. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  9559. }
  9560. }
  9561. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  9562. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  9563. }
  9564. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  9565. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  9566. }
  9567. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  9568. $annots .= ' /DA ('.$pl['opt']['da'].')';
  9569. }
  9570. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  9571. $annots .= ' /Q '.intval($pl['opt']['q']);
  9572. }
  9573. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  9574. $annots .= ' /Opt [';
  9575. foreach($pl['opt']['opt'] AS $copt) {
  9576. if (is_array($copt)) {
  9577. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  9578. } else {
  9579. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  9580. }
  9581. }
  9582. $annots .= ']';
  9583. }
  9584. if (isset($pl['opt']['ti'])) {
  9585. $annots .= ' /TI '.intval($pl['opt']['ti']);
  9586. }
  9587. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  9588. $annots .= ' /I [';
  9589. foreach($pl['opt']['i'] AS $copt) {
  9590. $annots .= intval($copt).' ';
  9591. }
  9592. $annots .= ']';
  9593. }
  9594. break;
  9595. }
  9596. case 'screen': {
  9597. break;
  9598. }
  9599. case 'printermark': {
  9600. break;
  9601. }
  9602. case 'trapnet': {
  9603. break;
  9604. }
  9605. case 'watermark': {
  9606. break;
  9607. }
  9608. case '3d': {
  9609. break;
  9610. }
  9611. default: {
  9612. break;
  9613. }
  9614. }
  9615. $annots .= '>>';
  9616. // create new annotation object
  9617. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  9618. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  9619. // store reference of form object
  9620. $this->form_obj_id[] = $annot_obj_id;
  9621. }
  9622. }
  9623. }
  9624. } // end for each page
  9625. }
  9626. /**
  9627. * Put appearance streams XObject used to define annotation's appearance states.
  9628. * @param $w (int) annotation width
  9629. * @param $h (int) annotation height
  9630. * @param $stream (string) appearance stream
  9631. * @return int object ID
  9632. * @protected
  9633. * @since 4.8.001 (2009-09-09)
  9634. */
  9635. protected function _putAPXObject($w=0, $h=0, $stream='') {
  9636. $stream = trim($stream);
  9637. $out = $this->_getobj()."\n";
  9638. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  9639. $out .= '<<';
  9640. $out .= ' /Type /XObject';
  9641. $out .= ' /Subtype /Form';
  9642. $out .= ' /FormType 1';
  9643. if ($this->compress) {
  9644. $stream = gzcompress($stream);
  9645. $out .= ' /Filter /FlateDecode';
  9646. }
  9647. $rect = sprintf('%F %F', $w, $h);
  9648. $out .= ' /BBox [0 0 '.$rect.']';
  9649. $out .= ' /Matrix [1 0 0 1 0 0]';
  9650. $out .= ' /Resources 2 0 R';
  9651. $stream = $this->_getrawstream($stream);
  9652. $out .= ' /Length '.strlen($stream);
  9653. $out .= ' >>';
  9654. $out .= ' stream'."\n".$stream."\n".'endstream';
  9655. $out .= "\n".'endobj';
  9656. $this->_out($out);
  9657. return $this->n;
  9658. }
  9659. /**
  9660. * Get ULONG from string (Big Endian 32-bit unsigned integer).
  9661. * @param $str (string) string from where to extract value
  9662. * @param $offset (int) point from where to read the data
  9663. * @return int 32 bit value
  9664. * @author Nicola Asuni
  9665. * @protected
  9666. * @since 5.2.000 (2010-06-02)
  9667. */
  9668. protected function _getULONG($str, $offset) {
  9669. $v = unpack('Ni', substr($str, $offset, 4));
  9670. return $v['i'];
  9671. }
  9672. /**
  9673. * Get USHORT from string (Big Endian 16-bit unsigned integer).
  9674. * @param $str (string) string from where to extract value
  9675. * @param $offset (int) point from where to read the data
  9676. * @return int 16 bit value
  9677. * @author Nicola Asuni
  9678. * @protected
  9679. * @since 5.2.000 (2010-06-02)
  9680. */
  9681. protected function _getUSHORT($str, $offset) {
  9682. $v = unpack('ni', substr($str, $offset, 2));
  9683. return $v['i'];
  9684. }
  9685. /**
  9686. * Get SHORT from string (Big Endian 16-bit signed integer).
  9687. * @param $str (string) String from where to extract value.
  9688. * @param $offset (int) Point from where to read the data.
  9689. * @return int 16 bit value
  9690. * @author Nicola Asuni
  9691. * @protected
  9692. * @since 5.2.000 (2010-06-02)
  9693. */
  9694. protected function _getSHORT($str, $offset) {
  9695. $v = unpack('si', substr($str, $offset, 2));
  9696. return $v['i'];
  9697. }
  9698. /**
  9699. * Get FWORD from string (Big Endian 16-bit signed integer).
  9700. * @param $str (string) String from where to extract value.
  9701. * @param $offset (int) Point from where to read the data.
  9702. * @return int 16 bit value
  9703. * @author Nicola Asuni
  9704. * @protected
  9705. * @since 5.9.123 (2011-09-30)
  9706. */
  9707. protected function _getFWORD($str, $offset) {
  9708. $v = $this->_getUSHORT($str, $offset);
  9709. if ($v > 0x7fff) {
  9710. $v -= 0x10000;
  9711. }
  9712. return $v;
  9713. }
  9714. /**
  9715. * Get UFWORD from string (Big Endian 16-bit unsigned integer).
  9716. * @param $str (string) string from where to extract value
  9717. * @param $offset (int) point from where to read the data
  9718. * @return int 16 bit value
  9719. * @author Nicola Asuni
  9720. * @protected
  9721. * @since 5.9.123 (2011-09-30)
  9722. */
  9723. protected function _getUFWORD($str, $offset) {
  9724. $v = $this->_getUSHORT($str, $offset);
  9725. return $v;
  9726. }
  9727. /**
  9728. * Get FIXED from string (32-bit signed fixed-point number (16.16).
  9729. * @param $str (string) string from where to extract value
  9730. * @param $offset (int) point from where to read the data
  9731. * @return int 16 bit value
  9732. * @author Nicola Asuni
  9733. * @protected
  9734. * @since 5.9.123 (2011-09-30)
  9735. */
  9736. protected function _getFIXED($str, $offset) {
  9737. // mantissa
  9738. $m = $this->_getFWORD($str, $offset);
  9739. // fraction
  9740. $f = $this->_getUSHORT($str, ($offset + 2));
  9741. $v = floatval(''.$m.'.'.$f.'');
  9742. return $v;
  9743. }
  9744. /**
  9745. * Get BYTE from string (8-bit unsigned integer).
  9746. * @param $str (string) String from where to extract value.
  9747. * @param $offset (int) Point from where to read the data.
  9748. * @return int 8 bit value
  9749. * @author Nicola Asuni
  9750. * @protected
  9751. * @since 5.2.000 (2010-06-02)
  9752. */
  9753. protected function _getBYTE($str, $offset) {
  9754. $v = unpack('Ci', substr($str, $offset, 1));
  9755. return $v['i'];
  9756. }
  9757. /**
  9758. * Update the CIDToGIDMap string with a new value.
  9759. * @param $map (string) CIDToGIDMap.
  9760. * @param $cid (int) CID value.
  9761. * @param $gid (int) GID value.
  9762. * @return (string) CIDToGIDMap.
  9763. * @author Nicola Asuni
  9764. * @protected
  9765. * @since 5.9.123 (2011-09-29)
  9766. */
  9767. protected function updateCIDtoGIDmap($map, $cid, $gid) {
  9768. if (($cid >= 0) AND ($cid <= 0xFFFF) AND ($gid >= 0)) {
  9769. if ($gid > 0xFFFF) {
  9770. $gid -= 0x10000;
  9771. }
  9772. $map[($cid * 2)] = chr($gid >> 8);
  9773. $map[(($cid * 2) + 1)] = chr($gid & 0xFF);
  9774. }
  9775. return $map;
  9776. }
  9777. /**
  9778. * Convert and add the selected TrueType or Type1 font to the fonts folder (that must be writeable).
  9779. * @param $fontfile (string) Font file (full path).
  9780. * @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.
  9781. * @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.
  9782. * @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.
  9783. * @param $outpath (string) Output path for generated font files (must be writeable by the web server). Leave empty for default font folder.
  9784. * @param $platid (int) Platform ID for CMAP table to extract (when building a Unicode font for Windows this value should be 3, for Macintosh should be 1).
  9785. * @param $encid (int) Encoding ID for CMAP table to extract (when building a Unicode font for Windows this value should be 1, for Macintosh should be 0). When Platform ID is 3, legal values for Encoding ID are: 0=Symbol, 1=Unicode, 2=ShiftJIS, 3=PRC, 4=Big5, 5=Wansung, 6=Johab, 7=Reserved, 8=Reserved, 9=Reserved, 10=UCS-4.
  9786. * @return (string) TCPDF font name.
  9787. * @author Nicola Asuni
  9788. * @public
  9789. * @since 5.9.123 (2010-09-30)
  9790. */
  9791. public function addTTFfont($fontfile, $fonttype='', $enc='', $flags=32, $outpath='', $platid=3, $encid=1) {
  9792. if (!file_exists($fontfile)) {
  9793. $this->Error('Could not find file: '.$fontfile.'');
  9794. }
  9795. // font metrics
  9796. $fmetric = array();
  9797. // build new font name for TCPDF compatibility
  9798. $font_path_parts = pathinfo($fontfile);
  9799. if (!isset($font_path_parts['filename'])) {
  9800. $font_path_parts['filename'] = substr($font_path_parts['basename'], 0, -(strlen($font_path_parts['extension']) + 1));
  9801. }
  9802. $font_name = strtolower($font_path_parts['filename']);
  9803. $font_name = preg_replace('/[^a-z0-9_]/', '', $font_name);
  9804. $search = array('bold', 'oblique', 'italic', 'regular');
  9805. $replace = array('b', 'i', 'i', '');
  9806. $font_name = str_replace($search, $replace, $font_name);
  9807. if (empty($font_name)) {
  9808. // set generic name
  9809. $font_name = 'tcpdffont';
  9810. }
  9811. // set output path
  9812. if (empty($outpath)) {
  9813. $outpath = $this->_getfontpath();
  9814. }
  9815. // check if this font already exist
  9816. if (file_exists($outpath.$font_name.'.php')) {
  9817. // this font already exist (delete it from fonts folder to rebuild it)
  9818. return $font_name;
  9819. }
  9820. $fmetric['file'] = $font_name.'.z';
  9821. $fmetric['ctg'] = $font_name.'.ctg.z';
  9822. // get font data
  9823. $font = file_get_contents($fontfile);
  9824. $fmetric['originalsize'] = strlen($font);
  9825. // autodetect font type
  9826. if (empty($fonttype)) {
  9827. if ($this->_getULONG($font, 0) == 0x10000) {
  9828. // True Type (Unicode or not)
  9829. $fonttype = 'TrueTypeUnicode';
  9830. } elseif (substr($font, 0, 4) == 'OTTO') {
  9831. // Open Type (Unicode or not)
  9832. $this->Error('Unsupported font format: OpenType with CFF data.');
  9833. } else {
  9834. // Type 1
  9835. $fonttype = 'Type1';
  9836. }
  9837. }
  9838. // set font type
  9839. switch ($fonttype) {
  9840. case 'CID0CT':
  9841. case 'CID0CS':
  9842. case 'CID0KR':
  9843. case 'CID0JP': {
  9844. $fmetric['type'] = 'cidfont0';
  9845. break;
  9846. }
  9847. case 'Type1': {
  9848. $fmetric['type'] = 'Type1';
  9849. if (empty($enc) AND (($flags & 4) == 0)) {
  9850. $enc = 'cp1252';
  9851. }
  9852. break;
  9853. }
  9854. case 'TrueType': {
  9855. $fmetric['type'] = 'TrueType';
  9856. break;
  9857. }
  9858. case 'TrueTypeUnicode':
  9859. default: {
  9860. $fmetric['type'] = 'TrueTypeUnicode';
  9861. break;
  9862. }
  9863. }
  9864. // set encoding maps (if any)
  9865. $fmetric['enc'] = preg_replace('/[^A-Za-z0-9_\-]/', '', $enc);
  9866. $fmetric['diff'] = '';
  9867. if (($fmetric['type'] == 'TrueType') OR ($fmetric['type'] == 'Type1')) {
  9868. if (!empty($enc) AND ($enc != 'cp1252') AND isset($this->encmaps->encmap[$enc])) {
  9869. // build differences from reference encoding
  9870. $enc_ref = $this->encmaps->encmap['cp1252'];
  9871. $enc_target = $this->encmaps->encmap[$enc];
  9872. $last = 0;
  9873. for ($i = 32; $i <= 255; ++$i) {
  9874. if ($enc_target != $enc_ref[$i]) {
  9875. if ($i != ($last + 1)) {
  9876. $fmetric['diff'] .= $i.' ';
  9877. }
  9878. $last = $i;
  9879. $fmetric['diff'] .= '/'.$enc_target[$i].' ';
  9880. }
  9881. }
  9882. }
  9883. }
  9884. // parse the font by type
  9885. if ($fmetric['type'] == 'Type1') {
  9886. // ---------- TYPE 1 ----------
  9887. // read first segment
  9888. $a = unpack('Cmarker/Ctype/Vsize', substr($font, 0, 6));
  9889. if ($a['marker'] != 128) {
  9890. $this->Error('Font file is not a valid binary Type1');
  9891. }
  9892. $fmetric['size1'] = $a['size'];
  9893. $data = substr($font, 6, $fmetric['size1']);
  9894. // read second segment
  9895. $a = unpack('Cmarker/Ctype/Vsize', substr($font, (6 + $fmetric['size1']), 6));
  9896. if ($a['marker'] != 128) {
  9897. $this->Error('Font file is not a valid binary Type1');
  9898. }
  9899. $fmetric['size2'] = $a['size'];
  9900. $encrypted = substr($font, (12 + $fmetric['size1']), $fmetric['size2']);
  9901. $data .= $encrypted;
  9902. // store compressed font
  9903. $fp = fopen($outpath.$fmetric['file'], 'wb');
  9904. fwrite($fp, gzcompress($data));
  9905. fclose($fp);
  9906. // get font info
  9907. $fmetric['Flags'] = $flags;
  9908. preg_match ('#/FullName[\s]*\(([^\)]*)#', $font, $matches);
  9909. $fmetric['name'] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $matches[1]);
  9910. preg_match('#/FontBBox[\s]*{([^}]*)#', $font, $matches);
  9911. $fmetric['bbox'] = trim($matches[1]);
  9912. $bv = explode(' ', $fmetric['bbox']);
  9913. $fmetric['Ascent'] = intval($bv[3]);
  9914. $fmetric['Descent'] = intval($bv[1]);
  9915. preg_match('#/ItalicAngle[\s]*([0-9\+\-]*)#', $font, $matches);
  9916. $fmetric['italicAngle'] = intval($matches[1]);
  9917. if ($fmetric['italicAngle'] != 0) {
  9918. $fmetric['Flags'] |= 64;
  9919. }
  9920. preg_match('#/UnderlinePosition[\s]*([0-9\+\-]*)#', $font, $matches);
  9921. $fmetric['underlinePosition'] = intval($matches[1]);
  9922. preg_match('#/UnderlineThickness[\s]*([0-9\+\-]*)#', $font, $matches);
  9923. $fmetric['underlineThickness'] = intval($matches[1]);
  9924. preg_match('#/isFixedPitch[\s]*([^\s]*)#', $font, $matches);
  9925. if ($matches[1] == 'true') {
  9926. $fmetric['Flags'] |= 1;
  9927. }
  9928. // get internal map
  9929. $imap = array();
  9930. if (preg_match_all('#dup[\s]([0-9]+)[\s]*/([^\s]*)[\s]put#sU', $font, $fmap, PREG_SET_ORDER) > 0) {
  9931. foreach ($fmap as $v) {
  9932. $imap[$v[2]] = $v[1];
  9933. }
  9934. }
  9935. // decrypt eexec encrypted part
  9936. $r = 55665; // eexec encryption constant
  9937. $c1 = 52845;
  9938. $c2 = 22719;
  9939. $elen = strlen($encrypted);
  9940. $eplain = '';
  9941. for ($i = 0; $i < $elen; ++$i) {
  9942. $chr = ord($encrypted[$i]);
  9943. $eplain .= chr($chr ^ ($r >> 8));
  9944. $r = ((($chr + $r) * $c1 + $c2) % 65536);
  9945. }
  9946. if (preg_match('#/ForceBold[\s]*([^\s]*)#', $eplain, $matches) > 0) {
  9947. if ($matches[1] == 'true') {
  9948. $fmetric['Flags'] |= 0x40000;
  9949. }
  9950. }
  9951. if (preg_match('#/StdVW[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  9952. $fmetric['StemV'] = intval($matches[1]);
  9953. } else {
  9954. $fmetric['StemV'] = 70;
  9955. }
  9956. if (preg_match('#/StdHW[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  9957. $fmetric['StemH'] = intval($matches[1]);
  9958. } else {
  9959. $fmetric['StemH'] = 30;
  9960. }
  9961. if (preg_match('#/BlueValues[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  9962. $bv = explode(' ', $matches[1]);
  9963. if (count($bv) >= 6) {
  9964. $v1 = intval($bv[2]);
  9965. $v2 = intval($bv[4]);
  9966. if ($v1 <= $v2) {
  9967. $fmetric['XHeight'] = $v1;
  9968. $fmetric['CapHeight'] = $v2;
  9969. } else {
  9970. $fmetric['XHeight'] = $v2;
  9971. $fmetric['CapHeight'] = $v1;
  9972. }
  9973. } else {
  9974. $fmetric['XHeight'] = 450;
  9975. $fmetric['CapHeight'] = 700;
  9976. }
  9977. } else {
  9978. $fmetric['XHeight'] = 450;
  9979. $fmetric['CapHeight'] = 700;
  9980. }
  9981. // get the number of random bytes at the beginning of charstrings
  9982. if (preg_match('#/lenIV[\s]*([0-9]*)#', $eplain, $matches) > 0) {
  9983. $lenIV = intval($matches[1]);
  9984. } else {
  9985. $lenIV = 4;
  9986. }
  9987. $fmetric['Leading'] = 0;
  9988. // get charstring data
  9989. $eplain = substr($eplain, (strpos($eplain, '/CharStrings') + 1));
  9990. preg_match_all('#/([A-Za-z0-9\.]*)[\s][0-9]+[\s]RD[\s](.*)[\s]ND#sU', $eplain, $matches, PREG_SET_ORDER);
  9991. if (!empty($enc) AND isset($this->encmaps->encmap[$enc])) {
  9992. $enc_map = $this->encmaps->encmap[$enc];
  9993. } else {
  9994. $enc_map = false;
  9995. }
  9996. $fmetric['cw'] = '';
  9997. $fmetric['MaxWidth'] = 0;
  9998. $cwidths = array();
  9999. foreach ($matches as $k => $v) {
  10000. $cid = 0;
  10001. if (isset($imap[$v[1]])) {
  10002. $cid = $imap[$v[1]];
  10003. } elseif ($enc_map !== false) {
  10004. $cid = array_search($v[1], $enc_map);
  10005. if ($cid === false) {
  10006. $cid = 0;
  10007. } elseif ($cid > 1000) {
  10008. $cid -= 1000;
  10009. }
  10010. }
  10011. // decrypt charstring encrypted part
  10012. $r = 4330; // charstring encryption constant
  10013. $c1 = 52845;
  10014. $c2 = 22719;
  10015. $cd = $v[2];
  10016. $clen = strlen($cd);
  10017. $ccom = array();
  10018. for ($i = 0; $i < $clen; ++$i) {
  10019. $chr = ord($cd[$i]);
  10020. $ccom[] = ($chr ^ ($r >> 8));
  10021. $r = ((($chr + $r) * $c1 + $c2) % 65536);
  10022. }
  10023. // decode numbers
  10024. $cdec = array();
  10025. $ck = 0;
  10026. $i = $lenIV;
  10027. while ($i < $clen) {
  10028. if ($ccom[$i] < 32) {
  10029. $cdec[$ck] = $ccom[$i];
  10030. if (($ck > 0) AND ($cdec[$ck] == 13)) {
  10031. // hsbw command: update width
  10032. $cwidths[$cid] = $cdec[($ck - 1)];
  10033. }
  10034. ++$i;
  10035. } elseif (($ccom[$i] >= 32) AND ($ccom[$i] <= 246)) {
  10036. $cdec[$ck] = ($ccom[$i] - 139);
  10037. ++$i;
  10038. } elseif (($ccom[$i] >= 247) AND ($ccom[$i] <= 250)) {
  10039. $cdec[$ck] = ((($ccom[$i] - 247) * 256) + $ccom[($i + 1)] + 108);
  10040. $i += 2;
  10041. } elseif (($ccom[$i] >= 251) AND ($ccom[$i] <= 254)) {
  10042. $cdec[$ck] = ((-($ccom[$i] - 251) * 256) - $ccom[($i + 1)] - 108);
  10043. $i += 2;
  10044. } elseif ($ccom[$i] == 255) {
  10045. $sval = chr($ccom[($i + 1)]).chr($ccom[($i + 2)]).chr($ccom[($i + 3)]).chr($ccom[($i + 4)]);
  10046. $vsval = unpack('li', $sval);
  10047. $cdec[$ck] = $vsval['i'];
  10048. $i += 5;
  10049. }
  10050. ++$ck;
  10051. }
  10052. } // end for each matches
  10053. $fmetric['MissingWidth'] = $cwidths[0];
  10054. $fmetric['MaxWidth'] = $fmetric['MissingWidth'];
  10055. $fmetric['AvgWidth'] = 0;
  10056. // set chars widths
  10057. for ($cid = 0; $cid <= 255; ++$cid) {
  10058. if (isset($cwidths[$cid])) {
  10059. if ($cwidths[$cid] > $fmetric['MaxWidth']) {
  10060. $fmetric['MaxWidth'] = $cwidths[$cid];
  10061. }
  10062. $fmetric['AvgWidth'] += $cwidths[$cid];
  10063. $fmetric['cw'] .= ','.$cid.'=>'.$cwidths[$cid];
  10064. } else {
  10065. $fmetric['cw'] .= ','.$cid.'=>'.$fmetric['MissingWidth'];
  10066. }
  10067. }
  10068. $fmetric['AvgWidth'] = round($fmetric['AvgWidth'] / count($cwidths));
  10069. } else {
  10070. // ---------- TRUE TYPE ----------
  10071. if ($fmetric['type'] != 'cidfont0') {
  10072. // store compressed font
  10073. $fp = fopen($outpath.$fmetric['file'], 'wb');
  10074. fwrite($fp, gzcompress($font));
  10075. fclose($fp);
  10076. }
  10077. $offset = 0; // offset position of the font data
  10078. if ($this->_getULONG($font, $offset) != 0x10000) {
  10079. // sfnt version must be 0x00010000 for TrueType version 1.0.
  10080. return $font;
  10081. }
  10082. $offset += 4;
  10083. // get number of tables
  10084. $numTables = $this->_getUSHORT($font, $offset);
  10085. $offset += 2;
  10086. // skip searchRange, entrySelector and rangeShift
  10087. $offset += 6;
  10088. // tables array
  10089. $table = array();
  10090. // ---------- get tables ----------
  10091. for ($i = 0; $i < $numTables; ++$i) {
  10092. // get table info
  10093. $tag = substr($font, $offset, 4);
  10094. $offset += 4;
  10095. $table[$tag] = array();
  10096. $table[$tag]['checkSum'] = $this->_getULONG($font, $offset);
  10097. $offset += 4;
  10098. $table[$tag]['offset'] = $this->_getULONG($font, $offset);
  10099. $offset += 4;
  10100. $table[$tag]['length'] = $this->_getULONG($font, $offset);
  10101. $offset += 4;
  10102. }
  10103. // check magicNumber
  10104. $offset = $table['head']['offset'] + 12;
  10105. if ($this->_getULONG($font, $offset) != 0x5F0F3CF5) {
  10106. // magicNumber must be 0x5F0F3CF5
  10107. return $font;
  10108. }
  10109. $offset += 4;
  10110. $offset += 2; // skip flags
  10111. // get FUnits
  10112. $fmetric['unitsPerEm'] = $this->_getUSHORT($font, $offset);
  10113. $offset += 2;
  10114. // units ratio constant
  10115. $urk = (1000 / $fmetric['unitsPerEm']);
  10116. $offset += 16; // skip created, modified
  10117. $xMin = round($this->_getFWORD($font, $offset) * $urk);
  10118. $offset += 2;
  10119. $yMin = round($this->_getFWORD($font, $offset) * $urk);
  10120. $offset += 2;
  10121. $xMax = round($this->_getFWORD($font, $offset) * $urk);
  10122. $offset += 2;
  10123. $yMax = round($this->_getFWORD($font, $offset) * $urk);
  10124. $offset += 2;
  10125. $fmetric['bbox'] = ''.$xMin.' '.$yMin.' '.$xMax.' '.$yMax.'';
  10126. $macStyle = $this->_getUSHORT($font, $offset);
  10127. $offset += 2;
  10128. // PDF font flags
  10129. $fmetric['Flags'] = $flags;
  10130. if (($macStyle & 2) == 2) {
  10131. // italic flag
  10132. $fmetric['Flags'] |= 64;
  10133. }
  10134. // get offset mode (indexToLocFormat : 0 = short, 1 = long)
  10135. $offset = $table['head']['offset'] + 50;
  10136. $short_offset = ($this->_getSHORT($font, $offset) == 0);
  10137. $offset += 2;
  10138. // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
  10139. $indexToLoc = array();
  10140. $offset = $table['loca']['offset'];
  10141. if ($short_offset) {
  10142. // short version
  10143. $tot_num_glyphs = ($table['loca']['length'] / 2); // numGlyphs + 1
  10144. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10145. $indexToLoc[$i] = $this->_getUSHORT($font, $offset) * 2;
  10146. $offset += 2;
  10147. }
  10148. } else {
  10149. // long version
  10150. $tot_num_glyphs = ($table['loca']['length'] / 4); // numGlyphs + 1
  10151. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10152. $indexToLoc[$i] = $this->_getULONG($font, $offset);
  10153. $offset += 4;
  10154. }
  10155. }
  10156. // get glyphs indexes of chars from cmap table
  10157. $offset = $table['cmap']['offset'] + 2;
  10158. $numEncodingTables = $this->_getUSHORT($font, $offset);
  10159. $offset += 2;
  10160. $encodingTables = array();
  10161. for ($i = 0; $i < $numEncodingTables; ++$i) {
  10162. $encodingTables[$i]['platformID'] = $this->_getUSHORT($font, $offset);
  10163. $offset += 2;
  10164. $encodingTables[$i]['encodingID'] = $this->_getUSHORT($font, $offset);
  10165. $offset += 2;
  10166. $encodingTables[$i]['offset'] = $this->_getULONG($font, $offset);
  10167. $offset += 4;
  10168. }
  10169. // ---------- get os/2 metrics ----------
  10170. $offset = $table['OS/2']['offset'];
  10171. $offset += 2; // skip version
  10172. // xAvgCharWidth
  10173. $fmetric['AvgWidth'] = round($this->_getFWORD($font, $offset) * $urk);
  10174. $offset += 2;
  10175. // usWeightClass
  10176. $usWeightClass = round($this->_getUFWORD($font, $offset) * $urk);
  10177. // estimate StemV and StemH (400 = usWeightClass for Normal - Regular font)
  10178. $fmetric['StemV'] = round((70 * $usWeightClass) / 400);
  10179. $fmetric['StemH'] = round((30 * $usWeightClass) / 400);
  10180. $offset += 2;
  10181. $offset += 2; // usWidthClass
  10182. $fsType = $this->_getSHORT($font, $offset);
  10183. $offset += 2;
  10184. if ($fsType == 2) {
  10185. $this->Error('This Font cannot be modified, embedded or exchanged in any manner without first obtaining permission of the legal owner.');
  10186. }
  10187. // ---------- get font name ----------
  10188. $fmetric['name'] = '';
  10189. $offset = $table['name']['offset'];
  10190. $offset += 2; // skip Format selector (=0).
  10191. // Number of NameRecords that follow n.
  10192. $numNameRecords = $this->_getUSHORT($font, $offset);
  10193. $offset += 2;
  10194. // Offset to start of string storage (from start of table).
  10195. $stringStorageOffset = $this->_getUSHORT($font, $offset);
  10196. $offset += 2;
  10197. for ($i = 0; $i < $numNameRecords; ++$i) {
  10198. $offset += 6; // skip Platform ID, Platform-specific encoding ID, Language ID.
  10199. // Name ID.
  10200. $nameID = $this->_getUSHORT($font, $offset);
  10201. $offset += 2;
  10202. if ($nameID == 6) {
  10203. // String length (in bytes).
  10204. $stringLength = $this->_getUSHORT($font, $offset);
  10205. $offset += 2;
  10206. // String offset from start of storage area (in bytes).
  10207. $stringOffset = $this->_getUSHORT($font, $offset);
  10208. $offset += 2;
  10209. $offset = ($table['name']['offset'] + $stringStorageOffset + $stringOffset);
  10210. $fmetric['name'] = substr($font, $offset, $stringLength);
  10211. $fmetric['name'] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $fmetric['name']);
  10212. break;
  10213. } else {
  10214. $offset += 4; // skip String length, String offset
  10215. }
  10216. }
  10217. if (empty($fmetric['name'])) {
  10218. $fmetric['name'] = $font_name;
  10219. }
  10220. // ---------- get post data ----------
  10221. $offset = $table['post']['offset'];
  10222. $offset += 4; // skip Format Type
  10223. $fmetric['italicAngle'] = $this->_getFIXED($font, $offset);
  10224. $offset += 4;
  10225. $fmetric['underlinePosition'] = round($this->_getFWORD($font, $offset) * $urk);
  10226. $offset += 2;
  10227. $fmetric['underlineThickness'] = round($this->_getFWORD($font, $offset) * $urk);
  10228. $offset += 2;
  10229. $isFixedPitch = ($this->_getULONG($font, $offset) == 0) ? false : true;
  10230. $offset += 2;
  10231. if ($isFixedPitch) {
  10232. $fmetric['Flags'] |= 1;
  10233. }
  10234. // ---------- get hhea data ----------
  10235. $offset = $table['hhea']['offset'];
  10236. $offset += 4; // skip Table version number
  10237. // Ascender
  10238. $fmetric['Ascent'] = round($this->_getFWORD($font, $offset) * $urk);
  10239. $offset += 2;
  10240. // Descender
  10241. $fmetric['Descent'] = round($this->_getFWORD($font, $offset) * $urk);
  10242. $offset += 2;
  10243. // LineGap
  10244. $fmetric['Leading'] = round($this->_getFWORD($font, $offset) * $urk);
  10245. $offset += 2;
  10246. // advanceWidthMax
  10247. $fmetric['MaxWidth'] = round($this->_getUFWORD($font, $offset) * $urk);
  10248. $offset += 2;
  10249. $offset += 22; // skip some values
  10250. // get the number of hMetric entries in hmtx table
  10251. $numberOfHMetrics = $this->_getUSHORT($font, $offset);
  10252. // ---------- get maxp data ----------
  10253. $offset = $table['maxp']['offset'];
  10254. $offset += 4; // skip Table version number
  10255. // get the the number of glyphs in the font.
  10256. $numGlyphs = $this->_getUSHORT($font, $offset);
  10257. // ---------- get CIDToGIDMap ----------
  10258. $ctg = array();
  10259. foreach ($encodingTables as $enctable) {
  10260. // get only specified Platform ID and Encoding ID
  10261. if (($enctable['platformID'] == $platid) AND ($enctable['encodingID'] == $encid)) {
  10262. $offset = $table['cmap']['offset'] + $enctable['offset'];
  10263. $format = $this->_getUSHORT($font, $offset);
  10264. $offset += 2;
  10265. switch ($format) {
  10266. case 0: { // Format 0: Byte encoding table
  10267. $offset += 4; // skip length and version/language
  10268. for ($c = 0; $c < 256; ++$c) {
  10269. $g = $this->_getBYTE($font, $offset);
  10270. $ctg[$c] = $g;
  10271. ++$offset;
  10272. }
  10273. break;
  10274. }
  10275. case 2: { // Format 2: High-byte mapping through table
  10276. $offset += 4; // skip length and version/language
  10277. $numSubHeaders = 0;
  10278. for ($i = 0; $i < 256; ++$i) {
  10279. // Array that maps high bytes to subHeaders: value is subHeader index * 8.
  10280. $subHeaderKeys[$i] = ($this->_getUSHORT($font, $offset) / 8);
  10281. $offset += 2;
  10282. if ($numSubHeaders < $subHeaderKeys[$i]) {
  10283. $numSubHeaders = $subHeaderKeys[$i];
  10284. }
  10285. }
  10286. // the number of subHeaders is equal to the max of subHeaderKeys + 1
  10287. ++$numSubHeaders;
  10288. // read subHeader structures
  10289. $subHeaders = array();
  10290. $numGlyphIndexArray = 0;
  10291. for ($k = 0; $k < $numSubHeaders; ++$k) {
  10292. $subHeaders[$k]['firstCode'] = $this->_getUSHORT($font, $offset);
  10293. $offset += 2;
  10294. $subHeaders[$k]['entryCount'] = $this->_getUSHORT($font, $offset);
  10295. $offset += 2;
  10296. $subHeaders[$k]['idDelta'] = $this->_getUSHORT($font, $offset);
  10297. $offset += 2;
  10298. $subHeaders[$k]['idRangeOffset'] = $this->_getUSHORT($font, $offset);
  10299. $offset += 2;
  10300. $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
  10301. $subHeaders[$k]['idRangeOffset'] /= 2;
  10302. $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
  10303. }
  10304. for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
  10305. $glyphIndexArray[$k] = $this->_getUSHORT($font, $offset);
  10306. $offset += 2;
  10307. }
  10308. for ($i = 0; $i < 256; ++$i) {
  10309. $k = $subHeaderKeys[$i];
  10310. if ($k == 0) {
  10311. // one byte code
  10312. $c = $i;
  10313. $g = $glyphIndexArray[0];
  10314. $ctg[$c] = $g;
  10315. } else {
  10316. // two bytes code
  10317. $start_byte = $subHeaders[$k]['firstCode'];
  10318. $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
  10319. for ($j = $start_byte; $j < $end_byte; ++$j) {
  10320. // combine high and low bytes
  10321. $c = (($i << 8) + $j);
  10322. $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
  10323. $g = ($glyphIndexArray[$idRangeOffset] + $idDelta[$k]) % 65536;
  10324. if ($g < 0) {
  10325. $g = 0;
  10326. }
  10327. $ctg[$c] = $g;
  10328. }
  10329. }
  10330. }
  10331. break;
  10332. }
  10333. case 4: { // Format 4: Segment mapping to delta values
  10334. $length = $this->_getUSHORT($font, $offset);
  10335. $offset += 2;
  10336. $offset += 2; // skip version/language
  10337. $segCount = ($this->_getUSHORT($font, $offset) / 2);
  10338. $offset += 2;
  10339. $offset += 6; // skip searchRange, entrySelector, rangeShift
  10340. $endCount = array(); // array of end character codes for each segment
  10341. for ($k = 0; $k < $segCount; ++$k) {
  10342. $endCount[$k] = $this->_getUSHORT($font, $offset);
  10343. $offset += 2;
  10344. }
  10345. $offset += 2; // skip reservedPad
  10346. $startCount = array(); // array of start character codes for each segment
  10347. for ($k = 0; $k < $segCount; ++$k) {
  10348. $startCount[$k] = $this->_getUSHORT($font, $offset);
  10349. $offset += 2;
  10350. }
  10351. $idDelta = array(); // delta for all character codes in segment
  10352. for ($k = 0; $k < $segCount; ++$k) {
  10353. $idDelta[$k] = $this->_getUSHORT($font, $offset);
  10354. $offset += 2;
  10355. }
  10356. $idRangeOffset = array(); // Offsets into glyphIdArray or 0
  10357. for ($k = 0; $k < $segCount; ++$k) {
  10358. $idRangeOffset[$k] = $this->_getUSHORT($font, $offset);
  10359. $offset += 2;
  10360. }
  10361. $gidlen = ($length / 2) - 8 - (4 * $segCount);
  10362. $glyphIdArray = array(); // glyph index array
  10363. for ($k = 0; $k < $gidlen; ++$k) {
  10364. $glyphIdArray[$k] = $this->_getUSHORT($font, $offset);
  10365. $offset += 2;
  10366. }
  10367. for ($k = 0; $k < $segCount; ++$k) {
  10368. for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
  10369. if ($idRangeOffset[$k] == 0) {
  10370. $g = ($idDelta[$k] + $c) % 65536;
  10371. } else {
  10372. $gid = (($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
  10373. $g = ($glyphIdArray[$gid] + $idDelta[$k]) % 65536;
  10374. }
  10375. if ($g < 0) {
  10376. $g = 0;
  10377. }
  10378. $ctg[$c] = $g;
  10379. }
  10380. }
  10381. break;
  10382. }
  10383. case 6: { // Format 6: Trimmed table mapping
  10384. $offset += 4; // skip length and version/language
  10385. $firstCode = $this->_getUSHORT($font, $offset);
  10386. $offset += 2;
  10387. $entryCount = $this->_getUSHORT($font, $offset);
  10388. $offset += 2;
  10389. for ($k = 0; $k < $entryCount; ++$k) {
  10390. $c = ($k + $firstCode);
  10391. $g = $this->_getUSHORT($font, $offset);
  10392. $offset += 2;
  10393. $ctg[$c] = $g;
  10394. }
  10395. break;
  10396. }
  10397. case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
  10398. $offset += 10; // skip reserved, length and version/language
  10399. for ($k = 0; $k < 8192; ++$k) {
  10400. $is32[$k] = $this->_getBYTE($font, $offset);
  10401. ++$offset;
  10402. }
  10403. $nGroups = $this->_getULONG($font, $offset);
  10404. $offset += 4;
  10405. for ($i = 0; $i < $nGroups; ++$i) {
  10406. $startCharCode = $this->_getULONG($font, $offset);
  10407. $offset += 4;
  10408. $endCharCode = $this->_getULONG($font, $offset);
  10409. $offset += 4;
  10410. $startGlyphID = $this->_getULONG($font, $offset);
  10411. $offset += 4;
  10412. for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
  10413. $is32idx = floor($c / 8);
  10414. if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
  10415. $c = $k;
  10416. } else {
  10417. // 32 bit format
  10418. // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
  10419. //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
  10420. //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
  10421. $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
  10422. }
  10423. $ctg[$c] = 0;
  10424. ++$startGlyphID;
  10425. }
  10426. }
  10427. break;
  10428. }
  10429. case 10: { // Format 10: Trimmed array
  10430. $offset += 10; // skip reserved, length and version/language
  10431. $startCharCode = $this->_getULONG($font, $offset);
  10432. $offset += 4;
  10433. $numChars = $this->_getULONG($font, $offset);
  10434. $offset += 4;
  10435. for ($k = 0; $k < $numChars; ++$k) {
  10436. $c = ($k + $startCharCode);
  10437. $g = $this->_getUSHORT($font, $offset);
  10438. $ctg[$c] = $g;
  10439. $offset += 2;
  10440. }
  10441. break;
  10442. }
  10443. case 12: { // Format 12: Segmented coverage
  10444. $offset += 10; // skip length and version/language
  10445. $nGroups = $this->_getULONG($font, $offset);
  10446. $offset += 4;
  10447. for ($k = 0; $k < $nGroups; ++$k) {
  10448. $startCharCode = $this->_getULONG($font, $offset);
  10449. $offset += 4;
  10450. $endCharCode = $this->_getULONG($font, $offset);
  10451. $offset += 4;
  10452. $startGlyphCode = $this->_getULONG($font, $offset);
  10453. $offset += 4;
  10454. for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
  10455. $ctg[$c] = $startGlyphCode;
  10456. ++$startGlyphCode;
  10457. }
  10458. }
  10459. break;
  10460. }
  10461. case 13: { // Format 13: Many-to-one range mappings
  10462. // to be implemented ...
  10463. break;
  10464. }
  10465. case 14: { // Format 14: Unicode Variation Sequences
  10466. // to be implemented ...
  10467. break;
  10468. }
  10469. }
  10470. }
  10471. }
  10472. if (!isset($ctg[0])) {
  10473. $ctg[0] = 0;
  10474. }
  10475. // get xHeight (height of x)
  10476. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[120]] + 4);
  10477. $yMin = $this->_getFWORD($font, $offset);
  10478. $offset += 4;
  10479. $yMax = $this->_getFWORD($font, $offset);
  10480. $offset += 2;
  10481. $fmetric['XHeight'] = round(($yMax - $yMin) * $urk);
  10482. // get CapHeight (height of H)
  10483. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[72]] + 4);
  10484. $yMin = $this->_getFWORD($font, $offset);
  10485. $offset += 4;
  10486. $yMax = $this->_getFWORD($font, $offset);
  10487. $offset += 2;
  10488. $fmetric['CapHeight'] = round(($yMax - $yMin) * $urk);
  10489. // ceate widths array
  10490. $cw = array();
  10491. $offset = $table['hmtx']['offset'];
  10492. for ($i = 0 ; $i < $numberOfHMetrics; ++$i) {
  10493. $cw[$i] = round($this->_getUFWORD($font, $offset) * $urk);
  10494. $offset += 4; // skip lsb
  10495. }
  10496. if ($numberOfHMetrics < $numGlyphs) {
  10497. // fill missing widths with the last value
  10498. $cw = array_pad($cw, $numGlyphs, $cw[($numberOfHMetrics - 1)]);
  10499. }
  10500. $fmetric['MissingWidth'] = $cw[0];
  10501. $fmetric['cw'] = '';
  10502. for ($cid = 0; $cid <= 65535; ++$cid) {
  10503. if (isset($ctg[$cid]) AND isset($cw[$ctg[$cid]])) {
  10504. $fmetric['cw'] .= ','.$cid.'=>'.$cw[$ctg[$cid]];
  10505. }
  10506. }
  10507. } // end of true type
  10508. if (($fmetric['type'] == 'TrueTypeUnicode') AND (count($ctg) == 256)) {
  10509. $fmetric['type'] == 'TrueType';
  10510. }
  10511. // ---------- create php font file ----------
  10512. $pfile = '<'.'?'.'php'."\n";
  10513. $pfile .= '// TCPDF FONT FILE DESCRIPTION'."\n";
  10514. $pfile .= '$type=\''.$fmetric['type'].'\';'."\n";
  10515. $pfile .= '$name=\''.$fmetric['name'].'\';'."\n";
  10516. $pfile .= '$up='.$fmetric['underlinePosition'].';'."\n";
  10517. $pfile .= '$ut='.$fmetric['underlineThickness'].';'."\n";
  10518. if ($fmetric['MissingWidth'] > 0) {
  10519. $pfile .= '$dw='.$fmetric['MissingWidth'].';'."\n";
  10520. } else {
  10521. $pfile .= '$dw='.$fmetric['AvgWidth'].';'."\n";
  10522. }
  10523. $pfile .= '$diff=\''.$fmetric['diff'].'\';'."\n";
  10524. if ($fmetric['type'] == 'Type1') {
  10525. // Type 1
  10526. $pfile .= '$enc=\''.$fmetric['enc'].'\';'."\n";
  10527. $pfile .= '$file=\''.$fmetric['file'].'\';'."\n";
  10528. $pfile .= '$size1='.$fmetric['size1'].';'."\n";
  10529. $pfile .= '$size2='.$fmetric['size2'].';'."\n";
  10530. } else {
  10531. $pfile .= '$originalsize='.$fmetric['originalsize'].';'."\n";
  10532. if ($fmetric['type'] == 'cidfont0') {
  10533. // CID-0
  10534. switch ($fonttype) {
  10535. case 'CID0JP': {
  10536. $pfile .= '// Japanese'."\n";
  10537. $pfile .= '$enc=\'UniJIS-UTF16-H\';'."\n";
  10538. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'Japan1\',\'Supplement\'=>5);'."\n";
  10539. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_aj16.php\');'."\n";
  10540. break;
  10541. }
  10542. case 'CID0KR': {
  10543. $pfile .= '// Korean'."\n";
  10544. $pfile .= '$enc=\'UniKS-UTF16-H\';'."\n";
  10545. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'Korea1\',\'Supplement\'=>0);'."\n";
  10546. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_ak12.php\');'."\n";
  10547. break;
  10548. }
  10549. case 'CID0CS': {
  10550. $pfile .= '// Chinese Simplified'."\n";
  10551. $pfile .= '$enc=\'UniGB-UTF16-H\';'."\n";
  10552. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'GB1\',\'Supplement\'=>2);'."\n";
  10553. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_ag15.php\');'."\n";
  10554. break;
  10555. }
  10556. case 'CID0CT':
  10557. default: {
  10558. $pfile .= '// Chinese Traditional'."\n";
  10559. $pfile .= '$enc=\'UniCNS-UTF16-H\';'."\n";
  10560. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'CNS1\',\'Supplement\'=>0);'."\n";
  10561. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_aj16.php\');'."\n";
  10562. break;
  10563. }
  10564. }
  10565. } else {
  10566. // TrueType
  10567. $pfile .= '$enc=\''.$fmetric['enc'].'\';'."\n";
  10568. $pfile .= '$file=\''.$fmetric['file'].'\';'."\n";
  10569. $pfile .= '$ctg=\''.$fmetric['ctg'].'\';'."\n";
  10570. // create CIDToGIDMap
  10571. $cidtogidmap = str_pad('', 131072, "\x00"); // (256 * 256 * 2) = 131072
  10572. foreach ($ctg as $cid => $gid) {
  10573. $cidtogidmap = $this->updateCIDtoGIDmap($cidtogidmap, $cid, $ctg[$cid]);
  10574. }
  10575. // store compressed CIDToGIDMap
  10576. $fp = fopen($outpath.$fmetric['ctg'], 'wb');
  10577. fwrite($fp, gzcompress($cidtogidmap));
  10578. fclose($fp);
  10579. }
  10580. }
  10581. $pfile .= '$desc=array(';
  10582. $pfile .= '\'Flags\'=>'.$fmetric['Flags'].',';
  10583. $pfile .= '\'FontBBox\'=>\'['.$fmetric['bbox'].']\',';
  10584. $pfile .= '\'ItalicAngle\'=>'.$fmetric['italicAngle'].',';
  10585. $pfile .= '\'Ascent\'=>'.$fmetric['Ascent'].',';
  10586. $pfile .= '\'Descent\'=>'.$fmetric['Descent'].',';
  10587. $pfile .= '\'Leading\'=>'.$fmetric['Leading'].',';
  10588. $pfile .= '\'CapHeight\'=>'.$fmetric['CapHeight'].',';
  10589. $pfile .= '\'XHeight\'=>'.$fmetric['XHeight'].',';
  10590. $pfile .= '\'StemV\'=>'.$fmetric['StemV'].',';
  10591. $pfile .= '\'StemH\'=>'.$fmetric['StemH'].',';
  10592. $pfile .= '\'AvgWidth\'=>'.$fmetric['AvgWidth'].',';
  10593. $pfile .= '\'MaxWidth\'=>'.$fmetric['MaxWidth'].',';
  10594. $pfile .= '\'MissingWidth\'=>'.$fmetric['MissingWidth'].'';
  10595. $pfile .= ');'."\n";
  10596. $pfile .= '$cw=array('.substr($fmetric['cw'], 1).');'."\n";
  10597. $pfile .= '// --- EOF ---'."\n";
  10598. // store file
  10599. $fp = fopen($outpath.$font_name.'.php', 'w');
  10600. fwrite($fp, $pfile);
  10601. fclose($fp);
  10602. // return TCPDF font name
  10603. return $font_name;
  10604. }
  10605. /**
  10606. * Returns a subset of the TrueType font data without the unused glyphs.
  10607. * @param $font (string) TrueType font data.
  10608. * @param $subsetchars (array) Array of used characters (the glyphs to keep).
  10609. * @return (string) A subset of TrueType font data without the unused glyphs.
  10610. * @author Nicola Asuni
  10611. * @protected
  10612. * @since 5.2.000 (2010-06-02)
  10613. */
  10614. protected function _getTrueTypeFontSubset($font, $subsetchars) {
  10615. ksort($subsetchars);
  10616. $offset = 0; // offset position of the font data
  10617. if ($this->_getULONG($font, $offset) != 0x10000) {
  10618. // sfnt version must be 0x00010000 for TrueType version 1.0.
  10619. return $font;
  10620. }
  10621. $offset += 4;
  10622. // get number of tables
  10623. $numTables = $this->_getUSHORT($font, $offset);
  10624. $offset += 2;
  10625. // skip searchRange, entrySelector and rangeShift
  10626. $offset += 6;
  10627. // tables array
  10628. $table = array();
  10629. // for each table
  10630. for ($i = 0; $i < $numTables; ++$i) {
  10631. // get table info
  10632. $tag = substr($font, $offset, 4);
  10633. $offset += 4;
  10634. $table[$tag] = array();
  10635. $table[$tag]['checkSum'] = $this->_getULONG($font, $offset);
  10636. $offset += 4;
  10637. $table[$tag]['offset'] = $this->_getULONG($font, $offset);
  10638. $offset += 4;
  10639. $table[$tag]['length'] = $this->_getULONG($font, $offset);
  10640. $offset += 4;
  10641. }
  10642. // check magicNumber
  10643. $offset = $table['head']['offset'] + 12;
  10644. if ($this->_getULONG($font, $offset) != 0x5F0F3CF5) {
  10645. // magicNumber must be 0x5F0F3CF5
  10646. return $font;
  10647. }
  10648. $offset += 4;
  10649. // get offset mode (indexToLocFormat : 0 = short, 1 = long)
  10650. $offset = $table['head']['offset'] + 50;
  10651. $short_offset = ($this->_getSHORT($font, $offset) == 0);
  10652. $offset += 2;
  10653. // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
  10654. $indexToLoc = array();
  10655. $offset = $table['loca']['offset'];
  10656. if ($short_offset) {
  10657. // short version
  10658. $tot_num_glyphs = ($table['loca']['length'] / 2); // numGlyphs + 1
  10659. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10660. $indexToLoc[$i] = $this->_getUSHORT($font, $offset) * 2;
  10661. $offset += 2;
  10662. }
  10663. } else {
  10664. // long version
  10665. $tot_num_glyphs = ($table['loca']['length'] / 4); // numGlyphs + 1
  10666. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10667. $indexToLoc[$i] = $this->_getULONG($font, $offset);
  10668. $offset += 4;
  10669. }
  10670. }
  10671. // get glyphs indexes of chars from cmap table
  10672. $subsetglyphs = array(); // glyph IDs on key
  10673. $subsetglyphs[0] = true; // character codes that do not correspond to any glyph in the font should be mapped to glyph index 0
  10674. $offset = $table['cmap']['offset'] + 2;
  10675. $numEncodingTables = $this->_getUSHORT($font, $offset);
  10676. $offset += 2;
  10677. $encodingTables = array();
  10678. for ($i = 0; $i < $numEncodingTables; ++$i) {
  10679. $encodingTables[$i]['platformID'] = $this->_getUSHORT($font, $offset);
  10680. $offset += 2;
  10681. $encodingTables[$i]['encodingID'] = $this->_getUSHORT($font, $offset);
  10682. $offset += 2;
  10683. $encodingTables[$i]['offset'] = $this->_getULONG($font, $offset);
  10684. $offset += 4;
  10685. }
  10686. foreach ($encodingTables as $enctable) {
  10687. // get all platforms and encodings
  10688. $offset = $table['cmap']['offset'] + $enctable['offset'];
  10689. $format = $this->_getUSHORT($font, $offset);
  10690. $offset += 2;
  10691. switch ($format) {
  10692. case 0: { // Format 0: Byte encoding table
  10693. $offset += 4; // skip length and version/language
  10694. for ($c = 0; $c < 256; ++$c) {
  10695. if (isset($subsetchars[$c])) {
  10696. $g = $this->_getBYTE($font, $offset);
  10697. $subsetglyphs[$g] = true;
  10698. }
  10699. ++$offset;
  10700. }
  10701. break;
  10702. }
  10703. case 2: { // Format 2: High-byte mapping through table
  10704. $offset += 4; // skip length and version/language
  10705. $numSubHeaders = 0;
  10706. for ($i = 0; $i < 256; ++$i) {
  10707. // Array that maps high bytes to subHeaders: value is subHeader index * 8.
  10708. $subHeaderKeys[$i] = ($this->_getUSHORT($font, $offset) / 8);
  10709. $offset += 2;
  10710. if ($numSubHeaders < $subHeaderKeys[$i]) {
  10711. $numSubHeaders = $subHeaderKeys[$i];
  10712. }
  10713. }
  10714. // the number of subHeaders is equal to the max of subHeaderKeys + 1
  10715. ++$numSubHeaders;
  10716. // read subHeader structures
  10717. $subHeaders = array();
  10718. $numGlyphIndexArray = 0;
  10719. for ($k = 0; $k < $numSubHeaders; ++$k) {
  10720. $subHeaders[$k]['firstCode'] = $this->_getUSHORT($font, $offset);
  10721. $offset += 2;
  10722. $subHeaders[$k]['entryCount'] = $this->_getUSHORT($font, $offset);
  10723. $offset += 2;
  10724. $subHeaders[$k]['idDelta'] = $this->_getUSHORT($font, $offset);
  10725. $offset += 2;
  10726. $subHeaders[$k]['idRangeOffset'] = $this->_getUSHORT($font, $offset);
  10727. $offset += 2;
  10728. $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
  10729. $subHeaders[$k]['idRangeOffset'] /= 2;
  10730. $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
  10731. }
  10732. for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
  10733. $glyphIndexArray[$k] = $this->_getUSHORT($font, $offset);
  10734. $offset += 2;
  10735. }
  10736. for ($i = 0; $i < 256; ++$i) {
  10737. $k = $subHeaderKeys[$i];
  10738. if ($k == 0) {
  10739. // one byte code
  10740. $c = $i;
  10741. if (isset($subsetchars[$c])) {
  10742. $g = $glyphIndexArray[0];
  10743. $subsetglyphs[$g] = true;
  10744. }
  10745. } else {
  10746. // two bytes code
  10747. $start_byte = $subHeaders[$k]['firstCode'];
  10748. $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
  10749. for ($j = $start_byte; $j < $end_byte; ++$j) {
  10750. // combine high and low bytes
  10751. $c = (($i << 8) + $j);
  10752. if (isset($subsetchars[$c])) {
  10753. $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
  10754. $g = ($glyphIndexArray[$idRangeOffset] + $idDelta[$k]) % 65536;
  10755. if ($g < 0) {
  10756. $g = 0;
  10757. }
  10758. $subsetglyphs[$g] = true;
  10759. }
  10760. }
  10761. }
  10762. }
  10763. break;
  10764. }
  10765. case 4: { // Format 4: Segment mapping to delta values
  10766. $length = $this->_getUSHORT($font, $offset);
  10767. $offset += 2;
  10768. $offset += 2; // skip version/language
  10769. $segCount = ($this->_getUSHORT($font, $offset) / 2);
  10770. $offset += 2;
  10771. $offset += 6; // skip searchRange, entrySelector, rangeShift
  10772. $endCount = array(); // array of end character codes for each segment
  10773. for ($k = 0; $k < $segCount; ++$k) {
  10774. $endCount[$k] = $this->_getUSHORT($font, $offset);
  10775. $offset += 2;
  10776. }
  10777. $offset += 2; // skip reservedPad
  10778. $startCount = array(); // array of start character codes for each segment
  10779. for ($k = 0; $k < $segCount; ++$k) {
  10780. $startCount[$k] = $this->_getUSHORT($font, $offset);
  10781. $offset += 2;
  10782. }
  10783. $idDelta = array(); // delta for all character codes in segment
  10784. for ($k = 0; $k < $segCount; ++$k) {
  10785. $idDelta[$k] = $this->_getUSHORT($font, $offset);
  10786. $offset += 2;
  10787. }
  10788. $idRangeOffset = array(); // Offsets into glyphIdArray or 0
  10789. for ($k = 0; $k < $segCount; ++$k) {
  10790. $idRangeOffset[$k] = $this->_getUSHORT($font, $offset);
  10791. $offset += 2;
  10792. }
  10793. $gidlen = ($length / 2) - 8 - (4 * $segCount);
  10794. $glyphIdArray = array(); // glyph index array
  10795. for ($k = 0; $k < $gidlen; ++$k) {
  10796. $glyphIdArray[$k] = $this->_getUSHORT($font, $offset);
  10797. $offset += 2;
  10798. }
  10799. for ($k = 0; $k < $segCount; ++$k) {
  10800. for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
  10801. if (isset($subsetchars[$c])) {
  10802. if ($idRangeOffset[$k] == 0) {
  10803. $g = ($idDelta[$k] + $c) % 65536;
  10804. } else {
  10805. $gid = (($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
  10806. $g = ($glyphIdArray[$gid] + $idDelta[$k]) % 65536;
  10807. }
  10808. if ($g < 0) {
  10809. $g = 0;
  10810. }
  10811. $subsetglyphs[$g] = true;
  10812. }
  10813. }
  10814. }
  10815. break;
  10816. }
  10817. case 6: { // Format 6: Trimmed table mapping
  10818. $offset += 4; // skip length and version/language
  10819. $firstCode = $this->_getUSHORT($font, $offset);
  10820. $offset += 2;
  10821. $entryCount = $this->_getUSHORT($font, $offset);
  10822. $offset += 2;
  10823. for ($k = 0; $k < $entryCount; ++$k) {
  10824. $c = ($k + $firstCode);
  10825. if (isset($subsetchars[$c])) {
  10826. $g = $this->_getUSHORT($font, $offset);
  10827. $subsetglyphs[$g] = true;
  10828. }
  10829. $offset += 2;
  10830. }
  10831. break;
  10832. }
  10833. case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
  10834. $offset += 10; // skip reserved, length and version/language
  10835. for ($k = 0; $k < 8192; ++$k) {
  10836. $is32[$k] = $this->_getBYTE($font, $offset);
  10837. ++$offset;
  10838. }
  10839. $nGroups = $this->_getULONG($font, $offset);
  10840. $offset += 4;
  10841. for ($i = 0; $i < $nGroups; ++$i) {
  10842. $startCharCode = $this->_getULONG($font, $offset);
  10843. $offset += 4;
  10844. $endCharCode = $this->_getULONG($font, $offset);
  10845. $offset += 4;
  10846. $startGlyphID = $this->_getULONG($font, $offset);
  10847. $offset += 4;
  10848. for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
  10849. $is32idx = floor($c / 8);
  10850. if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
  10851. $c = $k;
  10852. } else {
  10853. // 32 bit format
  10854. // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
  10855. //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
  10856. //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
  10857. $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
  10858. }
  10859. if (isset($subsetchars[$c])) {
  10860. $subsetglyphs[$startGlyphID] = true;
  10861. }
  10862. ++$startGlyphID;
  10863. }
  10864. }
  10865. break;
  10866. }
  10867. case 10: { // Format 10: Trimmed array
  10868. $offset += 10; // skip reserved, length and version/language
  10869. $startCharCode = $this->_getULONG($font, $offset);
  10870. $offset += 4;
  10871. $numChars = $this->_getULONG($font, $offset);
  10872. $offset += 4;
  10873. for ($k = 0; $k < $numChars; ++$k) {
  10874. $c = ($k + $startCharCode);
  10875. if (isset($subsetchars[$c])) {
  10876. $g = $this->_getUSHORT($font, $offset);
  10877. $subsetglyphs[$g] = true;
  10878. }
  10879. $offset += 2;
  10880. }
  10881. break;
  10882. }
  10883. case 12: { // Format 12: Segmented coverage
  10884. $offset += 10; // skip length and version/language
  10885. $nGroups = $this->_getULONG($font, $offset);
  10886. $offset += 4;
  10887. for ($k = 0; $k < $nGroups; ++$k) {
  10888. $startCharCode = $this->_getULONG($font, $offset);
  10889. $offset += 4;
  10890. $endCharCode = $this->_getULONG($font, $offset);
  10891. $offset += 4;
  10892. $startGlyphCode = $this->_getULONG($font, $offset);
  10893. $offset += 4;
  10894. for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
  10895. if (isset($subsetchars[$c])) {
  10896. $subsetglyphs[$startGlyphCode] = true;
  10897. }
  10898. ++$startGlyphCode;
  10899. }
  10900. }
  10901. break;
  10902. }
  10903. case 13: { // Format 13: Many-to-one range mappings
  10904. // to be implemented ...
  10905. break;
  10906. }
  10907. case 14: { // Format 14: Unicode Variation Sequences
  10908. // to be implemented ...
  10909. break;
  10910. }
  10911. }
  10912. }
  10913. // include all parts of composite glyphs
  10914. $new_sga = $subsetglyphs;
  10915. while (!empty($new_sga)) {
  10916. $sga = $new_sga;
  10917. $new_sga = array();
  10918. foreach ($sga as $key => $val) {
  10919. if (isset($indexToLoc[$key])) {
  10920. $offset = ($table['glyf']['offset'] + $indexToLoc[$key]);
  10921. $numberOfContours = $this->_getSHORT($font, $offset);
  10922. $offset += 2;
  10923. if ($numberOfContours < 0) { // composite glyph
  10924. $offset += 8; // skip xMin, yMin, xMax, yMax
  10925. do {
  10926. $flags = $this->_getUSHORT($font, $offset);
  10927. $offset += 2;
  10928. $glyphIndex = $this->_getUSHORT($font, $offset);
  10929. $offset += 2;
  10930. if (!isset($subsetglyphs[$glyphIndex])) {
  10931. // add missing glyphs
  10932. $new_sga[$glyphIndex] = true;
  10933. }
  10934. // skip some bytes by case
  10935. if ($flags & 1) {
  10936. $offset += 4;
  10937. } else {
  10938. $offset += 2;
  10939. }
  10940. if ($flags & 8) {
  10941. $offset += 2;
  10942. } elseif ($flags & 64) {
  10943. $offset += 4;
  10944. } elseif ($flags & 128) {
  10945. $offset += 8;
  10946. }
  10947. } while ($flags & 32);
  10948. }
  10949. }
  10950. }
  10951. $subsetglyphs += $new_sga;
  10952. }
  10953. // sort glyphs by key (and remove duplicates)
  10954. ksort($subsetglyphs);
  10955. // build new glyf and loca tables
  10956. $glyf = '';
  10957. $loca = '';
  10958. $offset = 0;
  10959. $glyf_offset = $table['glyf']['offset'];
  10960. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  10961. if (isset($subsetglyphs[$i])) {
  10962. $length = ($indexToLoc[($i + 1)] - $indexToLoc[$i]);
  10963. $glyf .= substr($font, ($glyf_offset + $indexToLoc[$i]), $length);
  10964. } else {
  10965. $length = 0;
  10966. }
  10967. if ($short_offset) {
  10968. $loca .= pack('n', ($offset / 2));
  10969. } else {
  10970. $loca .= pack('N', $offset);
  10971. }
  10972. $offset += $length;
  10973. }
  10974. // array of table names to preserve (loca and glyf tables will be added later)
  10975. // the cmap table is not needed and shall not be present, since the mapping from character codes to glyph descriptions is provided separately
  10976. $table_names = array ('head', 'hhea', 'hmtx', 'maxp', 'cvt ', 'fpgm', 'prep'); // minimum required table names
  10977. // get the tables to preserve
  10978. $offset = 12;
  10979. foreach ($table as $tag => $val) {
  10980. if (in_array($tag, $table_names)) {
  10981. $table[$tag]['data'] = substr($font, $table[$tag]['offset'], $table[$tag]['length']);
  10982. if ($tag == 'head') {
  10983. // set the checkSumAdjustment to 0
  10984. $table[$tag]['data'] = substr($table[$tag]['data'], 0, 8)."\x0\x0\x0\x0".substr($table[$tag]['data'], 12);
  10985. }
  10986. $pad = 4 - ($table[$tag]['length'] % 4);
  10987. if ($pad != 4) {
  10988. // the length of a table must be a multiple of four bytes
  10989. $table[$tag]['length'] += $pad;
  10990. $table[$tag]['data'] .= str_repeat("\x0", $pad);
  10991. }
  10992. $table[$tag]['offset'] = $offset;
  10993. $offset += $table[$tag]['length'];
  10994. // check sum is not changed (so keep the following line commented)
  10995. //$table[$tag]['checkSum'] = $this->_getTTFtableChecksum($table[$tag]['data'], $table[$tag]['length']);
  10996. } else {
  10997. unset($table[$tag]);
  10998. }
  10999. }
  11000. // add loca
  11001. $table['loca']['data'] = $loca;
  11002. $table['loca']['length'] = strlen($loca);
  11003. $pad = 4 - ($table['loca']['length'] % 4);
  11004. if ($pad != 4) {
  11005. // the length of a table must be a multiple of four bytes
  11006. $table['loca']['length'] += $pad;
  11007. $table['loca']['data'] .= str_repeat("\x0", $pad);
  11008. }
  11009. $table['loca']['offset'] = $offset;
  11010. $table['loca']['checkSum'] = $this->_getTTFtableChecksum($table['loca']['data'], $table['loca']['length']);
  11011. $offset += $table['loca']['length'];
  11012. // add glyf
  11013. $table['glyf']['data'] = $glyf;
  11014. $table['glyf']['length'] = strlen($glyf);
  11015. $pad = 4 - ($table['glyf']['length'] % 4);
  11016. if ($pad != 4) {
  11017. // the length of a table must be a multiple of four bytes
  11018. $table['glyf']['length'] += $pad;
  11019. $table['glyf']['data'] .= str_repeat("\x0", $pad);
  11020. }
  11021. $table['glyf']['offset'] = $offset;
  11022. $table['glyf']['checkSum'] = $this->_getTTFtableChecksum($table['glyf']['data'], $table['glyf']['length']);
  11023. // rebuild font
  11024. $font = '';
  11025. $font .= pack('N', 0x10000); // sfnt version
  11026. $numTables = count($table);
  11027. $font .= pack('n', $numTables); // numTables
  11028. $entrySelector = floor(log($numTables, 2));
  11029. $searchRange = pow(2, $entrySelector) * 16;
  11030. $rangeShift = ($numTables * 16) - $searchRange;
  11031. $font .= pack('n', $searchRange); // searchRange
  11032. $font .= pack('n', $entrySelector); // entrySelector
  11033. $font .= pack('n', $rangeShift); // rangeShift
  11034. $offset = ($numTables * 16);
  11035. foreach ($table as $tag => $data) {
  11036. $font .= $tag; // tag
  11037. $font .= pack('N', $data['checkSum']); // checkSum
  11038. $font .= pack('N', ($data['offset'] + $offset)); // offset
  11039. $font .= pack('N', $data['length']); // length
  11040. }
  11041. foreach ($table as $data) {
  11042. $font .= $data['data'];
  11043. }
  11044. // set checkSumAdjustment on head table
  11045. $checkSumAdjustment = 0xB1B0AFBA - $this->_getTTFtableChecksum($font, strlen($font));
  11046. $font = substr($font, 0, $table['head']['offset'] + 8).pack('N', $checkSumAdjustment).substr($font, $table['head']['offset'] + 12);
  11047. return $font;
  11048. }
  11049. /**
  11050. * Returs the checksum of a TTF table.
  11051. * @param $table (string) table to check
  11052. * @param $length (int) length of table in bytes
  11053. * @return int checksum
  11054. * @author Nicola Asuni
  11055. * @protected
  11056. * @since 5.2.000 (2010-06-02)
  11057. */
  11058. protected function _getTTFtableChecksum($table, $length) {
  11059. $sum = 0;
  11060. $tlen = ($length / 4);
  11061. $offset = 0;
  11062. for ($i = 0; $i < $tlen; ++$i) {
  11063. $v = unpack('Ni', substr($table, $offset, 4));
  11064. $sum += $v['i'];
  11065. $offset += 4;
  11066. }
  11067. $sum = unpack('Ni', pack('N', $sum));
  11068. return $sum['i'];
  11069. }
  11070. /**
  11071. * Outputs font widths
  11072. * @param $font (array) font data
  11073. * @param $cidoffset (int) offset for CID values
  11074. * @return PDF command string for font widths
  11075. * @author Nicola Asuni
  11076. * @protected
  11077. * @since 4.4.000 (2008-12-07)
  11078. */
  11079. protected function _putfontwidths($font, $cidoffset=0) {
  11080. ksort($font['cw']);
  11081. $rangeid = 0;
  11082. $range = array();
  11083. $prevcid = -2;
  11084. $prevwidth = -1;
  11085. $interval = false;
  11086. // for each character
  11087. foreach ($font['cw'] as $cid => $width) {
  11088. $cid -= $cidoffset;
  11089. if ($font['subset'] AND ($cid > 255) AND (!isset($font['subsetchars'][$cid]))) {
  11090. // ignore the unused characters (font subsetting)
  11091. continue;
  11092. }
  11093. if ($width != $font['dw']) {
  11094. if ($cid == ($prevcid + 1)) {
  11095. // consecutive CID
  11096. if ($width == $prevwidth) {
  11097. if ($width == $range[$rangeid][0]) {
  11098. $range[$rangeid][] = $width;
  11099. } else {
  11100. array_pop($range[$rangeid]);
  11101. // new range
  11102. $rangeid = $prevcid;
  11103. $range[$rangeid] = array();
  11104. $range[$rangeid][] = $prevwidth;
  11105. $range[$rangeid][] = $width;
  11106. }
  11107. $interval = true;
  11108. $range[$rangeid]['interval'] = true;
  11109. } else {
  11110. if ($interval) {
  11111. // new range
  11112. $rangeid = $cid;
  11113. $range[$rangeid] = array();
  11114. $range[$rangeid][] = $width;
  11115. } else {
  11116. $range[$rangeid][] = $width;
  11117. }
  11118. $interval = false;
  11119. }
  11120. } else {
  11121. // new range
  11122. $rangeid = $cid;
  11123. $range[$rangeid] = array();
  11124. $range[$rangeid][] = $width;
  11125. $interval = false;
  11126. }
  11127. $prevcid = $cid;
  11128. $prevwidth = $width;
  11129. }
  11130. }
  11131. // optimize ranges
  11132. $prevk = -1;
  11133. $nextk = -1;
  11134. $prevint = false;
  11135. foreach ($range as $k => $ws) {
  11136. $cws = count($ws);
  11137. if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
  11138. if (isset($range[$k]['interval'])) {
  11139. unset($range[$k]['interval']);
  11140. }
  11141. $range[$prevk] = array_merge($range[$prevk], $range[$k]);
  11142. unset($range[$k]);
  11143. } else {
  11144. $prevk = $k;
  11145. }
  11146. $nextk = $k + $cws;
  11147. if (isset($ws['interval'])) {
  11148. if ($cws > 3) {
  11149. $prevint = true;
  11150. } else {
  11151. $prevint = false;
  11152. }
  11153. unset($range[$k]['interval']);
  11154. --$nextk;
  11155. } else {
  11156. $prevint = false;
  11157. }
  11158. }
  11159. // output data
  11160. $w = '';
  11161. foreach ($range as $k => $ws) {
  11162. if (count(array_count_values($ws)) == 1) {
  11163. // interval mode is more compact
  11164. $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
  11165. } else {
  11166. // range mode
  11167. $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
  11168. }
  11169. }
  11170. return '/W ['.$w.' ]';
  11171. }
  11172. /**
  11173. * Output fonts.
  11174. * @author Nicola Asuni
  11175. * @protected
  11176. */
  11177. protected function _putfonts() {
  11178. $nf = $this->n;
  11179. foreach ($this->diffs as $diff) {
  11180. //Encodings
  11181. $this->_newobj();
  11182. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  11183. }
  11184. $mqr = $this->get_mqr();
  11185. $this->set_mqr(false);
  11186. foreach ($this->FontFiles as $file => $info) {
  11187. // search and get font file to embedd
  11188. $fontdir = $info['fontdir'];
  11189. $file = strtolower($file);
  11190. $fontfile = '';
  11191. // search files on various directories
  11192. if (($fontdir !== false) AND file_exists($fontdir.$file)) {
  11193. $fontfile = $fontdir.$file;
  11194. } elseif (file_exists($this->_getfontpath().$file)) {
  11195. $fontfile = $this->_getfontpath().$file;
  11196. } elseif (file_exists($file)) {
  11197. $fontfile = $file;
  11198. }
  11199. if (!$this->empty_string($fontfile)) {
  11200. $font = file_get_contents($fontfile);
  11201. $compressed = (substr($file, -2) == '.z');
  11202. if ((!$compressed) AND (isset($info['length2']))) {
  11203. $header = (ord($font{0}) == 128);
  11204. if ($header) {
  11205. // strip first binary header
  11206. $font = substr($font, 6);
  11207. }
  11208. if ($header AND (ord($font[$info['length1']]) == 128)) {
  11209. // strip second binary header
  11210. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  11211. }
  11212. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  11213. if ($compressed) {
  11214. // uncompress font
  11215. $font = gzuncompress($font);
  11216. }
  11217. // merge subset characters
  11218. $subsetchars = array(); // used chars
  11219. foreach ($info['fontkeys'] as $fontkey) {
  11220. $fontinfo = $this->getFontBuffer($fontkey);
  11221. $subsetchars += $fontinfo['subsetchars'];
  11222. }
  11223. // rebuild a font subset
  11224. $font = $this->_getTrueTypeFontSubset($font, $subsetchars);
  11225. // calculate new font length
  11226. $info['length1'] = strlen($font);
  11227. if ($compressed) {
  11228. // recompress font
  11229. $font = gzcompress($font);
  11230. }
  11231. }
  11232. $this->_newobj();
  11233. $this->FontFiles[$file]['n'] = $this->n;
  11234. $stream = $this->_getrawstream($font);
  11235. $out = '<< /Length '.strlen($stream);
  11236. if ($compressed) {
  11237. $out .= ' /Filter /FlateDecode';
  11238. }
  11239. $out .= ' /Length1 '.$info['length1'];
  11240. if (isset($info['length2'])) {
  11241. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  11242. }
  11243. $out .= ' >>';
  11244. $out .= ' stream'."\n".$stream."\n".'endstream';
  11245. $out .= "\n".'endobj';
  11246. $this->_out($out);
  11247. }
  11248. }
  11249. $this->set_mqr($mqr);
  11250. foreach ($this->fontkeys as $k) {
  11251. //Font objects
  11252. $font = $this->getFontBuffer($k);
  11253. $type = $font['type'];
  11254. $name = $font['name'];
  11255. if ($type == 'core') {
  11256. // standard core font
  11257. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  11258. $out .= '<</Type /Font';
  11259. $out .= ' /Subtype /Type1';
  11260. $out .= ' /BaseFont /'.$name;
  11261. $out .= ' /Name /F'.$font['i'];
  11262. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  11263. $out .= ' /Encoding /WinAnsiEncoding';
  11264. }
  11265. if ($k == 'helvetica') {
  11266. // add default font for annotations
  11267. $this->annotation_fonts[$k] = $font['i'];
  11268. }
  11269. $out .= ' >>';
  11270. $out .= "\n".'endobj';
  11271. $this->_out($out);
  11272. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  11273. // additional Type1 or TrueType font
  11274. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  11275. $out .= '<</Type /Font';
  11276. $out .= ' /Subtype /'.$type;
  11277. $out .= ' /BaseFont /'.$name;
  11278. $out .= ' /Name /F'.$font['i'];
  11279. $out .= ' /FirstChar 32 /LastChar 255';
  11280. $out .= ' /Widths '.($this->n + 1).' 0 R';
  11281. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  11282. if ($font['enc']) {
  11283. if (isset($font['diff'])) {
  11284. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  11285. } else {
  11286. $out .= ' /Encoding /WinAnsiEncoding';
  11287. }
  11288. }
  11289. $out .= ' >>';
  11290. $out .= "\n".'endobj';
  11291. $this->_out($out);
  11292. // Widths
  11293. $this->_newobj();
  11294. $s = '[';
  11295. for ($i = 32; $i < 256; ++$i) {
  11296. $s .= $font['cw'][$i].' ';
  11297. }
  11298. $s .= ']';
  11299. $s .= "\n".'endobj';
  11300. $this->_out($s);
  11301. //Descriptor
  11302. $this->_newobj();
  11303. $s = '<</Type /FontDescriptor /FontName /'.$name;
  11304. foreach ($font['desc'] as $fdk => $fdv) {
  11305. if (is_float($fdv)) {
  11306. $fdv = sprintf('%F', $fdv);
  11307. }
  11308. $s .= ' /'.$fdk.' '.$fdv.'';
  11309. }
  11310. if (!$this->empty_string($font['file'])) {
  11311. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  11312. }
  11313. $s .= '>>';
  11314. $s .= "\n".'endobj';
  11315. $this->_out($s);
  11316. } else {
  11317. // additional types
  11318. $mtd = '_put'.strtolower($type);
  11319. if (!method_exists($this, $mtd)) {
  11320. $this->Error('Unsupported font type: '.$type);
  11321. }
  11322. $this->$mtd($font);
  11323. }
  11324. }
  11325. }
  11326. /**
  11327. * Adds unicode fonts.<br>
  11328. * Based on PDF Reference 1.3 (section 5)
  11329. * @param $font (array) font data
  11330. * @protected
  11331. * @author Nicola Asuni
  11332. * @since 1.52.0.TC005 (2005-01-05)
  11333. */
  11334. protected function _puttruetypeunicode($font) {
  11335. $fontname = '';
  11336. if ($font['subset']) {
  11337. // change name for font subsetting
  11338. $subtag = sprintf('%06u', $font['i']);
  11339. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  11340. $fontname .= $subtag.'+';
  11341. }
  11342. $fontname .= $font['name'];
  11343. // Type0 Font
  11344. // A composite font composed of other fonts, organized hierarchically
  11345. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  11346. $out .= '<< /Type /Font';
  11347. $out .= ' /Subtype /Type0';
  11348. $out .= ' /BaseFont /'.$fontname;
  11349. $out .= ' /Name /F'.$font['i'];
  11350. $out .= ' /Encoding /'.$font['enc'];
  11351. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  11352. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  11353. $out .= ' >>';
  11354. $out .= "\n".'endobj';
  11355. $this->_out($out);
  11356. // ToUnicode map for Identity-H
  11357. $stream = "/CIDInit /ProcSet findresource begin\n";
  11358. $stream .= "12 dict begin\n";
  11359. $stream .= "begincmap\n";
  11360. $stream .= "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n";
  11361. $stream .= "/CMapName /Adobe-Identity-UCS def\n";
  11362. $stream .= "/CMapType 2 def\n";
  11363. $stream .= "/WMode 0 def\n";
  11364. $stream .= "1 begincodespacerange\n";
  11365. $stream .= "<0000> <FFFF>\n";
  11366. $stream .= "endcodespacerange\n";
  11367. $stream .= "100 beginbfrange\n";
  11368. $stream .= "<0000> <00ff> <0000>\n";
  11369. $stream .= "<0100> <01ff> <0100>\n";
  11370. $stream .= "<0200> <02ff> <0200>\n";
  11371. $stream .= "<0300> <03ff> <0300>\n";
  11372. $stream .= "<0400> <04ff> <0400>\n";
  11373. $stream .= "<0500> <05ff> <0500>\n";
  11374. $stream .= "<0600> <06ff> <0600>\n";
  11375. $stream .= "<0700> <07ff> <0700>\n";
  11376. $stream .= "<0800> <08ff> <0800>\n";
  11377. $stream .= "<0900> <09ff> <0900>\n";
  11378. $stream .= "<0a00> <0aff> <0a00>\n";
  11379. $stream .= "<0b00> <0bff> <0b00>\n";
  11380. $stream .= "<0c00> <0cff> <0c00>\n";
  11381. $stream .= "<0d00> <0dff> <0d00>\n";
  11382. $stream .= "<0e00> <0eff> <0e00>\n";
  11383. $stream .= "<0f00> <0fff> <0f00>\n";
  11384. $stream .= "<1000> <10ff> <1000>\n";
  11385. $stream .= "<1100> <11ff> <1100>\n";
  11386. $stream .= "<1200> <12ff> <1200>\n";
  11387. $stream .= "<1300> <13ff> <1300>\n";
  11388. $stream .= "<1400> <14ff> <1400>\n";
  11389. $stream .= "<1500> <15ff> <1500>\n";
  11390. $stream .= "<1600> <16ff> <1600>\n";
  11391. $stream .= "<1700> <17ff> <1700>\n";
  11392. $stream .= "<1800> <18ff> <1800>\n";
  11393. $stream .= "<1900> <19ff> <1900>\n";
  11394. $stream .= "<1a00> <1aff> <1a00>\n";
  11395. $stream .= "<1b00> <1bff> <1b00>\n";
  11396. $stream .= "<1c00> <1cff> <1c00>\n";
  11397. $stream .= "<1d00> <1dff> <1d00>\n";
  11398. $stream .= "<1e00> <1eff> <1e00>\n";
  11399. $stream .= "<1f00> <1fff> <1f00>\n";
  11400. $stream .= "<2000> <20ff> <2000>\n";
  11401. $stream .= "<2100> <21ff> <2100>\n";
  11402. $stream .= "<2200> <22ff> <2200>\n";
  11403. $stream .= "<2300> <23ff> <2300>\n";
  11404. $stream .= "<2400> <24ff> <2400>\n";
  11405. $stream .= "<2500> <25ff> <2500>\n";
  11406. $stream .= "<2600> <26ff> <2600>\n";
  11407. $stream .= "<2700> <27ff> <2700>\n";
  11408. $stream .= "<2800> <28ff> <2800>\n";
  11409. $stream .= "<2900> <29ff> <2900>\n";
  11410. $stream .= "<2a00> <2aff> <2a00>\n";
  11411. $stream .= "<2b00> <2bff> <2b00>\n";
  11412. $stream .= "<2c00> <2cff> <2c00>\n";
  11413. $stream .= "<2d00> <2dff> <2d00>\n";
  11414. $stream .= "<2e00> <2eff> <2e00>\n";
  11415. $stream .= "<2f00> <2fff> <2f00>\n";
  11416. $stream .= "<3000> <30ff> <3000>\n";
  11417. $stream .= "<3100> <31ff> <3100>\n";
  11418. $stream .= "<3200> <32ff> <3200>\n";
  11419. $stream .= "<3300> <33ff> <3300>\n";
  11420. $stream .= "<3400> <34ff> <3400>\n";
  11421. $stream .= "<3500> <35ff> <3500>\n";
  11422. $stream .= "<3600> <36ff> <3600>\n";
  11423. $stream .= "<3700> <37ff> <3700>\n";
  11424. $stream .= "<3800> <38ff> <3800>\n";
  11425. $stream .= "<3900> <39ff> <3900>\n";
  11426. $stream .= "<3a00> <3aff> <3a00>\n";
  11427. $stream .= "<3b00> <3bff> <3b00>\n";
  11428. $stream .= "<3c00> <3cff> <3c00>\n";
  11429. $stream .= "<3d00> <3dff> <3d00>\n";
  11430. $stream .= "<3e00> <3eff> <3e00>\n";
  11431. $stream .= "<3f00> <3fff> <3f00>\n";
  11432. $stream .= "<4000> <40ff> <4000>\n";
  11433. $stream .= "<4100> <41ff> <4100>\n";
  11434. $stream .= "<4200> <42ff> <4200>\n";
  11435. $stream .= "<4300> <43ff> <4300>\n";
  11436. $stream .= "<4400> <44ff> <4400>\n";
  11437. $stream .= "<4500> <45ff> <4500>\n";
  11438. $stream .= "<4600> <46ff> <4600>\n";
  11439. $stream .= "<4700> <47ff> <4700>\n";
  11440. $stream .= "<4800> <48ff> <4800>\n";
  11441. $stream .= "<4900> <49ff> <4900>\n";
  11442. $stream .= "<4a00> <4aff> <4a00>\n";
  11443. $stream .= "<4b00> <4bff> <4b00>\n";
  11444. $stream .= "<4c00> <4cff> <4c00>\n";
  11445. $stream .= "<4d00> <4dff> <4d00>\n";
  11446. $stream .= "<4e00> <4eff> <4e00>\n";
  11447. $stream .= "<4f00> <4fff> <4f00>\n";
  11448. $stream .= "<5000> <50ff> <5000>\n";
  11449. $stream .= "<5100> <51ff> <5100>\n";
  11450. $stream .= "<5200> <52ff> <5200>\n";
  11451. $stream .= "<5300> <53ff> <5300>\n";
  11452. $stream .= "<5400> <54ff> <5400>\n";
  11453. $stream .= "<5500> <55ff> <5500>\n";
  11454. $stream .= "<5600> <56ff> <5600>\n";
  11455. $stream .= "<5700> <57ff> <5700>\n";
  11456. $stream .= "<5800> <58ff> <5800>\n";
  11457. $stream .= "<5900> <59ff> <5900>\n";
  11458. $stream .= "<5a00> <5aff> <5a00>\n";
  11459. $stream .= "<5b00> <5bff> <5b00>\n";
  11460. $stream .= "<5c00> <5cff> <5c00>\n";
  11461. $stream .= "<5d00> <5dff> <5d00>\n";
  11462. $stream .= "<5e00> <5eff> <5e00>\n";
  11463. $stream .= "<5f00> <5fff> <5f00>\n";
  11464. $stream .= "<6000> <60ff> <6000>\n";
  11465. $stream .= "<6100> <61ff> <6100>\n";
  11466. $stream .= "<6200> <62ff> <6200>\n";
  11467. $stream .= "<6300> <63ff> <6300>\n";
  11468. $stream .= "endbfrange\n";
  11469. $stream .= "100 beginbfrange\n";
  11470. $stream .= "<6400> <64ff> <6400>\n";
  11471. $stream .= "<6500> <65ff> <6500>\n";
  11472. $stream .= "<6600> <66ff> <6600>\n";
  11473. $stream .= "<6700> <67ff> <6700>\n";
  11474. $stream .= "<6800> <68ff> <6800>\n";
  11475. $stream .= "<6900> <69ff> <6900>\n";
  11476. $stream .= "<6a00> <6aff> <6a00>\n";
  11477. $stream .= "<6b00> <6bff> <6b00>\n";
  11478. $stream .= "<6c00> <6cff> <6c00>\n";
  11479. $stream .= "<6d00> <6dff> <6d00>\n";
  11480. $stream .= "<6e00> <6eff> <6e00>\n";
  11481. $stream .= "<6f00> <6fff> <6f00>\n";
  11482. $stream .= "<7000> <70ff> <7000>\n";
  11483. $stream .= "<7100> <71ff> <7100>\n";
  11484. $stream .= "<7200> <72ff> <7200>\n";
  11485. $stream .= "<7300> <73ff> <7300>\n";
  11486. $stream .= "<7400> <74ff> <7400>\n";
  11487. $stream .= "<7500> <75ff> <7500>\n";
  11488. $stream .= "<7600> <76ff> <7600>\n";
  11489. $stream .= "<7700> <77ff> <7700>\n";
  11490. $stream .= "<7800> <78ff> <7800>\n";
  11491. $stream .= "<7900> <79ff> <7900>\n";
  11492. $stream .= "<7a00> <7aff> <7a00>\n";
  11493. $stream .= "<7b00> <7bff> <7b00>\n";
  11494. $stream .= "<7c00> <7cff> <7c00>\n";
  11495. $stream .= "<7d00> <7dff> <7d00>\n";
  11496. $stream .= "<7e00> <7eff> <7e00>\n";
  11497. $stream .= "<7f00> <7fff> <7f00>\n";
  11498. $stream .= "<8000> <80ff> <8000>\n";
  11499. $stream .= "<8100> <81ff> <8100>\n";
  11500. $stream .= "<8200> <82ff> <8200>\n";
  11501. $stream .= "<8300> <83ff> <8300>\n";
  11502. $stream .= "<8400> <84ff> <8400>\n";
  11503. $stream .= "<8500> <85ff> <8500>\n";
  11504. $stream .= "<8600> <86ff> <8600>\n";
  11505. $stream .= "<8700> <87ff> <8700>\n";
  11506. $stream .= "<8800> <88ff> <8800>\n";
  11507. $stream .= "<8900> <89ff> <8900>\n";
  11508. $stream .= "<8a00> <8aff> <8a00>\n";
  11509. $stream .= "<8b00> <8bff> <8b00>\n";
  11510. $stream .= "<8c00> <8cff> <8c00>\n";
  11511. $stream .= "<8d00> <8dff> <8d00>\n";
  11512. $stream .= "<8e00> <8eff> <8e00>\n";
  11513. $stream .= "<8f00> <8fff> <8f00>\n";
  11514. $stream .= "<9000> <90ff> <9000>\n";
  11515. $stream .= "<9100> <91ff> <9100>\n";
  11516. $stream .= "<9200> <92ff> <9200>\n";
  11517. $stream .= "<9300> <93ff> <9300>\n";
  11518. $stream .= "<9400> <94ff> <9400>\n";
  11519. $stream .= "<9500> <95ff> <9500>\n";
  11520. $stream .= "<9600> <96ff> <9600>\n";
  11521. $stream .= "<9700> <97ff> <9700>\n";
  11522. $stream .= "<9800> <98ff> <9800>\n";
  11523. $stream .= "<9900> <99ff> <9900>\n";
  11524. $stream .= "<9a00> <9aff> <9a00>\n";
  11525. $stream .= "<9b00> <9bff> <9b00>\n";
  11526. $stream .= "<9c00> <9cff> <9c00>\n";
  11527. $stream .= "<9d00> <9dff> <9d00>\n";
  11528. $stream .= "<9e00> <9eff> <9e00>\n";
  11529. $stream .= "<9f00> <9fff> <9f00>\n";
  11530. $stream .= "<a000> <a0ff> <a000>\n";
  11531. $stream .= "<a100> <a1ff> <a100>\n";
  11532. $stream .= "<a200> <a2ff> <a200>\n";
  11533. $stream .= "<a300> <a3ff> <a300>\n";
  11534. $stream .= "<a400> <a4ff> <a400>\n";
  11535. $stream .= "<a500> <a5ff> <a500>\n";
  11536. $stream .= "<a600> <a6ff> <a600>\n";
  11537. $stream .= "<a700> <a7ff> <a700>\n";
  11538. $stream .= "<a800> <a8ff> <a800>\n";
  11539. $stream .= "<a900> <a9ff> <a900>\n";
  11540. $stream .= "<aa00> <aaff> <aa00>\n";
  11541. $stream .= "<ab00> <abff> <ab00>\n";
  11542. $stream .= "<ac00> <acff> <ac00>\n";
  11543. $stream .= "<ad00> <adff> <ad00>\n";
  11544. $stream .= "<ae00> <aeff> <ae00>\n";
  11545. $stream .= "<af00> <afff> <af00>\n";
  11546. $stream .= "<b000> <b0ff> <b000>\n";
  11547. $stream .= "<b100> <b1ff> <b100>\n";
  11548. $stream .= "<b200> <b2ff> <b200>\n";
  11549. $stream .= "<b300> <b3ff> <b300>\n";
  11550. $stream .= "<b400> <b4ff> <b400>\n";
  11551. $stream .= "<b500> <b5ff> <b500>\n";
  11552. $stream .= "<b600> <b6ff> <b600>\n";
  11553. $stream .= "<b700> <b7ff> <b700>\n";
  11554. $stream .= "<b800> <b8ff> <b800>\n";
  11555. $stream .= "<b900> <b9ff> <b900>\n";
  11556. $stream .= "<ba00> <baff> <ba00>\n";
  11557. $stream .= "<bb00> <bbff> <bb00>\n";
  11558. $stream .= "<bc00> <bcff> <bc00>\n";
  11559. $stream .= "<bd00> <bdff> <bd00>\n";
  11560. $stream .= "<be00> <beff> <be00>\n";
  11561. $stream .= "<bf00> <bfff> <bf00>\n";
  11562. $stream .= "<c000> <c0ff> <c000>\n";
  11563. $stream .= "<c100> <c1ff> <c100>\n";
  11564. $stream .= "<c200> <c2ff> <c200>\n";
  11565. $stream .= "<c300> <c3ff> <c300>\n";
  11566. $stream .= "<c400> <c4ff> <c400>\n";
  11567. $stream .= "<c500> <c5ff> <c500>\n";
  11568. $stream .= "<c600> <c6ff> <c600>\n";
  11569. $stream .= "<c700> <c7ff> <c700>\n";
  11570. $stream .= "endbfrange\n";
  11571. $stream .= "56 beginbfrange\n";
  11572. $stream .= "<c800> <c8ff> <c800>\n";
  11573. $stream .= "<c900> <c9ff> <c900>\n";
  11574. $stream .= "<ca00> <caff> <ca00>\n";
  11575. $stream .= "<cb00> <cbff> <cb00>\n";
  11576. $stream .= "<cc00> <ccff> <cc00>\n";
  11577. $stream .= "<cd00> <cdff> <cd00>\n";
  11578. $stream .= "<ce00> <ceff> <ce00>\n";
  11579. $stream .= "<cf00> <cfff> <cf00>\n";
  11580. $stream .= "<d000> <d0ff> <d000>\n";
  11581. $stream .= "<d100> <d1ff> <d100>\n";
  11582. $stream .= "<d200> <d2ff> <d200>\n";
  11583. $stream .= "<d300> <d3ff> <d300>\n";
  11584. $stream .= "<d400> <d4ff> <d400>\n";
  11585. $stream .= "<d500> <d5ff> <d500>\n";
  11586. $stream .= "<d600> <d6ff> <d600>\n";
  11587. $stream .= "<d700> <d7ff> <d700>\n";
  11588. $stream .= "<d800> <d8ff> <d800>\n";
  11589. $stream .= "<d900> <d9ff> <d900>\n";
  11590. $stream .= "<da00> <daff> <da00>\n";
  11591. $stream .= "<db00> <dbff> <db00>\n";
  11592. $stream .= "<dc00> <dcff> <dc00>\n";
  11593. $stream .= "<dd00> <ddff> <dd00>\n";
  11594. $stream .= "<de00> <deff> <de00>\n";
  11595. $stream .= "<df00> <dfff> <df00>\n";
  11596. $stream .= "<e000> <e0ff> <e000>\n";
  11597. $stream .= "<e100> <e1ff> <e100>\n";
  11598. $stream .= "<e200> <e2ff> <e200>\n";
  11599. $stream .= "<e300> <e3ff> <e300>\n";
  11600. $stream .= "<e400> <e4ff> <e400>\n";
  11601. $stream .= "<e500> <e5ff> <e500>\n";
  11602. $stream .= "<e600> <e6ff> <e600>\n";
  11603. $stream .= "<e700> <e7ff> <e700>\n";
  11604. $stream .= "<e800> <e8ff> <e800>\n";
  11605. $stream .= "<e900> <e9ff> <e900>\n";
  11606. $stream .= "<ea00> <eaff> <ea00>\n";
  11607. $stream .= "<eb00> <ebff> <eb00>\n";
  11608. $stream .= "<ec00> <ecff> <ec00>\n";
  11609. $stream .= "<ed00> <edff> <ed00>\n";
  11610. $stream .= "<ee00> <eeff> <ee00>\n";
  11611. $stream .= "<ef00> <efff> <ef00>\n";
  11612. $stream .= "<f000> <f0ff> <f000>\n";
  11613. $stream .= "<f100> <f1ff> <f100>\n";
  11614. $stream .= "<f200> <f2ff> <f200>\n";
  11615. $stream .= "<f300> <f3ff> <f300>\n";
  11616. $stream .= "<f400> <f4ff> <f400>\n";
  11617. $stream .= "<f500> <f5ff> <f500>\n";
  11618. $stream .= "<f600> <f6ff> <f600>\n";
  11619. $stream .= "<f700> <f7ff> <f700>\n";
  11620. $stream .= "<f800> <f8ff> <f800>\n";
  11621. $stream .= "<f900> <f9ff> <f900>\n";
  11622. $stream .= "<fa00> <faff> <fa00>\n";
  11623. $stream .= "<fb00> <fbff> <fb00>\n";
  11624. $stream .= "<fc00> <fcff> <fc00>\n";
  11625. $stream .= "<fd00> <fdff> <fd00>\n";
  11626. $stream .= "<fe00> <feff> <fe00>\n";
  11627. $stream .= "<ff00> <ffff> <ff00>\n";
  11628. $stream .= "endbfrange\n";
  11629. $stream .= "endcmap\n";
  11630. $stream .= "CMapName currentdict /CMap defineresource pop\n";
  11631. $stream .= "end\n";
  11632. $stream .= "end";
  11633. // ToUnicode Object
  11634. $this->_newobj();
  11635. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  11636. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  11637. $stream = $this->_getrawstream($stream);
  11638. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  11639. // CIDFontType2
  11640. // A CIDFont whose glyph descriptions are based on TrueType font technology
  11641. $oid = $this->_newobj();
  11642. $out = '<< /Type /Font';
  11643. $out .= ' /Subtype /CIDFontType2';
  11644. $out .= ' /BaseFont /'.$fontname;
  11645. // A dictionary containing entries that define the character collection of the CIDFont.
  11646. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  11647. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  11648. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  11649. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  11650. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  11651. $out .= ' /DW '.$font['dw']; // default width
  11652. $out .= "\n".$this->_putfontwidths($font, 0);
  11653. if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
  11654. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  11655. }
  11656. $out .= ' >>';
  11657. $out .= "\n".'endobj';
  11658. $this->_out($out);
  11659. // Font descriptor
  11660. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  11661. $this->_newobj();
  11662. $out = '<< /Type /FontDescriptor';
  11663. $out .= ' /FontName /'.$fontname;
  11664. foreach ($font['desc'] as $key => $value) {
  11665. if (is_float($value)) {
  11666. $value = sprintf('%F', $value);
  11667. }
  11668. $out .= ' /'.$key.' '.$value;
  11669. }
  11670. $fontdir = false;
  11671. if (!$this->empty_string($font['file'])) {
  11672. // A stream containing a TrueType font
  11673. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  11674. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  11675. }
  11676. $out .= ' >>';
  11677. $out .= "\n".'endobj';
  11678. $this->_out($out);
  11679. if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
  11680. $this->_newobj();
  11681. // Embed CIDToGIDMap
  11682. // A specification of the mapping from CIDs to glyph indices
  11683. // search and get CTG font file to embedd
  11684. $ctgfile = strtolower($font['ctg']);
  11685. // search and get ctg font file to embedd
  11686. $fontfile = '';
  11687. // search files on various directories
  11688. if (($fontdir !== false) AND file_exists($fontdir.$ctgfile)) {
  11689. $fontfile = $fontdir.$ctgfile;
  11690. } elseif (file_exists($this->_getfontpath().$ctgfile)) {
  11691. $fontfile = $this->_getfontpath().$ctgfile;
  11692. } elseif (file_exists($ctgfile)) {
  11693. $fontfile = $ctgfile;
  11694. }
  11695. if ($this->empty_string($fontfile)) {
  11696. $this->Error('Font file not found: '.$ctgfile);
  11697. }
  11698. $stream = $this->_getrawstream(file_get_contents($fontfile));
  11699. $out = '<< /Length '.strlen($stream).'';
  11700. if (substr($fontfile, -2) == '.z') { // check file extension
  11701. // Decompresses data encoded using the public-domain
  11702. // zlib/deflate compression method, reproducing the
  11703. // original text or binary data
  11704. $out .= ' /Filter /FlateDecode';
  11705. }
  11706. $out .= ' >>';
  11707. $out .= ' stream'."\n".$stream."\n".'endstream';
  11708. $out .= "\n".'endobj';
  11709. $this->_out($out);
  11710. }
  11711. }
  11712. /**
  11713. * Output CID-0 fonts.
  11714. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  11715. * @param $font (array) font data
  11716. * @protected
  11717. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  11718. * @since 3.2.000 (2008-06-23)
  11719. */
  11720. protected function _putcidfont0($font) {
  11721. $cidoffset = 0;
  11722. if (!isset($font['cw'][1])) {
  11723. $cidoffset = 31;
  11724. }
  11725. if (isset($font['cidinfo']['uni2cid'])) {
  11726. // convert unicode to cid.
  11727. $uni2cid = $font['cidinfo']['uni2cid'];
  11728. $cw = array();
  11729. foreach ($font['cw'] as $uni => $width) {
  11730. if (isset($uni2cid[$uni])) {
  11731. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  11732. } elseif ($uni < 256) {
  11733. $cw[$uni] = $width;
  11734. } // else unknown character
  11735. }
  11736. $font = array_merge($font, array('cw' => $cw));
  11737. }
  11738. $name = $font['name'];
  11739. $enc = $font['enc'];
  11740. if ($enc) {
  11741. $longname = $name.'-'.$enc;
  11742. } else {
  11743. $longname = $name;
  11744. }
  11745. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  11746. $out .= '<</Type /Font';
  11747. $out .= ' /Subtype /Type0';
  11748. $out .= ' /BaseFont /'.$longname;
  11749. $out .= ' /Name /F'.$font['i'];
  11750. if ($enc) {
  11751. $out .= ' /Encoding /'.$enc;
  11752. }
  11753. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  11754. $out .= ' >>';
  11755. $out .= "\n".'endobj';
  11756. $this->_out($out);
  11757. $oid = $this->_newobj();
  11758. $out = '<</Type /Font';
  11759. $out .= ' /Subtype /CIDFontType0';
  11760. $out .= ' /BaseFont /'.$name;
  11761. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  11762. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  11763. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  11764. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  11765. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  11766. $out .= ' /DW '.$font['dw'];
  11767. $out .= "\n".$this->_putfontwidths($font, $cidoffset);
  11768. $out .= ' >>';
  11769. $out .= "\n".'endobj';
  11770. $this->_out($out);
  11771. $this->_newobj();
  11772. $s = '<</Type /FontDescriptor /FontName /'.$name;
  11773. foreach ($font['desc'] as $k => $v) {
  11774. if ($k != 'Style') {
  11775. if (is_float($v)) {
  11776. $v = sprintf('%F', $v);
  11777. }
  11778. $s .= ' /'.$k.' '.$v.'';
  11779. }
  11780. }
  11781. $s .= '>>';
  11782. $s .= "\n".'endobj';
  11783. $this->_out($s);
  11784. }
  11785. /**
  11786. * Output images.
  11787. * @protected
  11788. */
  11789. protected function _putimages() {
  11790. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  11791. foreach ($this->imagekeys as $file) {
  11792. $info = $this->getImageBuffer($file);
  11793. // set object for alternate images array
  11794. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  11795. $altoid = $this->_newobj();
  11796. $out = '[';
  11797. foreach ($info['altimgs'] as $altimage) {
  11798. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  11799. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  11800. $out .= ' /DefaultForPrinting';
  11801. if ($altimage[1] === true) {
  11802. $out .= ' true';
  11803. } else {
  11804. $out .= ' false';
  11805. }
  11806. $out .= ' >>';
  11807. }
  11808. }
  11809. $out .= ' ]';
  11810. $out .= "\n".'endobj';
  11811. $this->_out($out);
  11812. }
  11813. // set image object
  11814. $oid = $this->_newobj();
  11815. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  11816. $this->setImageSubBuffer($file, 'n', $this->n);
  11817. $out = '<</Type /XObject';
  11818. $out .= ' /Subtype /Image';
  11819. $out .= ' /Width '.$info['w'];
  11820. $out .= ' /Height '.$info['h'];
  11821. if (array_key_exists('masked', $info)) {
  11822. $out .= ' /SMask '.($this->n - 1).' 0 R';
  11823. }
  11824. // set color space
  11825. $icc = false;
  11826. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  11827. // ICC Colour Space
  11828. $icc = true;
  11829. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  11830. } elseif ($info['cs'] == 'Indexed') {
  11831. // Indexed Colour Space
  11832. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  11833. } else {
  11834. // Device Colour Space
  11835. $out .= ' /ColorSpace /'.$info['cs'];
  11836. }
  11837. if ($info['cs'] == 'DeviceCMYK') {
  11838. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  11839. }
  11840. $out .= ' /BitsPerComponent '.$info['bpc'];
  11841. if (isset($altoid) AND ($altoid > 0)) {
  11842. // reference to alternate images dictionary
  11843. $out .= ' /Alternates '.$altoid.' 0 R';
  11844. }
  11845. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  11846. // external stream
  11847. $out .= ' /Length 0';
  11848. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  11849. if (isset($info['f'])) {
  11850. $out .= ' /FFilter /'.$info['f'];
  11851. }
  11852. $out .= ' >>';
  11853. $out .= ' stream'."\n".'endstream';
  11854. } else {
  11855. if (isset($info['f'])) {
  11856. $out .= ' /Filter /'.$info['f'];
  11857. }
  11858. if (isset($info['parms'])) {
  11859. $out .= ' '.$info['parms'];
  11860. }
  11861. if (isset($info['trns']) AND is_array($info['trns'])) {
  11862. $trns = '';
  11863. $count_info = count($info['trns']);
  11864. for ($i=0; $i < $count_info; ++$i) {
  11865. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  11866. }
  11867. $out .= ' /Mask ['.$trns.']';
  11868. }
  11869. $stream = $this->_getrawstream($info['data']);
  11870. $out .= ' /Length '.strlen($stream).' >>';
  11871. $out .= ' stream'."\n".$stream."\n".'endstream';
  11872. }
  11873. $out .= "\n".'endobj';
  11874. $this->_out($out);
  11875. if ($icc) {
  11876. // ICC colour profile
  11877. $this->_newobj();
  11878. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  11879. $icc = $this->_getrawstream($icc);
  11880. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  11881. } elseif ($info['cs'] == 'Indexed') {
  11882. // colour palette
  11883. $this->_newobj();
  11884. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  11885. $pal = $this->_getrawstream($pal);
  11886. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  11887. }
  11888. }
  11889. }
  11890. /**
  11891. * Output Form XObjects Templates.
  11892. * @author Nicola Asuni
  11893. * @since 5.8.017 (2010-08-24)
  11894. * @protected
  11895. * @see startTemplate(), endTemplate(), printTemplate()
  11896. */
  11897. protected function _putxobjects() {
  11898. foreach ($this->xobjects as $key => $data) {
  11899. if (isset($data['outdata'])) {
  11900. $stream = trim($data['outdata']);
  11901. $out = $this->_getobj($data['n'])."\n";
  11902. $out .= '<<';
  11903. $out .= ' /Type /XObject';
  11904. $out .= ' /Subtype /Form';
  11905. $out .= ' /FormType 1';
  11906. if ($this->compress) {
  11907. $stream = gzcompress($stream);
  11908. $out .= ' /Filter /FlateDecode';
  11909. }
  11910. $out .= sprintf(' /BBox [%F %F %F %F]', ($data['x'] * $this->k), (-$data['y'] * $this->k), (($data['w'] + $data['x']) * $this->k), (($data['h'] - $data['y']) * $this->k));
  11911. $out .= ' /Matrix [1 0 0 1 0 0]';
  11912. $out .= ' /Resources <<';
  11913. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  11914. if (!$this->pdfa_mode) {
  11915. // transparency
  11916. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  11917. $out .= ' /ExtGState <<';
  11918. foreach ($data['extgstates'] as $k => $extgstate) {
  11919. if (isset($this->extgstates[$k]['name'])) {
  11920. $out .= ' /'.$this->extgstates[$k]['name'];
  11921. } else {
  11922. $out .= ' /GS'.$k;
  11923. }
  11924. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  11925. }
  11926. $out .= ' >>';
  11927. }
  11928. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  11929. $gp = '';
  11930. $gs = '';
  11931. foreach ($data['gradients'] as $id => $grad) {
  11932. // gradient patterns
  11933. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  11934. // gradient shadings
  11935. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  11936. }
  11937. $out .= ' /Pattern <<'.$gp.' >>';
  11938. $out .= ' /Shading <<'.$gs.' >>';
  11939. }
  11940. }
  11941. // spot colors
  11942. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  11943. $out .= ' /ColorSpace <<';
  11944. foreach ($data['spot_colors'] as $name => $color) {
  11945. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  11946. }
  11947. $out .= ' >>';
  11948. }
  11949. // fonts
  11950. if (!empty($data['fonts'])) {
  11951. $out .= ' /Font <<';
  11952. foreach ($data['fonts'] as $fontkey => $fontid) {
  11953. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  11954. }
  11955. $out .= ' >>';
  11956. }
  11957. // images or nested xobjects
  11958. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  11959. $out .= ' /XObject <<';
  11960. foreach ($data['images'] as $imgid) {
  11961. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  11962. }
  11963. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  11964. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  11965. }
  11966. $out .= ' >>';
  11967. }
  11968. $out .= ' >>'; //end resources
  11969. if (isset($data['group']) AND ($data['group'] !== false)) {
  11970. // set transparency group
  11971. $out .= ' /Group << /Type /Group /S /Transparency';
  11972. if (is_array($data['group'])) {
  11973. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  11974. $out .= ' /CS /'.$data['group']['CS'];
  11975. }
  11976. if (isset($data['group']['I'])) {
  11977. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  11978. }
  11979. if (isset($data['group']['K'])) {
  11980. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  11981. }
  11982. }
  11983. $out .= ' >>';
  11984. }
  11985. $stream = $this->_getrawstream($stream, $data['n']);
  11986. $out .= ' /Length '.strlen($stream);
  11987. $out .= ' >>';
  11988. $out .= ' stream'."\n".$stream."\n".'endstream';
  11989. $out .= "\n".'endobj';
  11990. $this->_out($out);
  11991. }
  11992. }
  11993. }
  11994. /**
  11995. * Output Spot Colors Resources.
  11996. * @protected
  11997. * @since 4.0.024 (2008-09-12)
  11998. */
  11999. protected function _putspotcolors() {
  12000. foreach ($this->spot_colors as $name => $color) {
  12001. $this->_newobj();
  12002. $this->spot_colors[$name]['n'] = $this->n;
  12003. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  12004. $out .= ' /DeviceCMYK <<';
  12005. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  12006. $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  12007. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  12008. $out .= "\n".'endobj';
  12009. $this->_out($out);
  12010. }
  12011. }
  12012. /**
  12013. * Return XObjects Dictionary.
  12014. * @return string XObjects dictionary
  12015. * @protected
  12016. * @since 5.8.014 (2010-08-23)
  12017. */
  12018. protected function _getxobjectdict() {
  12019. $out = '';
  12020. foreach ($this->xobjects as $id => $objid) {
  12021. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  12022. }
  12023. return $out;
  12024. }
  12025. /**
  12026. * Output Resources Dictionary.
  12027. * @protected
  12028. */
  12029. protected function _putresourcedict() {
  12030. $out = $this->_getobj(2)."\n";
  12031. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  12032. $out .= ' /Font <<';
  12033. foreach ($this->fontkeys as $fontkey) {
  12034. $font = $this->getFontBuffer($fontkey);
  12035. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  12036. }
  12037. $out .= ' >>';
  12038. $out .= ' /XObject <<';
  12039. $out .= $this->_getxobjectdict();
  12040. $out .= ' >>';
  12041. // layers
  12042. if (!empty($this->pdflayers)) {
  12043. $out .= ' /Properties <<';
  12044. foreach ($this->pdflayers as $layer) {
  12045. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  12046. }
  12047. $out .= ' >>';
  12048. }
  12049. if (!$this->pdfa_mode) {
  12050. // transparency
  12051. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  12052. $out .= ' /ExtGState <<';
  12053. foreach ($this->extgstates as $k => $extgstate) {
  12054. if (isset($extgstate['name'])) {
  12055. $out .= ' /'.$extgstate['name'];
  12056. } else {
  12057. $out .= ' /GS'.$k;
  12058. }
  12059. $out .= ' '.$extgstate['n'].' 0 R';
  12060. }
  12061. $out .= ' >>';
  12062. }
  12063. if (isset($this->gradients) AND !empty($this->gradients)) {
  12064. $gp = '';
  12065. $gs = '';
  12066. foreach ($this->gradients as $id => $grad) {
  12067. // gradient patterns
  12068. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  12069. // gradient shadings
  12070. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  12071. }
  12072. $out .= ' /Pattern <<'.$gp.' >>';
  12073. $out .= ' /Shading <<'.$gs.' >>';
  12074. }
  12075. }
  12076. // spot colors
  12077. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  12078. $out .= ' /ColorSpace <<';
  12079. foreach ($this->spot_colors as $color) {
  12080. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  12081. }
  12082. $out .= ' >>';
  12083. }
  12084. $out .= ' >>';
  12085. $out .= "\n".'endobj';
  12086. $this->_out($out);
  12087. }
  12088. /**
  12089. * Output Resources.
  12090. * @protected
  12091. */
  12092. protected function _putresources() {
  12093. $this->_putextgstates();
  12094. $this->_putocg();
  12095. $this->_putfonts();
  12096. $this->_putimages();
  12097. $this->_putspotcolors();
  12098. $this->_putshaders();
  12099. $this->_putxobjects();
  12100. $this->_putresourcedict();
  12101. $this->_putdests();
  12102. $this->_putbookmarks();
  12103. $this->_putEmbeddedFiles();
  12104. $this->_putannotsobjs();
  12105. $this->_putjavascript();
  12106. $this->_putencryption();
  12107. }
  12108. /**
  12109. * Adds some Metadata information (Document Information Dictionary)
  12110. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  12111. * @return int object id
  12112. * @protected
  12113. */
  12114. protected function _putinfo() {
  12115. $oid = $this->_newobj();
  12116. $out = '<<';
  12117. // store current isunicode value
  12118. $prev_isunicode = $this->isunicode;
  12119. if ($this->docinfounicode) {
  12120. $this->isunicode = true;
  12121. }
  12122. if (!$this->empty_string($this->title)) {
  12123. // The document's title.
  12124. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  12125. }
  12126. if (!$this->empty_string($this->author)) {
  12127. // The name of the person who created the document.
  12128. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  12129. }
  12130. if (!$this->empty_string($this->subject)) {
  12131. // The subject of the document.
  12132. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  12133. }
  12134. if (!$this->empty_string($this->keywords)) {
  12135. // Keywords associated with the document.
  12136. $out .= ' /Keywords '.$this->_textstring($this->keywords.' TCPDF', $oid);
  12137. }
  12138. if (!$this->empty_string($this->creator)) {
  12139. // 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.
  12140. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  12141. }
  12142. // restore previous isunicode value
  12143. $this->isunicode = $prev_isunicode;
  12144. // default producer
  12145. $out .= ' /Producer '.$this->_textstring($this->pdfproducer, $oid);
  12146. // The date and time the document was created, in human-readable form
  12147. $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
  12148. // The date and time the document was most recently modified, in human-readable form
  12149. $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
  12150. // A name object indicating whether the document has been modified to include trapping information
  12151. $out .= ' /Trapped /False';
  12152. $out .= ' >>';
  12153. $out .= "\n".'endobj';
  12154. $this->_out($out);
  12155. return $oid;
  12156. }
  12157. /**
  12158. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  12159. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  12160. * @param $xmp (string) Custom XMP data.
  12161. * @since 5.9.128 (2011-10-06)
  12162. * @public
  12163. */
  12164. public function setExtraXMP($xmp) {
  12165. $this->custom_xmp = $xmp;
  12166. }
  12167. /**
  12168. * Put XMP data object and return ID.
  12169. * @return (int) The object ID.
  12170. * @since 5.9.121 (2011-09-28)
  12171. * @protected
  12172. */
  12173. protected function _putXMP() {
  12174. $oid = $this->_newobj();
  12175. // store current isunicode value
  12176. $prev_isunicode = $this->isunicode;
  12177. $this->isunicode = true;
  12178. $prev_encrypted = $this->encrypted;
  12179. $this->encrypted = false;
  12180. // set XMP data
  12181. $xmp = '<?xpacket begin="'.$this->unichr(0xfeff).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  12182. $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";
  12183. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  12184. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  12185. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  12186. $xmp .= "\t\t\t".'<dc:title>'."\n";
  12187. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  12188. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.$this->_escapeXML($this->title).'</rdf:li>'."\n";
  12189. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  12190. $xmp .= "\t\t\t".'</dc:title>'."\n";
  12191. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  12192. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  12193. $xmp .= "\t\t\t\t\t".'<rdf:li>'.$this->_escapeXML($this->author).'</rdf:li>'."\n";
  12194. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  12195. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  12196. $xmp .= "\t\t\t".'<dc:description>'."\n";
  12197. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  12198. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.$this->_escapeXML($this->subject).'</rdf:li>'."\n";
  12199. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  12200. $xmp .= "\t\t\t".'</dc:description>'."\n";
  12201. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  12202. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  12203. $xmp .= "\t\t\t\t\t".'<rdf:li>'.$this->_escapeXML($this->keywords).'</rdf:li>'."\n";
  12204. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  12205. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  12206. $xmp .= "\t\t".'</rdf:Description>'."\n";
  12207. // convert doc creation date format
  12208. $dcdate = $this->getFormattedDate($this->doc_creation_timestamp);
  12209. $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
  12210. $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
  12211. $doccreationdate .= '+'.substr($dcdate, 15, 2).':'.substr($dcdate, 18, 2);
  12212. $doccreationdate = $this->_escapeXML($doccreationdate);
  12213. // convert doc modification date format
  12214. $dmdate = $this->getFormattedDate($this->doc_modification_timestamp);
  12215. $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
  12216. $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
  12217. $docmoddate .= '+'.substr($dmdate, 15, 2).':'.substr($dmdate, 18, 2);
  12218. $docmoddate = $this->_escapeXML($docmoddate);
  12219. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  12220. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
  12221. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  12222. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
  12223. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
  12224. $xmp .= "\t\t".'</rdf:Description>'."\n";
  12225. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  12226. $xmp .= "\t\t\t".'<pdf:Keywords>'.$this->_escapeXML($this->keywords).' TCPDF</pdf:Keywords>'."\n";
  12227. $xmp .= "\t\t\t".'<pdf:Producer>'.$this->_escapeXML($this->pdfproducer).'</pdf:Producer>'."\n";
  12228. $xmp .= "\t\t".'</rdf:Description>'."\n";
  12229. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  12230. $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);
  12231. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  12232. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  12233. $xmp .= "\t\t".'</rdf:Description>'."\n";
  12234. if ($this->pdfa_mode) {
  12235. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  12236. $xmp .= "\t\t\t".'<pdfaid:part>1</pdfaid:part>'."\n";
  12237. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  12238. $xmp .= "\t\t".'</rdf:Description>'."\n";
  12239. }
  12240. // XMP extension schemas
  12241. $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";
  12242. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  12243. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  12244. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12245. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  12246. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  12247. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  12248. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  12249. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12250. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  12251. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  12252. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  12253. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  12254. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  12255. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12256. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  12257. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  12258. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  12259. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  12260. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  12261. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  12262. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  12263. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  12264. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12265. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  12266. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  12267. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  12268. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  12269. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  12270. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12271. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  12272. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  12273. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  12274. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  12275. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  12276. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12277. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  12278. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  12279. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  12280. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  12281. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  12282. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  12283. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  12284. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  12285. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  12286. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  12287. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  12288. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  12289. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  12290. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  12291. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  12292. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  12293. $xmp .= "\t\t".'</rdf:Description>'."\n";
  12294. $xmp .= "\t".'</rdf:RDF>'."\n";
  12295. $xmp .= $this->custom_xmp;
  12296. $xmp .= '</x:xmpmeta>'."\n";
  12297. $xmp .= '<?xpacket end="w"?>';
  12298. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  12299. // restore previous isunicode value
  12300. $this->isunicode = $prev_isunicode;
  12301. $this->encrypted = $prev_encrypted;
  12302. $this->_out($out);
  12303. return $oid;
  12304. }
  12305. /**
  12306. * Output Catalog.
  12307. * @return int object id
  12308. * @protected
  12309. */
  12310. protected function _putcatalog() {
  12311. // put XMP
  12312. $xmpobj = $this->_putXMP();
  12313. // if required, add standard sRGB_IEC61966-2.1 blackscaled ICC colour profile
  12314. if ($this->pdfa_mode OR $this->force_srgb) {
  12315. $iccobj = $this->_newobj();
  12316. $icc = file_get_contents(dirname(__FILE__).'/sRGB.icc');
  12317. $filter = '';
  12318. if ($this->compress) {
  12319. $filter = ' /Filter /FlateDecode';
  12320. $icc = gzcompress($icc);
  12321. }
  12322. $icc = $this->_getrawstream($icc);
  12323. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  12324. }
  12325. // start catalog
  12326. $oid = $this->_newobj();
  12327. $out = '<< /Type /Catalog';
  12328. $out .= ' /Version /'.$this->PDFVersion;
  12329. //$out .= ' /Extensions <<>>';
  12330. $out .= ' /Pages 1 0 R';
  12331. //$out .= ' /PageLabels ' //...;
  12332. $out .= ' /Names <<';
  12333. if ((!$this->pdfa_mode) AND ((!empty($this->javascript)) OR (!empty($this->js_objects)))) {
  12334. $out .= ' /JavaScript '.($this->n_js).' 0 R';
  12335. }
  12336. $out .= ' >>';
  12337. if (!empty($this->dests)) {
  12338. $out .= ' /Dests '.$this->n_dests.' 0 R';
  12339. }
  12340. $out .= $this->_putviewerpreferences();
  12341. if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
  12342. $out .= ' /PageLayout /'.$this->LayoutMode;
  12343. }
  12344. if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
  12345. $out .= ' /PageMode /'.$this->PageMode;
  12346. }
  12347. if (count($this->outlines) > 0) {
  12348. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  12349. $out .= ' /PageMode /UseOutlines';
  12350. }
  12351. //$out .= ' /Threads []';
  12352. if ($this->ZoomMode == 'fullpage') {
  12353. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  12354. } elseif ($this->ZoomMode == 'fullwidth') {
  12355. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  12356. } elseif ($this->ZoomMode == 'real') {
  12357. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  12358. } elseif (!is_string($this->ZoomMode)) {
  12359. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
  12360. }
  12361. //$out .= ' /AA <<>>';
  12362. //$out .= ' /URI <<>>';
  12363. $out .= ' /Metadata '.$xmpobj.' 0 R';
  12364. //$out .= ' /StructTreeRoot <<>>';
  12365. //$out .= ' /MarkInfo <<>>';
  12366. if (isset($this->l['a_meta_language'])) {
  12367. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  12368. }
  12369. //$out .= ' /SpiderInfo <<>>';
  12370. // set OutputIntent to sRGB IEC61966-2.1 if required
  12371. if ($this->pdfa_mode OR $this->force_srgb) {
  12372. $out .= ' /OutputIntents [<<';
  12373. $out .= ' /Type /OutputIntent';
  12374. $out .= ' /S /GTS_PDFA1';
  12375. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  12376. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  12377. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  12378. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  12379. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  12380. $out .= ' >>]';
  12381. }
  12382. //$out .= ' /PieceInfo <<>>';
  12383. if (!empty($this->pdflayers)) {
  12384. $lyrobjs = '';
  12385. $lyrobjs_print = '';
  12386. $lyrobjs_view = '';
  12387. foreach ($this->pdflayers as $layer) {
  12388. $lyrobjs .= ' '.$layer['objid'].' 0 R';
  12389. if ($layer['print']) {
  12390. $lyrobjs_print .= ' '.$layer['objid'].' 0 R';
  12391. }
  12392. if ($layer['view']) {
  12393. $lyrobjs_view .= ' '.$layer['objid'].' 0 R';
  12394. }
  12395. }
  12396. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  12397. $out .= ' /D <<';
  12398. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  12399. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  12400. $out .= ' /BaseState /ON';
  12401. $out .= ' /ON ['.$lyrobjs_print.']';
  12402. $out .= ' /OFF ['.$lyrobjs_view.']';
  12403. $out .= ' /Intent /View';
  12404. $out .= ' /AS [';
  12405. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  12406. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  12407. $out .= ' ]';
  12408. $out .= ' /Order ['.$lyrobjs.']';
  12409. $out .= ' /ListMode /AllPages';
  12410. //$out .= ' /RBGroups ['..']';
  12411. //$out .= ' /Locked ['..']';
  12412. $out .= ' >>';
  12413. $out .= ' >>';
  12414. }
  12415. // AcroForm
  12416. if (!empty($this->form_obj_id) OR ($this->sign AND isset($this->signature_data['cert_type']))) {
  12417. $out .= ' /AcroForm <<';
  12418. $objrefs = '';
  12419. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12420. // set reference for signature object
  12421. $objrefs .= $this->sig_obj_id.' 0 R';
  12422. }
  12423. if (!empty($this->empty_signature_appearance)) {
  12424. foreach ($this->empty_signature_appearance as $esa) {
  12425. // set reference for empty signature objects
  12426. $objrefs .= ' '.$esa['objid'].' 0 R';
  12427. }
  12428. }
  12429. if (!empty($this->form_obj_id)) {
  12430. foreach($this->form_obj_id as $objid) {
  12431. $objrefs .= ' '.$objid.' 0 R';
  12432. }
  12433. }
  12434. $out .= ' /Fields ['.$objrefs.']';
  12435. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  12436. $out .= ' /NeedAppearances false';
  12437. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12438. if ($this->signature_data['cert_type'] > 0) {
  12439. $out .= ' /SigFlags 3';
  12440. } else {
  12441. $out .= ' /SigFlags 1';
  12442. }
  12443. }
  12444. //$out .= ' /CO ';
  12445. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  12446. $out .= ' /DR <<';
  12447. $out .= ' /Font <<';
  12448. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  12449. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  12450. }
  12451. $out .= ' >> >>';
  12452. }
  12453. $font = $this->getFontBuffer('helvetica');
  12454. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  12455. $out .= ' /Q '.(($this->rtl)?'2':'0');
  12456. //$out .= ' /XFA ';
  12457. $out .= ' >>';
  12458. // signatures
  12459. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12460. if ($this->signature_data['cert_type'] > 0) {
  12461. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  12462. } else {
  12463. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  12464. }
  12465. }
  12466. }
  12467. //$out .= ' /Legal <<>>';
  12468. //$out .= ' /Requirements []';
  12469. //$out .= ' /Collection <<>>';
  12470. //$out .= ' /NeedsRendering true';
  12471. $out .= ' >>';
  12472. $out .= "\n".'endobj';
  12473. $this->_out($out);
  12474. return $oid;
  12475. }
  12476. /**
  12477. * Output viewer preferences.
  12478. * @return string for viewer preferences
  12479. * @author Nicola asuni
  12480. * @since 3.1.000 (2008-06-09)
  12481. * @protected
  12482. */
  12483. protected function _putviewerpreferences() {
  12484. $out = ' /ViewerPreferences <<';
  12485. if ($this->rtl) {
  12486. $out .= ' /Direction /R2L';
  12487. } else {
  12488. $out .= ' /Direction /L2R';
  12489. }
  12490. if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
  12491. $out .= ' /HideToolbar true';
  12492. }
  12493. if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
  12494. $out .= ' /HideMenubar true';
  12495. }
  12496. if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
  12497. $out .= ' /HideWindowUI true';
  12498. }
  12499. if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
  12500. $out .= ' /FitWindow true';
  12501. }
  12502. if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
  12503. $out .= ' /CenterWindow true';
  12504. }
  12505. if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
  12506. $out .= ' /DisplayDocTitle true';
  12507. }
  12508. if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
  12509. $out .= ' /NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'];
  12510. }
  12511. if (isset($this->viewer_preferences['ViewArea'])) {
  12512. $out .= ' /ViewArea /'.$this->viewer_preferences['ViewArea'];
  12513. }
  12514. if (isset($this->viewer_preferences['ViewClip'])) {
  12515. $out .= ' /ViewClip /'.$this->viewer_preferences['ViewClip'];
  12516. }
  12517. if (isset($this->viewer_preferences['PrintArea'])) {
  12518. $out .= ' /PrintArea /'.$this->viewer_preferences['PrintArea'];
  12519. }
  12520. if (isset($this->viewer_preferences['PrintClip'])) {
  12521. $out .= ' /PrintClip /'.$this->viewer_preferences['PrintClip'];
  12522. }
  12523. if (isset($this->viewer_preferences['PrintScaling'])) {
  12524. $out .= ' /PrintScaling /'.$this->viewer_preferences['PrintScaling'];
  12525. }
  12526. if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
  12527. $out .= ' /Duplex /'.$this->viewer_preferences['Duplex'];
  12528. }
  12529. if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
  12530. if ($this->viewer_preferences['PickTrayByPDFSize']) {
  12531. $out .= ' /PickTrayByPDFSize true';
  12532. } else {
  12533. $out .= ' /PickTrayByPDFSize false';
  12534. }
  12535. }
  12536. if (isset($this->viewer_preferences['PrintPageRange'])) {
  12537. $PrintPageRangeNum = '';
  12538. foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
  12539. $PrintPageRangeNum .= ' '.($v - 1).'';
  12540. }
  12541. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  12542. }
  12543. if (isset($this->viewer_preferences['NumCopies'])) {
  12544. $out .= ' /NumCopies '.intval($this->viewer_preferences['NumCopies']);
  12545. }
  12546. $out .= ' >>';
  12547. return $out;
  12548. }
  12549. /**
  12550. * Output PDF File Header (7.5.2).
  12551. * @protected
  12552. */
  12553. protected function _putheader() {
  12554. $this->_out('%PDF-'.$this->PDFVersion);
  12555. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  12556. }
  12557. /**
  12558. * Output end of document (EOF).
  12559. * @protected
  12560. */
  12561. protected function _enddoc() {
  12562. $this->state = 1;
  12563. $this->_putheader();
  12564. $this->_putpages();
  12565. $this->_putresources();
  12566. // empty signature fields
  12567. if (!empty($this->empty_signature_appearance)) {
  12568. foreach ($this->empty_signature_appearance as $key => $esa) {
  12569. // widget annotation for empty signature
  12570. $out = $this->_getobj($esa['objid'])."\n";
  12571. $out .= '<< /Type /Annot';
  12572. $out .= ' /Subtype /Widget';
  12573. $out .= ' /Rect ['.$esa['rect'].']';
  12574. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  12575. $out .= ' /F 4';
  12576. $out .= ' /FT /Sig';
  12577. $signame = sprintf('Signature_%03d', ($key + 1));
  12578. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  12579. $out .= ' /Ff 0';
  12580. $out .= ' >>';
  12581. $out .= "\n".'endobj';
  12582. $this->_out($out);
  12583. }
  12584. }
  12585. // Signature
  12586. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  12587. // widget annotation for signature
  12588. $out = $this->_getobj($this->sig_obj_id)."\n";
  12589. $out .= '<< /Type /Annot';
  12590. $out .= ' /Subtype /Widget';
  12591. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  12592. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  12593. $out .= ' /F 4';
  12594. $out .= ' /FT /Sig';
  12595. $out .= ' /T '.$this->_textstring('Signature_000', $this->sig_obj_id);
  12596. $out .= ' /Ff 0';
  12597. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  12598. $out .= ' >>';
  12599. $out .= "\n".'endobj';
  12600. $this->_out($out);
  12601. // signature
  12602. $this->_putsignature();
  12603. }
  12604. // Info
  12605. $objid_info = $this->_putinfo();
  12606. // Catalog
  12607. $objid_catalog = $this->_putcatalog();
  12608. // Cross-ref
  12609. $o = $this->bufferlen;
  12610. // XREF section
  12611. $this->_out('xref');
  12612. $this->_out('0 '.($this->n + 1));
  12613. $this->_out('0000000000 65535 f ');
  12614. $freegen = ($this->n + 2);
  12615. for ($i=1; $i <= $this->n; ++$i) {
  12616. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  12617. $this->_out(sprintf('0000000000 %05d f ', $freegen));
  12618. ++$freegen;
  12619. } else {
  12620. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  12621. }
  12622. }
  12623. // TRAILER
  12624. $out = 'trailer'."\n";
  12625. $out .= '<<';
  12626. $out .= ' /Size '.($this->n + 1);
  12627. $out .= ' /Root '.$objid_catalog.' 0 R';
  12628. $out .= ' /Info '.$objid_info.' 0 R';
  12629. if ($this->encrypted) {
  12630. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  12631. }
  12632. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  12633. $out .= ' >>';
  12634. $this->_out($out);
  12635. $this->_out('startxref');
  12636. $this->_out($o);
  12637. $this->_out('%%EOF');
  12638. $this->state = 3; // end-of-doc
  12639. if ($this->diskcache) {
  12640. // remove temporary files used for images
  12641. foreach ($this->imagekeys as $key) {
  12642. // remove temporary files
  12643. unlink($this->images[$key]);
  12644. }
  12645. foreach ($this->fontkeys as $key) {
  12646. // remove temporary files
  12647. unlink($this->fonts[$key]);
  12648. }
  12649. }
  12650. }
  12651. /**
  12652. * Initialize a new page.
  12653. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  12654. * @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().
  12655. * @protected
  12656. * @see getPageSizeFromFormat(), setPageFormat()
  12657. */
  12658. protected function _beginpage($orientation='', $format='') {
  12659. ++$this->page;
  12660. $this->pageobjects[$this->page] = array();
  12661. $this->setPageBuffer($this->page, '');
  12662. // initialize array for graphics tranformation positions inside a page buffer
  12663. $this->transfmrk[$this->page] = array();
  12664. $this->state = 2;
  12665. if ($this->empty_string($orientation)) {
  12666. if (isset($this->CurOrientation)) {
  12667. $orientation = $this->CurOrientation;
  12668. } elseif ($this->fwPt > $this->fhPt) {
  12669. // landscape
  12670. $orientation = 'L';
  12671. } else {
  12672. // portrait
  12673. $orientation = 'P';
  12674. }
  12675. }
  12676. if ($this->empty_string($format)) {
  12677. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  12678. $this->setPageOrientation($orientation);
  12679. } else {
  12680. $this->setPageFormat($format, $orientation);
  12681. }
  12682. if ($this->rtl) {
  12683. $this->x = $this->w - $this->rMargin;
  12684. } else {
  12685. $this->x = $this->lMargin;
  12686. }
  12687. $this->y = $this->tMargin;
  12688. if (isset($this->newpagegroup[$this->page])) {
  12689. // start a new group
  12690. $this->currpagegroup = $this->newpagegroup[$this->page];
  12691. $this->pagegroups[$this->currpagegroup] = 1;
  12692. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  12693. ++$this->pagegroups[$this->currpagegroup];
  12694. }
  12695. }
  12696. /**
  12697. * Mark end of page.
  12698. * @protected
  12699. */
  12700. protected function _endpage() {
  12701. $this->setVisibility('all');
  12702. $this->state = 1;
  12703. }
  12704. /**
  12705. * Begin a new object and return the object number.
  12706. * @return int object number
  12707. * @protected
  12708. */
  12709. protected function _newobj() {
  12710. $this->_out($this->_getobj());
  12711. return $this->n;
  12712. }
  12713. /**
  12714. * Return the starting object string for the selected object ID.
  12715. * @param $objid (int) Object ID (leave empty to get a new ID).
  12716. * @return string the starting object string
  12717. * @protected
  12718. * @since 5.8.009 (2010-08-20)
  12719. */
  12720. protected function _getobj($objid='') {
  12721. if ($objid === '') {
  12722. ++$this->n;
  12723. $objid = $this->n;
  12724. }
  12725. $this->offsets[$objid] = $this->bufferlen;
  12726. $this->pageobjects[$this->page][] = $objid;
  12727. return $objid.' 0 obj';
  12728. }
  12729. /**
  12730. * Underline text.
  12731. * @param $x (int) X coordinate
  12732. * @param $y (int) Y coordinate
  12733. * @param $txt (string) text to underline
  12734. * @protected
  12735. */
  12736. protected function _dounderline($x, $y, $txt) {
  12737. $w = $this->GetStringWidth($txt);
  12738. return $this->_dounderlinew($x, $y, $w);
  12739. }
  12740. /**
  12741. * Underline for rectangular text area.
  12742. * @param $x (int) X coordinate
  12743. * @param $y (int) Y coordinate
  12744. * @param $w (int) width to underline
  12745. * @protected
  12746. * @since 4.8.008 (2009-09-29)
  12747. */
  12748. protected function _dounderlinew($x, $y, $w) {
  12749. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  12750. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  12751. }
  12752. /**
  12753. * Line through text.
  12754. * @param $x (int) X coordinate
  12755. * @param $y (int) Y coordinate
  12756. * @param $txt (string) text to linethrough
  12757. * @protected
  12758. */
  12759. protected function _dolinethrough($x, $y, $txt) {
  12760. $w = $this->GetStringWidth($txt);
  12761. return $this->_dolinethroughw($x, $y, $w);
  12762. }
  12763. /**
  12764. * Line through for rectangular text area.
  12765. * @param $x (int) X coordinate
  12766. * @param $y (int) Y coordinate
  12767. * @param $w (int) line length (width)
  12768. * @protected
  12769. * @since 4.9.008 (2009-09-29)
  12770. */
  12771. protected function _dolinethroughw($x, $y, $w) {
  12772. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  12773. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  12774. }
  12775. /**
  12776. * Overline text.
  12777. * @param $x (int) X coordinate
  12778. * @param $y (int) Y coordinate
  12779. * @param $txt (string) text to overline
  12780. * @protected
  12781. * @since 4.9.015 (2010-04-19)
  12782. */
  12783. protected function _dooverline($x, $y, $txt) {
  12784. $w = $this->GetStringWidth($txt);
  12785. return $this->_dooverlinew($x, $y, $w);
  12786. }
  12787. /**
  12788. * Overline for rectangular text area.
  12789. * @param $x (int) X coordinate
  12790. * @param $y (int) Y coordinate
  12791. * @param $w (int) width to overline
  12792. * @protected
  12793. * @since 4.9.015 (2010-04-19)
  12794. */
  12795. protected function _dooverlinew($x, $y, $w) {
  12796. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  12797. return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  12798. }
  12799. /**
  12800. * Read a 4-byte (32 bit) integer from file.
  12801. * @param $f (string) file name.
  12802. * @return 4-byte integer
  12803. * @protected
  12804. */
  12805. protected function _freadint($f) {
  12806. $a = unpack('Ni', fread($f, 4));
  12807. return $a['i'];
  12808. }
  12809. /**
  12810. * Add "\" before "\", "(" and ")"
  12811. * @param $s (string) string to escape.
  12812. * @return string escaped string.
  12813. * @protected
  12814. */
  12815. protected function _escape($s) {
  12816. // the chr(13) substitution fixes the Bugs item #1421290.
  12817. return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
  12818. }
  12819. /**
  12820. * Format a data string for meta information
  12821. * @param $s (string) data string to escape.
  12822. * @param $n (int) object ID
  12823. * @return string escaped string.
  12824. * @protected
  12825. */
  12826. protected function _datastring($s, $n=0) {
  12827. if ($n == 0) {
  12828. $n = $this->n;
  12829. }
  12830. $s = $this->_encrypt_data($n, $s);
  12831. return '('. $this->_escape($s).')';
  12832. }
  12833. /**
  12834. * Set the document creation timestamp
  12835. * @param $time (mixed) Document creation timestamp in seconds or date-time string.
  12836. * @public
  12837. * @since 5.9.152 (2012-03-23)
  12838. */
  12839. public function setDocCreationTimestamp($time) {
  12840. if (is_string($time)) {
  12841. $time = getTimestamp($time);
  12842. }
  12843. $this->doc_creation_timestamp = intval($time);
  12844. }
  12845. /**
  12846. * Set the document modification timestamp
  12847. * @param $time (mixed) Document modification timestamp in seconds or date-time string.
  12848. * @public
  12849. * @since 5.9.152 (2012-03-23)
  12850. */
  12851. public function setDocModificationTimestamp($time) {
  12852. if (is_string($time)) {
  12853. $time = getTimestamp($time);
  12854. }
  12855. $this->doc_modification_timestamp = intval($time);
  12856. }
  12857. /**
  12858. * Returns document creation timestamp in seconds.
  12859. * @return (int) Creation timestamp in seconds.
  12860. * @public
  12861. * @since 5.9.152 (2012-03-23)
  12862. */
  12863. public function getDocCreationTimestamp() {
  12864. return $this->doc_creation_timestamp;
  12865. }
  12866. /**
  12867. * Returns document modification timestamp in seconds.
  12868. * @return (int) Modfication timestamp in seconds.
  12869. * @public
  12870. * @since 5.9.152 (2012-03-23)
  12871. */
  12872. public function getDocModificationTimestamp() {
  12873. return $this->doc_modification_timestamp;
  12874. }
  12875. /**
  12876. * Returns timestamp in seconds from formatted date-time.
  12877. * @param $date (string) Formatted date-time.
  12878. * @return int seconds.
  12879. * @public
  12880. * @since 5.9.152 (2012-03-23)
  12881. */
  12882. public function getTimestamp($date) {
  12883. if (($date[0] == 'D') AND ($date[1] == ':')) {
  12884. // remove date prefix if present
  12885. $date = substr($date, 2);
  12886. }
  12887. return strtotime($date);
  12888. }
  12889. /**
  12890. * Returns a formatted date-time.
  12891. * @param $time (int) Time in seconds.
  12892. * @return string escaped date string.
  12893. * @public
  12894. * @since 5.9.152 (2012-03-23)
  12895. */
  12896. public function getFormattedDate($time) {
  12897. return substr_replace(date('YmdHisO', intval($time)), '\'', (0 - 2), 0).'\'';
  12898. }
  12899. /**
  12900. * Returns a formatted date for meta information
  12901. * @param $n (int) Object ID.
  12902. * @param $timestamp (int) Timestamp to convert.
  12903. * @return string escaped date string.
  12904. * @protected
  12905. * @since 4.6.028 (2009-08-25)
  12906. */
  12907. protected function _datestring($n=0, $timestamp=0) {
  12908. if ((empty($timestamp)) OR ($timestamp < 0)) {
  12909. $timestamp = $this->doc_creation_timestamp;
  12910. }
  12911. return $this->_datastring('D:'.$this->getFormattedDate($timestamp), $n);
  12912. }
  12913. /**
  12914. * Format a text string for meta information
  12915. * @param $s (string) string to escape.
  12916. * @param $n (int) object ID
  12917. * @return string escaped string.
  12918. * @protected
  12919. */
  12920. protected function _textstring($s, $n=0) {
  12921. if ($this->isunicode) {
  12922. //Convert string to UTF-16BE
  12923. $s = $this->UTF8ToUTF16BE($s, true);
  12924. }
  12925. return $this->_datastring($s, $n);
  12926. }
  12927. /**
  12928. * THIS METHOD IS DEPRECATED
  12929. * Format a text string
  12930. * @param $s (string) string to escape.
  12931. * @return string escaped string.
  12932. * @protected
  12933. * @deprecated
  12934. */
  12935. protected function _escapetext($s) {
  12936. if ($this->isunicode) {
  12937. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  12938. $s = $this->UTF8ToLatin1($s);
  12939. } else {
  12940. //Convert string to UTF-16BE and reverse RTL language
  12941. $s = $this->utf8StrRev($s, false, $this->tmprtl);
  12942. }
  12943. }
  12944. return $this->_escape($s);
  12945. }
  12946. /**
  12947. * Escape some special characters (&lt; &gt; &amp;) for XML output.
  12948. * @param $str (string) Input string to convert.
  12949. * @return converted string
  12950. * @since 5.9.121 (2011-09-28)
  12951. * @protected
  12952. */
  12953. protected function _escapeXML($str) {
  12954. $replaceTable = array("\0" => '', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;');
  12955. $str = strtr($str, $replaceTable);
  12956. return $str;
  12957. }
  12958. /**
  12959. * get raw output stream.
  12960. * @param $s (string) string to output.
  12961. * @param $n (int) object reference for encryption mode
  12962. * @protected
  12963. * @author Nicola Asuni
  12964. * @since 5.5.000 (2010-06-22)
  12965. */
  12966. protected function _getrawstream($s, $n=0) {
  12967. if ($n <= 0) {
  12968. // default to current object
  12969. $n = $this->n;
  12970. }
  12971. return $this->_encrypt_data($n, $s);
  12972. }
  12973. /**
  12974. * Format output stream (DEPRECATED).
  12975. * @param $s (string) string to output.
  12976. * @param $n (int) object reference for encryption mode
  12977. * @protected
  12978. * @deprecated
  12979. */
  12980. protected function _getstream($s, $n=0) {
  12981. return 'stream'."\n".$this->_getrawstream($s, $n)."\n".'endstream';
  12982. }
  12983. /**
  12984. * Output a stream (DEPRECATED).
  12985. * @param $s (string) string to output.
  12986. * @param $n (int) object reference for encryption mode
  12987. * @protected
  12988. * @deprecated
  12989. */
  12990. protected function _putstream($s, $n=0) {
  12991. $this->_out($this->_getstream($s, $n));
  12992. }
  12993. /**
  12994. * Output a string to the document.
  12995. * @param $s (string) string to output.
  12996. * @protected
  12997. */
  12998. protected function _out($s) {
  12999. if ($this->state == 2) {
  13000. if ($this->inxobj) {
  13001. // we are inside an XObject template
  13002. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  13003. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  13004. // puts data before page footer
  13005. $pagebuff = $this->getPageBuffer($this->page);
  13006. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  13007. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  13008. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  13009. // update footer position
  13010. $this->footerpos[$this->page] += strlen($s."\n");
  13011. } else {
  13012. $this->setPageBuffer($this->page, $s."\n", true);
  13013. }
  13014. } else {
  13015. $this->setBuffer($s."\n");
  13016. }
  13017. }
  13018. /**
  13019. * Converts UTF-8 strings to codepoints array.<br>
  13020. * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
  13021. * Based on: http://www.faqs.org/rfcs/rfc3629.html
  13022. * <pre>
  13023. * Char. number range | UTF-8 octet sequence
  13024. * (hexadecimal) | (binary)
  13025. * --------------------+-----------------------------------------------
  13026. * 0000 0000-0000 007F | 0xxxxxxx
  13027. * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
  13028. * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
  13029. * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  13030. * ---------------------------------------------------------------------
  13031. *
  13032. * ABFN notation:
  13033. * ---------------------------------------------------------------------
  13034. * UTF8-octets = *( UTF8-char )
  13035. * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
  13036. * UTF8-1 = %x00-7F
  13037. * UTF8-2 = %xC2-DF UTF8-tail
  13038. *
  13039. * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
  13040. * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
  13041. * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
  13042. * %xF4 %x80-8F 2( UTF8-tail )
  13043. * UTF8-tail = %x80-BF
  13044. * ---------------------------------------------------------------------
  13045. * </pre>
  13046. * @param $str (string) string to process.
  13047. * @return array containing codepoints (UTF-8 characters values)
  13048. * @protected
  13049. * @author Nicola Asuni
  13050. * @since 1.53.0.TC005 (2005-01-05)
  13051. */
  13052. protected function UTF8StringToArray($str) {
  13053. // build a unique string key
  13054. $strkey = md5($str);
  13055. if (isset($this->cache_UTF8StringToArray[$strkey])) {
  13056. // return cached value
  13057. $chrarray = $this->cache_UTF8StringToArray[$strkey]['s'];
  13058. if (!isset($this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']])) {
  13059. if ($this->isunicode) {
  13060. foreach ($chrarray as $chr) {
  13061. // store this char for font subsetting
  13062. $this->CurrentFont['subsetchars'][$chr] = true;
  13063. }
  13064. // update font subsetchars
  13065. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  13066. }
  13067. $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
  13068. }
  13069. return $chrarray;
  13070. }
  13071. // check cache size
  13072. if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
  13073. // remove first element
  13074. array_shift($this->cache_UTF8StringToArray);
  13075. }
  13076. // new cache array for selected string
  13077. $this->cache_UTF8StringToArray[$strkey] = array('s' => array(), 'f' => array());
  13078. ++$this->cache_size_UTF8StringToArray;
  13079. if (!$this->isunicode) {
  13080. // split string into array of equivalent codes
  13081. $strarr = array();
  13082. $strlen = strlen($str);
  13083. for ($i=0; $i < $strlen; ++$i) {
  13084. $strarr[] = ord($str[$i]);
  13085. }
  13086. // insert new value on cache
  13087. $this->cache_UTF8StringToArray[$strkey]['s'] = $strarr;
  13088. $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
  13089. return $strarr;
  13090. }
  13091. $unichar = -1; // last unicode char
  13092. $unicode = array(); // array containing unicode values
  13093. $bytes = array(); // array containing single character byte sequences
  13094. $numbytes = 1; // number of octetc needed to represent the UTF-8 character
  13095. $str .= ''; // force $str to be a string
  13096. $length = strlen($str);
  13097. for ($i = 0; $i < $length; ++$i) {
  13098. $char = ord($str[$i]); // get one string character at time
  13099. if (count($bytes) == 0) { // get starting octect
  13100. if ($char <= 0x7F) {
  13101. $unichar = $char; // use the character "as is" because is ASCII
  13102. $numbytes = 1;
  13103. } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
  13104. $bytes[] = ($char - 0xC0) << 0x06;
  13105. $numbytes = 2;
  13106. } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
  13107. $bytes[] = ($char - 0xE0) << 0x0C;
  13108. $numbytes = 3;
  13109. } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
  13110. $bytes[] = ($char - 0xF0) << 0x12;
  13111. $numbytes = 4;
  13112. } else {
  13113. // use replacement character for other invalid sequences
  13114. $unichar = 0xFFFD;
  13115. $bytes = array();
  13116. $numbytes = 1;
  13117. }
  13118. } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  13119. $bytes[] = $char - 0x80;
  13120. if (count($bytes) == $numbytes) {
  13121. // compose UTF-8 bytes to a single unicode value
  13122. $char = $bytes[0];
  13123. for ($j = 1; $j < $numbytes; ++$j) {
  13124. $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
  13125. }
  13126. if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
  13127. /* The definition of UTF-8 prohibits encoding character numbers between
  13128. U+D800 and U+DFFF, which are reserved for use with the UTF-16
  13129. encoding form (as surrogate pairs) and do not directly represent
  13130. characters. */
  13131. $unichar = 0xFFFD; // use replacement character
  13132. } else {
  13133. $unichar = $char; // add char to array
  13134. }
  13135. // reset data for next char
  13136. $bytes = array();
  13137. $numbytes = 1;
  13138. }
  13139. } else {
  13140. // use replacement character for other invalid sequences
  13141. $unichar = 0xFFFD;
  13142. $bytes = array();
  13143. $numbytes = 1;
  13144. }
  13145. if ($unichar >= 0) {
  13146. // insert unicode value into array
  13147. $unicode[] = $unichar;
  13148. // store this char for font subsetting
  13149. $this->CurrentFont['subsetchars'][$unichar] = true;
  13150. $unichar = -1;
  13151. }
  13152. }
  13153. // update font subsetchars
  13154. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  13155. // insert new value on cache
  13156. $this->cache_UTF8StringToArray[$strkey]['s'] = $unicode;
  13157. $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
  13158. return $unicode;
  13159. }
  13160. /**
  13161. * Converts UTF-8 strings to UTF16-BE.<br>
  13162. * @param $str (string) string to process.
  13163. * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
  13164. * @return string
  13165. * @author Nicola Asuni
  13166. * @since 1.53.0.TC005 (2005-01-05)
  13167. * @see UTF8StringToArray(), arrUTF8ToUTF16BE()
  13168. * @protected
  13169. */
  13170. protected function UTF8ToUTF16BE($str, $setbom=false) {
  13171. if (!$this->isunicode) {
  13172. return $str; // string is not in unicode
  13173. }
  13174. $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
  13175. return $this->arrUTF8ToUTF16BE($unicode, $setbom);
  13176. }
  13177. /**
  13178. * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
  13179. * @param $str (string) string to process.
  13180. * @return string
  13181. * @author Andrew Whitehead, Nicola Asuni
  13182. * @protected
  13183. * @since 3.2.000 (2008-06-23)
  13184. */
  13185. protected function UTF8ToLatin1($str) {
  13186. if (!$this->isunicode) {
  13187. return $str; // string is not in unicode
  13188. }
  13189. $outstr = ''; // string to be returned
  13190. $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
  13191. foreach ($unicode as $char) {
  13192. if ($char < 256) {
  13193. $outstr .= chr($char);
  13194. } elseif (array_key_exists($char, $this->unicode->uni_utf8tolatin)) {
  13195. // map from UTF-8
  13196. $outstr .= chr($this->unicode->uni_utf8tolatin[$char]);
  13197. } elseif ($char == 0xFFFD) {
  13198. // skip
  13199. } else {
  13200. $outstr .= '?';
  13201. }
  13202. }
  13203. return $outstr;
  13204. }
  13205. /**
  13206. * Converts UTF-8 characters array to array of Latin1 characters<br>
  13207. * @param $unicode (array) array containing UTF-8 unicode values
  13208. * @return array
  13209. * @author Nicola Asuni
  13210. * @protected
  13211. * @since 4.8.023 (2010-01-15)
  13212. */
  13213. protected function UTF8ArrToLatin1($unicode) {
  13214. if ((!$this->isunicode) OR $this->isUnicodeFont()) {
  13215. return $unicode;
  13216. }
  13217. $outarr = array(); // array to be returned
  13218. foreach ($unicode as $char) {
  13219. if ($char < 256) {
  13220. $outarr[] = $char;
  13221. } elseif (array_key_exists($char, $this->unicode->uni_utf8tolatin)) {
  13222. // map from UTF-8
  13223. $outarr[] = $this->unicode->uni_utf8tolatin[$char];
  13224. } elseif ($char == 0xFFFD) {
  13225. // skip
  13226. } else {
  13227. $outarr[] = 63; // '?' character
  13228. }
  13229. }
  13230. return $outarr;
  13231. }
  13232. /**
  13233. * Converts array of UTF-8 characters to UTF16-BE string.<br>
  13234. * Based on: http://www.faqs.org/rfcs/rfc2781.html
  13235. * <pre>
  13236. * Encoding UTF-16:
  13237. *
  13238. * Encoding of a single character from an ISO 10646 character value to
  13239. * UTF-16 proceeds as follows. Let U be the character number, no greater
  13240. * than 0x10FFFF.
  13241. *
  13242. * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
  13243. * terminate.
  13244. *
  13245. * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
  13246. * U' must be less than or equal to 0xFFFFF. That is, U' can be
  13247. * represented in 20 bits.
  13248. *
  13249. * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
  13250. * 0xDC00, respectively. These integers each have 10 bits free to
  13251. * encode the character value, for a total of 20 bits.
  13252. *
  13253. * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
  13254. * bits of W1 and the 10 low-order bits of U' to the 10 low-order
  13255. * bits of W2. Terminate.
  13256. *
  13257. * Graphically, steps 2 through 4 look like:
  13258. * U' = yyyyyyyyyyxxxxxxxxxx
  13259. * W1 = 110110yyyyyyyyyy
  13260. * W2 = 110111xxxxxxxxxx
  13261. * </pre>
  13262. * @param $unicode (array) array containing UTF-8 unicode values
  13263. * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
  13264. * @return string
  13265. * @protected
  13266. * @author Nicola Asuni
  13267. * @since 2.1.000 (2008-01-08)
  13268. * @see UTF8ToUTF16BE()
  13269. */
  13270. protected function arrUTF8ToUTF16BE($unicode, $setbom=false) {
  13271. $outstr = ''; // string to be returned
  13272. if ($setbom) {
  13273. $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
  13274. }
  13275. foreach ($unicode as $char) {
  13276. if ($char == 0x200b) {
  13277. // skip Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)
  13278. } elseif ($char == 0xFFFD) {
  13279. $outstr .= "\xFF\xFD"; // replacement character
  13280. } elseif ($char < 0x10000) {
  13281. $outstr .= chr($char >> 0x08);
  13282. $outstr .= chr($char & 0xFF);
  13283. } else {
  13284. $char -= 0x10000;
  13285. $w1 = 0xD800 | ($char >> 0x0a);
  13286. $w2 = 0xDC00 | ($char & 0x3FF);
  13287. $outstr .= chr($w1 >> 0x08);
  13288. $outstr .= chr($w1 & 0xFF);
  13289. $outstr .= chr($w2 >> 0x08);
  13290. $outstr .= chr($w2 & 0xFF);
  13291. }
  13292. }
  13293. return $outstr;
  13294. }
  13295. // ====================================================
  13296. /**
  13297. * Set header font.
  13298. * @param $font (array) font
  13299. * @public
  13300. * @since 1.1
  13301. */
  13302. public function setHeaderFont($font) {
  13303. $this->header_font = $font;
  13304. }
  13305. /**
  13306. * Get header font.
  13307. * @return array()
  13308. * @public
  13309. * @since 4.0.012 (2008-07-24)
  13310. */
  13311. public function getHeaderFont() {
  13312. return $this->header_font;
  13313. }
  13314. /**
  13315. * Set footer font.
  13316. * @param $font (array) font
  13317. * @public
  13318. * @since 1.1
  13319. */
  13320. public function setFooterFont($font) {
  13321. $this->footer_font = $font;
  13322. }
  13323. /**
  13324. * Get Footer font.
  13325. * @return array()
  13326. * @public
  13327. * @since 4.0.012 (2008-07-24)
  13328. */
  13329. public function getFooterFont() {
  13330. return $this->footer_font;
  13331. }
  13332. /**
  13333. * Set language array.
  13334. * @param $language (array)
  13335. * @public
  13336. * @since 1.1
  13337. */
  13338. public function setLanguageArray($language) {
  13339. $this->l = $language;
  13340. if (isset($this->l['a_meta_dir'])) {
  13341. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  13342. } else {
  13343. $this->rtl = false;
  13344. }
  13345. }
  13346. /**
  13347. * Returns the PDF data.
  13348. * @public
  13349. */
  13350. public function getPDFData() {
  13351. if ($this->state < 3) {
  13352. $this->Close();
  13353. }
  13354. return $this->buffer;
  13355. }
  13356. /**
  13357. * Output anchor link.
  13358. * @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;)
  13359. * @param $name (string) link name
  13360. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  13361. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  13362. * @param $color (array) array of RGB text color
  13363. * @param $style (string) font style (U, D, B, I)
  13364. * @param $firstblock (boolean) if true the string is the starting of a line.
  13365. * @return the number of cells used or the remaining text if $firstline = true;
  13366. * @public
  13367. */
  13368. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  13369. if (!$this->empty_string($url) AND ($url{0} == '#')) {
  13370. // convert url to internal link
  13371. $lnkdata = explode(',', $url);
  13372. if (isset($lnkdata[0])) {
  13373. $page = intval(substr($lnkdata[0], 1));
  13374. if (empty($page) OR ($page <= 0)) {
  13375. $page = $this->page;
  13376. }
  13377. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  13378. $lnky = floatval($lnkdata[1]);
  13379. } else {
  13380. $lnky = 0;
  13381. }
  13382. $url = $this->AddLink();
  13383. $this->SetLink($url, $lnky, $page);
  13384. }
  13385. }
  13386. // store current settings
  13387. $prevcolor = $this->fgcolor;
  13388. $prevstyle = $this->FontStyle;
  13389. if (empty($color)) {
  13390. $this->SetTextColorArray($this->htmlLinkColorArray);
  13391. } else {
  13392. $this->SetTextColorArray($color);
  13393. }
  13394. if ($style == -1) {
  13395. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  13396. } else {
  13397. $this->SetFont('', $this->FontStyle.$style);
  13398. }
  13399. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  13400. // restore settings
  13401. $this->SetFont('', $prevstyle);
  13402. $this->SetTextColorArray($prevcolor);
  13403. return $ret;
  13404. }
  13405. /**
  13406. * 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.
  13407. * @param $hcolor (string) HTML color.
  13408. * @param $defcol (array) Color to return in case of error.
  13409. * @return array RGB or CMYK color, or false in case of error.
  13410. * @public
  13411. */
  13412. public function convertHTMLColorToDec($hcolor='#FFFFFF', $defcol=array('R'=>128,'G'=>128,'B'=>128)) {
  13413. $color = preg_replace('/[\s]*/', '', $hcolor); // remove extra spaces
  13414. $color = strtolower($color);
  13415. // check for javascript color array syntax
  13416. if (strpos($color, '[') !== false) {
  13417. if (preg_match('/[\[][\"\'](t|g|rgb|cmyk)[\"\'][\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\]]/', $color, $m) > 0) {
  13418. $returncolor = array();
  13419. switch ($m[1]) {
  13420. case 'cmyk': {
  13421. // RGB
  13422. $returncolor['C'] = max(0, min(100, (floatval($m[2]) * 100)));
  13423. $returncolor['M'] = max(0, min(100, (floatval($m[3]) * 100)));
  13424. $returncolor['Y'] = max(0, min(100, (floatval($m[4]) * 100)));
  13425. $returncolor['K'] = max(0, min(100, (floatval($m[5]) * 100)));
  13426. break;
  13427. }
  13428. case 'rgb': {
  13429. // RGB
  13430. $returncolor['R'] = max(0, min(255, (floatval($m[2]) * 255)));
  13431. $returncolor['G'] = max(0, min(255, (floatval($m[3]) * 255)));
  13432. $returncolor['B'] = max(0, min(255, (floatval($m[4]) * 255)));
  13433. break;
  13434. }
  13435. case 'g': {
  13436. // grayscale
  13437. $returncolor['G'] = max(0, min(255, (floatval($m[2]) * 255)));
  13438. break;
  13439. }
  13440. case 't':
  13441. default: {
  13442. // transparent (empty array)
  13443. break;
  13444. }
  13445. }
  13446. return $returncolor;
  13447. }
  13448. } elseif (($dotpos = strpos($color, '.')) !== false) {
  13449. // remove class parent (i.e.: color.red)
  13450. $color = substr($color, ($dotpos + 1));
  13451. if ($color == 'transparent') {
  13452. // transparent (empty array)
  13453. return array();
  13454. }
  13455. }
  13456. if (strlen($color) == 0) {
  13457. return $defcol;
  13458. }
  13459. // RGB ARRAY
  13460. if (substr($color, 0, 3) == 'rgb') {
  13461. $codes = substr($color, 4);
  13462. $codes = str_replace(')', '', $codes);
  13463. $returncolor = explode(',', $codes);
  13464. foreach ($returncolor as $key => $val) {
  13465. if (strpos($val, '%') > 0) {
  13466. // percentage
  13467. $returncolor[$key] = (255 * intval($val) / 100);
  13468. } else {
  13469. $returncolor[$key] = intval($val);
  13470. }
  13471. // normalize value
  13472. $returncolor[$key] = max(0, min(255, $returncolor[$key]));
  13473. }
  13474. return $returncolor;
  13475. }
  13476. // CMYK ARRAY
  13477. if (substr($color, 0, 4) == 'cmyk') {
  13478. $codes = substr($color, 5);
  13479. $codes = str_replace(')', '', $codes);
  13480. $returncolor = explode(',', $codes);
  13481. foreach ($returncolor as $key => $val) {
  13482. if (strpos($val, '%') !== false) {
  13483. // percentage
  13484. $returncolor[$key] = (100 * intval($val) / 100);
  13485. } else {
  13486. $returncolor[$key] = intval($val);
  13487. }
  13488. // normalize value
  13489. $returncolor[$key] = max(0, min(100, $returncolor[$key]));
  13490. }
  13491. return $returncolor;
  13492. }
  13493. if ($color{0} != '#') {
  13494. // COLOR NAME
  13495. if (isset($this->webcolor[$color])) {
  13496. // web color
  13497. $color_code = $this->webcolor[$color];
  13498. } else {
  13499. // spot color
  13500. $returncolor = $this->getSpotColor($color);
  13501. if ($returncolor === false) {
  13502. $returncolor = $defcol;
  13503. }
  13504. return $returncolor;
  13505. }
  13506. } else {
  13507. $color_code = substr($color, 1);
  13508. }
  13509. // HEXADECIMAL REPRESENTATION
  13510. switch (strlen($color_code)) {
  13511. case 3: {
  13512. // 3-digit RGB hexadecimal representation
  13513. $r = substr($color_code, 0, 1);
  13514. $g = substr($color_code, 1, 1);
  13515. $b = substr($color_code, 2, 1);
  13516. $returncolor = array();
  13517. $returncolor['R'] = max(0, min(255, hexdec($r.$r)));
  13518. $returncolor['G'] = max(0, min(255, hexdec($g.$g)));
  13519. $returncolor['B'] = max(0, min(255, hexdec($b.$b)));
  13520. break;
  13521. }
  13522. case 6: {
  13523. // 6-digit RGB hexadecimal representation
  13524. $returncolor = array();
  13525. $returncolor['R'] = max(0, min(255, hexdec(substr($color_code, 0, 2))));
  13526. $returncolor['G'] = max(0, min(255, hexdec(substr($color_code, 2, 2))));
  13527. $returncolor['B'] = max(0, min(255, hexdec(substr($color_code, 4, 2))));
  13528. break;
  13529. }
  13530. case 8: {
  13531. // 8-digit CMYK hexadecimal representation
  13532. $returncolor = array();
  13533. $returncolor['C'] = max(0, min(100, round(hexdec(substr($color_code, 0, 2)) / 2.55)));
  13534. $returncolor['M'] = max(0, min(100, round(hexdec(substr($color_code, 2, 2)) / 2.55)));
  13535. $returncolor['Y'] = max(0, min(100, round(hexdec(substr($color_code, 4, 2)) / 2.55)));
  13536. $returncolor['K'] = max(0, min(100, round(hexdec(substr($color_code, 6, 2)) / 2.55)));
  13537. break;
  13538. }
  13539. default: {
  13540. $returncolor = $defcol;
  13541. break;
  13542. }
  13543. }
  13544. return $returncolor;
  13545. }
  13546. /**
  13547. * Converts pixels to User's Units.
  13548. * @param $px (int) pixels
  13549. * @return float value in user's unit
  13550. * @public
  13551. * @see setImageScale(), getImageScale()
  13552. */
  13553. public function pixelsToUnits($px) {
  13554. return ($px / ($this->imgscale * $this->k));
  13555. }
  13556. /**
  13557. * Reverse function for htmlentities.
  13558. * Convert entities in UTF-8.
  13559. * @param $text_to_convert (string) Text to convert.
  13560. * @return string converted text string
  13561. * @public
  13562. */
  13563. public function unhtmlentities($text_to_convert) {
  13564. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  13565. }
  13566. // ENCRYPTION METHODS ----------------------------------
  13567. /**
  13568. * Returns a string containing random data to be used as a seed for encryption methods.
  13569. * @param $seed (string) starting seed value
  13570. * @return string containing random data
  13571. * @author Nicola Asuni
  13572. * @since 5.9.006 (2010-10-19)
  13573. * @protected
  13574. */
  13575. protected function getRandomSeed($seed='') {
  13576. $seed .= microtime();
  13577. if (function_exists('openssl_random_pseudo_bytes') AND (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) {
  13578. // this is not used on windows systems because it is very slow for a know bug
  13579. $seed .= openssl_random_pseudo_bytes(512);
  13580. } else {
  13581. for ($i = 0; $i < 23; ++$i) {
  13582. $seed .= uniqid('', true);
  13583. }
  13584. }
  13585. $seed .= uniqid('', true);
  13586. $seed .= rand();
  13587. $seed .= getmypid();
  13588. $seed .= __FILE__;
  13589. $seed .= $this->bufferlen;
  13590. if (isset($_SERVER['REMOTE_ADDR'])) {
  13591. $seed .= $_SERVER['REMOTE_ADDR'];
  13592. }
  13593. if (isset($_SERVER['HTTP_USER_AGENT'])) {
  13594. $seed .= $_SERVER['HTTP_USER_AGENT'];
  13595. }
  13596. if (isset($_SERVER['HTTP_ACCEPT'])) {
  13597. $seed .= $_SERVER['HTTP_ACCEPT'];
  13598. }
  13599. if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
  13600. $seed .= $_SERVER['HTTP_ACCEPT_ENCODING'];
  13601. }
  13602. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  13603. $seed .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  13604. }
  13605. if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
  13606. $seed .= $_SERVER['HTTP_ACCEPT_CHARSET'];
  13607. }
  13608. $seed .= rand();
  13609. $seed .= uniqid('', true);
  13610. $seed .= microtime();
  13611. return $seed;
  13612. }
  13613. /**
  13614. * Compute encryption key depending on object number where the encrypted data is stored.
  13615. * This is used for all strings and streams without crypt filter specifier.
  13616. * @param $n (int) object number
  13617. * @return int object key
  13618. * @protected
  13619. * @author Nicola Asuni
  13620. * @since 2.0.000 (2008-01-02)
  13621. */
  13622. protected function _objectkey($n) {
  13623. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  13624. if ($this->encryptdata['mode'] == 2) { // AES-128
  13625. // AES padding
  13626. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  13627. }
  13628. $objkey = substr($this->_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  13629. $objkey = substr($objkey, 0, 16);
  13630. return $objkey;
  13631. }
  13632. /**
  13633. * Encrypt the input string.
  13634. * @param $n (int) object number
  13635. * @param $s (string) data string to encrypt
  13636. * @return encrypted string
  13637. * @protected
  13638. * @author Nicola Asuni
  13639. * @since 5.0.005 (2010-05-11)
  13640. */
  13641. protected function _encrypt_data($n, $s) {
  13642. if (!$this->encrypted) {
  13643. return $s;
  13644. }
  13645. switch ($this->encryptdata['mode']) {
  13646. case 0: // RC4-40
  13647. case 1: { // RC4-128
  13648. $s = $this->_RC4($this->_objectkey($n), $s);
  13649. break;
  13650. }
  13651. case 2: { // AES-128
  13652. $s = $this->_AES($this->_objectkey($n), $s);
  13653. break;
  13654. }
  13655. case 3: { // AES-256
  13656. $s = $this->_AES($this->encryptdata['key'], $s);
  13657. break;
  13658. }
  13659. }
  13660. return $s;
  13661. }
  13662. /**
  13663. * Put encryption on PDF document.
  13664. * @protected
  13665. * @author Nicola Asuni
  13666. * @since 2.0.000 (2008-01-02)
  13667. */
  13668. protected function _putencryption() {
  13669. if (!$this->encrypted) {
  13670. return;
  13671. }
  13672. $this->encryptdata['objid'] = $this->_newobj();
  13673. $out = '<<';
  13674. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  13675. $this->encryptdata['Filter'] = 'Standard';
  13676. }
  13677. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  13678. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  13679. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  13680. }
  13681. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  13682. $this->encryptdata['V'] = 1;
  13683. }
  13684. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  13685. $out .= ' /V '.$this->encryptdata['V'];
  13686. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  13687. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  13688. $out .= ' /Length '.$this->encryptdata['Length'];
  13689. } else {
  13690. $out .= ' /Length 40';
  13691. }
  13692. if ($this->encryptdata['V'] >= 4) {
  13693. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  13694. $this->encryptdata['StmF'] = 'Identity';
  13695. }
  13696. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  13697. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  13698. $this->encryptdata['StrF'] = 'Identity';
  13699. }
  13700. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  13701. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  13702. $out .= ' /CF <<';
  13703. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  13704. $out .= ' /Type /CryptFilter';
  13705. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  13706. // The method used
  13707. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  13708. if ($this->encryptdata['pubkey']) {
  13709. $out .= ' /Recipients [';
  13710. foreach ($this->encryptdata['Recipients'] as $rec) {
  13711. $out .= ' <'.$rec.'>';
  13712. }
  13713. $out .= ' ]';
  13714. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  13715. $out .= ' /EncryptMetadata false';
  13716. } else {
  13717. $out .= ' /EncryptMetadata true';
  13718. }
  13719. }
  13720. } else {
  13721. $out .= ' /CFM /None';
  13722. }
  13723. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  13724. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  13725. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  13726. } else {
  13727. $out .= ' /AuthEvent /DocOpen';
  13728. }
  13729. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  13730. // The bit length of the encryption key.
  13731. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  13732. }
  13733. $out .= ' >> >>';
  13734. }
  13735. // The name of the crypt filter that shall be used by default when decrypting streams.
  13736. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  13737. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  13738. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  13739. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  13740. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  13741. $out .= ' /EFF /'.$this->encryptdata[''];
  13742. }
  13743. }
  13744. // Additional encryption dictionary entries for the standard security handler
  13745. if ($this->encryptdata['pubkey']) {
  13746. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  13747. $out .= ' /Recipients [';
  13748. foreach ($this->encryptdata['Recipients'] as $rec) {
  13749. $out .= ' <'.$rec.'>';
  13750. }
  13751. $out .= ' ]';
  13752. }
  13753. } else {
  13754. $out .= ' /R';
  13755. if ($this->encryptdata['V'] == 5) { // AES-256
  13756. $out .= ' 5';
  13757. $out .= ' /OE ('.$this->_escape($this->encryptdata['OE']).')';
  13758. $out .= ' /UE ('.$this->_escape($this->encryptdata['UE']).')';
  13759. $out .= ' /Perms ('.$this->_escape($this->encryptdata['perms']).')';
  13760. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  13761. $out .= ' 4';
  13762. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  13763. $out .= ' 2';
  13764. } else { // RC-128
  13765. $out .= ' 3';
  13766. }
  13767. $out .= ' /O ('.$this->_escape($this->encryptdata['O']).')';
  13768. $out .= ' /U ('.$this->_escape($this->encryptdata['U']).')';
  13769. $out .= ' /P '.$this->encryptdata['P'];
  13770. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  13771. $out .= ' /EncryptMetadata false';
  13772. } else {
  13773. $out .= ' /EncryptMetadata true';
  13774. }
  13775. }
  13776. $out .= ' >>';
  13777. $out .= "\n".'endobj';
  13778. $this->_out($out);
  13779. }
  13780. /**
  13781. * Returns the input text encrypted using RC4 algorithm and the specified key.
  13782. * RC4 is the standard encryption algorithm used in PDF format
  13783. * @param $key (string) encryption key
  13784. * @param $text (String) input text to be encrypted
  13785. * @return String encrypted text
  13786. * @protected
  13787. * @since 2.0.000 (2008-01-02)
  13788. * @author Klemen Vodopivec, Nicola Asuni
  13789. */
  13790. protected function _RC4($key, $text) {
  13791. if (function_exists('mcrypt_decrypt') AND ($out = @mcrypt_decrypt(MCRYPT_ARCFOUR, $key, $text, MCRYPT_MODE_STREAM, ''))) {
  13792. // try to use mcrypt function if exist
  13793. return $out;
  13794. }
  13795. if ($this->last_enc_key != $key) {
  13796. $k = str_repeat($key, ((256 / strlen($key)) + 1));
  13797. $rc4 = range(0, 255);
  13798. $j = 0;
  13799. for ($i = 0; $i < 256; ++$i) {
  13800. $t = $rc4[$i];
  13801. $j = ($j + $t + ord($k[$i])) % 256;
  13802. $rc4[$i] = $rc4[$j];
  13803. $rc4[$j] = $t;
  13804. }
  13805. $this->last_enc_key = $key;
  13806. $this->last_enc_key_c = $rc4;
  13807. } else {
  13808. $rc4 = $this->last_enc_key_c;
  13809. }
  13810. $len = strlen($text);
  13811. $a = 0;
  13812. $b = 0;
  13813. $out = '';
  13814. for ($i = 0; $i < $len; ++$i) {
  13815. $a = ($a + 1) % 256;
  13816. $t = $rc4[$a];
  13817. $b = ($b + $t) % 256;
  13818. $rc4[$a] = $rc4[$b];
  13819. $rc4[$b] = $t;
  13820. $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
  13821. $out .= chr(ord($text[$i]) ^ $k);
  13822. }
  13823. return $out;
  13824. }
  13825. /**
  13826. * Returns the input text exrypted using AES algorithm and the specified key.
  13827. * This method requires mcrypt.
  13828. * @param $key (string) encryption key
  13829. * @param $text (String) input text to be encrypted
  13830. * @return String encrypted text
  13831. * @protected
  13832. * @author Nicola Asuni
  13833. * @since 5.0.005 (2010-05-11)
  13834. */
  13835. protected function _AES($key, $text) {
  13836. // padding (RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0)
  13837. $padding = 16 - (strlen($text) % 16);
  13838. $text .= str_repeat(chr($padding), $padding);
  13839. $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
  13840. $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
  13841. $text = $iv.$text;
  13842. return $text;
  13843. }
  13844. /**
  13845. * Encrypts a string using MD5 and returns it's value as a binary string.
  13846. * @param $str (string) input string
  13847. * @return String MD5 encrypted binary string
  13848. * @protected
  13849. * @since 2.0.000 (2008-01-02)
  13850. * @author Klemen Vodopivec
  13851. */
  13852. protected function _md5_16($str) {
  13853. return pack('H*', md5($str));
  13854. }
  13855. /**
  13856. * Compute U value (used for encryption)
  13857. * @return string U value
  13858. * @protected
  13859. * @since 2.0.000 (2008-01-02)
  13860. * @author Nicola Asuni
  13861. */
  13862. protected function _Uvalue() {
  13863. if ($this->encryptdata['mode'] == 0) { // RC4-40
  13864. return $this->_RC4($this->encryptdata['key'], $this->enc_padding);
  13865. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  13866. $tmp = $this->_md5_16($this->enc_padding.$this->encryptdata['fileid']);
  13867. $enc = $this->_RC4($this->encryptdata['key'], $tmp);
  13868. $len = strlen($tmp);
  13869. for ($i = 1; $i <= 19; ++$i) {
  13870. $ek = '';
  13871. for ($j = 0; $j < $len; ++$j) {
  13872. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  13873. }
  13874. $enc = $this->_RC4($ek, $enc);
  13875. }
  13876. $enc .= str_repeat("\x00", 16);
  13877. return substr($enc, 0, 32);
  13878. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  13879. $seed = $this->_md5_16($this->getRandomSeed());
  13880. // User Validation Salt
  13881. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  13882. // User Key Salt
  13883. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  13884. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  13885. }
  13886. }
  13887. /**
  13888. * Compute UE value (used for encryption)
  13889. * @return string UE value
  13890. * @protected
  13891. * @since 5.9.006 (2010-10-19)
  13892. * @author Nicola Asuni
  13893. */
  13894. protected function _UEvalue() {
  13895. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  13896. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
  13897. return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashkey, $this->encryptdata['key'], MCRYPT_MODE_CBC, $iv);
  13898. }
  13899. /**
  13900. * Compute O value (used for encryption)
  13901. * @return string O value
  13902. * @protected
  13903. * @since 2.0.000 (2008-01-02)
  13904. * @author Nicola Asuni
  13905. */
  13906. protected function _Ovalue() {
  13907. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  13908. $tmp = $this->_md5_16($this->encryptdata['owner_password']);
  13909. if ($this->encryptdata['mode'] > 0) {
  13910. for ($i = 0; $i < 50; ++$i) {
  13911. $tmp = $this->_md5_16($tmp);
  13912. }
  13913. }
  13914. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  13915. $enc = $this->_RC4($owner_key, $this->encryptdata['user_password']);
  13916. if ($this->encryptdata['mode'] > 0) {
  13917. $len = strlen($owner_key);
  13918. for ($i = 1; $i <= 19; ++$i) {
  13919. $ek = '';
  13920. for ($j = 0; $j < $len; ++$j) {
  13921. $ek .= chr(ord($owner_key[$j]) ^ $i);
  13922. }
  13923. $enc = $this->_RC4($ek, $enc);
  13924. }
  13925. }
  13926. return $enc;
  13927. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  13928. $seed = $this->_md5_16($this->getRandomSeed());
  13929. // Owner Validation Salt
  13930. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  13931. // Owner Key Salt
  13932. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  13933. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  13934. }
  13935. }
  13936. /**
  13937. * Compute OE value (used for encryption)
  13938. * @return string OE value
  13939. * @protected
  13940. * @since 5.9.006 (2010-10-19)
  13941. * @author Nicola Asuni
  13942. */
  13943. protected function _OEvalue() {
  13944. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  13945. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
  13946. return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashkey, $this->encryptdata['key'], MCRYPT_MODE_CBC, $iv);
  13947. }
  13948. /**
  13949. * Convert password for AES-256 encryption mode
  13950. * @param $password (string) password
  13951. * @return string password
  13952. * @protected
  13953. * @since 5.9.006 (2010-10-19)
  13954. * @author Nicola Asuni
  13955. */
  13956. protected function _fixAES256Password($password) {
  13957. $psw = ''; // password to be returned
  13958. $psw_array = $this->utf8Bidi($this->UTF8StringToArray($password), $password, $this->rtl);
  13959. foreach ($psw_array as $c) {
  13960. $psw .= $this->unichr($c);
  13961. }
  13962. return substr($psw, 0, 127);
  13963. }
  13964. /**
  13965. * Compute encryption key
  13966. * @protected
  13967. * @since 2.0.000 (2008-01-02)
  13968. * @author Nicola Asuni
  13969. */
  13970. protected function _generateencryptionkey() {
  13971. $keybytelen = ($this->encryptdata['Length'] / 8);
  13972. if (!$this->encryptdata['pubkey']) { // standard mode
  13973. if ($this->encryptdata['mode'] == 3) { // AES-256
  13974. // generate 256 bit random key
  13975. $this->encryptdata['key'] = substr(hash('sha256', $this->getRandomSeed(), true), 0, $keybytelen);
  13976. // truncate passwords
  13977. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  13978. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  13979. // Compute U value
  13980. $this->encryptdata['U'] = $this->_Uvalue();
  13981. // Compute UE value
  13982. $this->encryptdata['UE'] = $this->_UEvalue();
  13983. // Compute O value
  13984. $this->encryptdata['O'] = $this->_Ovalue();
  13985. // Compute OE value
  13986. $this->encryptdata['OE'] = $this->_OEvalue();
  13987. // Compute P value
  13988. $this->encryptdata['P'] = $this->encryptdata['protection'];
  13989. // Computing the encryption dictionary's Perms (permissions) value
  13990. $perms = $this->getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  13991. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  13992. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  13993. $perms .= 'F';
  13994. } else {
  13995. $perms .= 'T';
  13996. }
  13997. $perms .= 'adb'; // bytes 9-11
  13998. $perms .= 'nick'; // bytes 12-15
  13999. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
  14000. $this->encryptdata['perms'] = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->encryptdata['key'], $perms, MCRYPT_MODE_ECB, $iv);
  14001. } else { // RC4-40, RC4-128, AES-128
  14002. // Pad passwords
  14003. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].$this->enc_padding, 0, 32);
  14004. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].$this->enc_padding, 0, 32);
  14005. // Compute O value
  14006. $this->encryptdata['O'] = $this->_Ovalue();
  14007. // get default permissions (reverse byte order)
  14008. $permissions = $this->getEncPermissionsString($this->encryptdata['protection']);
  14009. // Compute encryption key
  14010. $tmp = $this->_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  14011. if ($this->encryptdata['mode'] > 0) {
  14012. for ($i = 0; $i < 50; ++$i) {
  14013. $tmp = $this->_md5_16(substr($tmp, 0, $keybytelen));
  14014. }
  14015. }
  14016. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  14017. // Compute U value
  14018. $this->encryptdata['U'] = $this->_Uvalue();
  14019. // Compute P value
  14020. $this->encryptdata['P'] = $this->encryptdata['protection'];
  14021. }
  14022. } else { // Public-Key mode
  14023. // random 20-byte seed
  14024. $seed = sha1($this->getRandomSeed(), true);
  14025. $recipient_bytes = '';
  14026. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  14027. // for each public certificate
  14028. if (isset($pubkey['p'])) {
  14029. $pkprotection = $this->getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  14030. } else {
  14031. $pkprotection = $this->encryptdata['protection'];
  14032. }
  14033. // get default permissions (reverse byte order)
  14034. $pkpermissions = $this->getEncPermissionsString($pkprotection);
  14035. // envelope data
  14036. $envelope = $seed.$pkpermissions;
  14037. // write the envelope data to a temporary file
  14038. $tempkeyfile = tempnam(K_PATH_CACHE, 'tmpkey_');
  14039. $f = fopen($tempkeyfile, 'wb');
  14040. if (!$f) {
  14041. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  14042. }
  14043. $envelope_length = strlen($envelope);
  14044. fwrite($f, $envelope, $envelope_length);
  14045. fclose($f);
  14046. $tempencfile = tempnam(K_PATH_CACHE, 'tmpenc_');
  14047. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  14048. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  14049. }
  14050. unlink($tempkeyfile);
  14051. // read encryption signature
  14052. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  14053. unlink($tempencfile);
  14054. // extract signature
  14055. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  14056. $tmparr = explode("\n\n", $signature);
  14057. $signature = trim($tmparr[1]);
  14058. unset($tmparr);
  14059. // decode signature
  14060. $signature = base64_decode($signature);
  14061. // convert signature to hex
  14062. $hexsignature = current(unpack('H*', $signature));
  14063. // store signature on recipients array
  14064. $this->encryptdata['Recipients'][] = $hexsignature;
  14065. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  14066. $recipient_bytes .= $signature;
  14067. }
  14068. // calculate encryption key
  14069. if ($this->encryptdata['mode'] == 3) { // AES-256
  14070. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  14071. } else { // RC4-40, RC4-128, AES-128
  14072. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  14073. }
  14074. }
  14075. }
  14076. /**
  14077. * Return the premission code used on encryption (P value).
  14078. * @param $permissions (Array) the set of permissions (specify the ones you want to block).
  14079. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  14080. * @protected
  14081. * @since 5.0.005 (2010-05-12)
  14082. * @author Nicola Asuni
  14083. */
  14084. protected function getUserPermissionCode($permissions, $mode=0) {
  14085. $options = array(
  14086. 'owner' => 2, // bit 2 -- inverted logic: cleared by default
  14087. 'print' => 4, // bit 3
  14088. 'modify' => 8, // bit 4
  14089. 'copy' => 16, // bit 5
  14090. 'annot-forms' => 32, // bit 6
  14091. 'fill-forms' => 256, // bit 9
  14092. 'extract' => 512, // bit 10
  14093. 'assemble' => 1024,// bit 11
  14094. 'print-high' => 2048 // bit 12
  14095. );
  14096. $protection = 2147422012; // 32 bit: (01111111 11111111 00001111 00111100)
  14097. foreach ($permissions as $permission) {
  14098. if (!isset($options[$permission])) {
  14099. $this->Error('Incorrect permission: '.$permission);
  14100. }
  14101. if (($mode > 0) OR ($options[$permission] <= 32)) {
  14102. // set only valid permissions
  14103. if ($options[$permission] == 2) {
  14104. // the logic for bit 2 is inverted (cleared by default)
  14105. $protection += $options[$permission];
  14106. } else {
  14107. $protection -= $options[$permission];
  14108. }
  14109. }
  14110. }
  14111. return $protection;
  14112. }
  14113. /**
  14114. * Set document protection
  14115. * Remark: the protection against modification is for people who have the full Acrobat product.
  14116. * 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.
  14117. * 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.
  14118. * @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>
  14119. * @param $user_pass (String) user password. Empty by default.
  14120. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  14121. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  14122. * @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')))
  14123. * @public
  14124. * @since 2.0.000 (2008-01-02)
  14125. * @author Nicola Asuni
  14126. */
  14127. 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) {
  14128. if ($this->pdfa_mode) {
  14129. // encryption is not allowed in PDF/A mode
  14130. return;
  14131. }
  14132. $this->encryptdata['protection'] = $this->getUserPermissionCode($permissions, $mode);
  14133. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  14134. // public-key mode
  14135. $this->encryptdata['pubkeys'] = $pubkeys;
  14136. if ($mode == 0) {
  14137. // public-Key Security requires at least 128 bit
  14138. $mode = 1;
  14139. }
  14140. if (!function_exists('openssl_pkcs7_encrypt')) {
  14141. $this->Error('Public-Key Security requires openssl library.');
  14142. }
  14143. // Set Public-Key filter (availabe are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  14144. $this->encryptdata['pubkey'] = true;
  14145. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  14146. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  14147. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  14148. } else {
  14149. // standard mode (password mode)
  14150. $this->encryptdata['pubkey'] = false;
  14151. $this->encryptdata['Filter'] = 'Standard';
  14152. $this->encryptdata['StmF'] = 'StdCF';
  14153. $this->encryptdata['StrF'] = 'StdCF';
  14154. }
  14155. if ($mode > 1) { // AES
  14156. if (!extension_loaded('mcrypt')) {
  14157. $this->Error('AES encryption requires mcrypt library (http://www.php.net/manual/en/mcrypt.requirements.php).');
  14158. }
  14159. if (mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  14160. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  14161. }
  14162. if (($mode == 3) AND !function_exists('hash')) {
  14163. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  14164. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  14165. }
  14166. }
  14167. if ($owner_pass === null) {
  14168. $owner_pass = md5($this->getRandomSeed());
  14169. }
  14170. $this->encryptdata['user_password'] = $user_pass;
  14171. $this->encryptdata['owner_password'] = $owner_pass;
  14172. $this->encryptdata['mode'] = $mode;
  14173. switch ($mode) {
  14174. case 0: { // RC4 40 bit
  14175. $this->encryptdata['V'] = 1;
  14176. $this->encryptdata['Length'] = 40;
  14177. $this->encryptdata['CF']['CFM'] = 'V2';
  14178. break;
  14179. }
  14180. case 1: { // RC4 128 bit
  14181. $this->encryptdata['V'] = 2;
  14182. $this->encryptdata['Length'] = 128;
  14183. $this->encryptdata['CF']['CFM'] = 'V2';
  14184. if ($this->encryptdata['pubkey']) {
  14185. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  14186. $this->encryptdata['Recipients'] = array();
  14187. }
  14188. break;
  14189. }
  14190. case 2: { // AES 128 bit
  14191. $this->encryptdata['V'] = 4;
  14192. $this->encryptdata['Length'] = 128;
  14193. $this->encryptdata['CF']['CFM'] = 'AESV2';
  14194. $this->encryptdata['CF']['Length'] = 128;
  14195. if ($this->encryptdata['pubkey']) {
  14196. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  14197. $this->encryptdata['Recipients'] = array();
  14198. }
  14199. break;
  14200. }
  14201. case 3: { // AES 256 bit
  14202. $this->encryptdata['V'] = 5;
  14203. $this->encryptdata['Length'] = 256;
  14204. $this->encryptdata['CF']['CFM'] = 'AESV3';
  14205. $this->encryptdata['CF']['Length'] = 256;
  14206. if ($this->encryptdata['pubkey']) {
  14207. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  14208. $this->encryptdata['Recipients'] = array();
  14209. }
  14210. break;
  14211. }
  14212. }
  14213. $this->encrypted = true;
  14214. $this->encryptdata['fileid'] = $this->convertHexStringToString($this->file_id);
  14215. $this->_generateencryptionkey();
  14216. }
  14217. /**
  14218. * Convert hexadecimal string to string
  14219. * @param $bs (string) byte-string to convert
  14220. * @return String
  14221. * @protected
  14222. * @since 5.0.005 (2010-05-12)
  14223. * @author Nicola Asuni
  14224. */
  14225. protected function convertHexStringToString($bs) {
  14226. $string = ''; // string to be returned
  14227. $bslength = strlen($bs);
  14228. if (($bslength % 2) != 0) {
  14229. // padding
  14230. $bs .= '0';
  14231. ++$bslength;
  14232. }
  14233. for ($i = 0; $i < $bslength; $i += 2) {
  14234. $string .= chr(hexdec($bs[$i].$bs[($i + 1)]));
  14235. }
  14236. return $string;
  14237. }
  14238. /**
  14239. * Convert string to hexadecimal string (byte string)
  14240. * @param $s (string) string to convert
  14241. * @return byte string
  14242. * @protected
  14243. * @since 5.0.010 (2010-05-17)
  14244. * @author Nicola Asuni
  14245. */
  14246. protected function convertStringToHexString($s) {
  14247. $bs = '';
  14248. $chars = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
  14249. foreach ($chars as $c) {
  14250. $bs .= sprintf('%02s', dechex(ord($c)));
  14251. }
  14252. return $bs;
  14253. }
  14254. /**
  14255. * Convert encryption P value to a string of bytes, low-order byte first.
  14256. * @param $protection (string) 32bit encryption permission value (P value)
  14257. * @return String
  14258. * @protected
  14259. * @since 5.0.005 (2010-05-12)
  14260. * @author Nicola Asuni
  14261. */
  14262. protected function getEncPermissionsString($protection) {
  14263. $binprot = sprintf('%032b', $protection);
  14264. $str = chr(bindec(substr($binprot, 24, 8)));
  14265. $str .= chr(bindec(substr($binprot, 16, 8)));
  14266. $str .= chr(bindec(substr($binprot, 8, 8)));
  14267. $str .= chr(bindec(substr($binprot, 0, 8)));
  14268. return $str;
  14269. }
  14270. // END OF ENCRYPTION FUNCTIONS -------------------------
  14271. // START TRANSFORMATIONS SECTION -----------------------
  14272. /**
  14273. * Starts a 2D tranformation saving current graphic state.
  14274. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  14275. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  14276. * @public
  14277. * @since 2.1.000 (2008-01-07)
  14278. * @see StartTransform(), StopTransform()
  14279. */
  14280. public function StartTransform() {
  14281. $this->_out('q');
  14282. if ($this->inxobj) {
  14283. // we are inside an XObject template
  14284. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  14285. } else {
  14286. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  14287. }
  14288. ++$this->transfmatrix_key;
  14289. $this->transfmatrix[$this->transfmatrix_key] = array();
  14290. }
  14291. /**
  14292. * Stops a 2D tranformation restoring previous graphic state.
  14293. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  14294. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  14295. * @public
  14296. * @since 2.1.000 (2008-01-07)
  14297. * @see StartTransform(), StopTransform()
  14298. */
  14299. public function StopTransform() {
  14300. $this->_out('Q');
  14301. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  14302. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  14303. --$this->transfmatrix_key;
  14304. }
  14305. if ($this->inxobj) {
  14306. // we are inside an XObject template
  14307. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  14308. } else {
  14309. array_pop($this->transfmrk[$this->page]);
  14310. }
  14311. }
  14312. /**
  14313. * Horizontal Scaling.
  14314. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  14315. * @param $x (int) abscissa of the scaling center. Default is current x position
  14316. * @param $y (int) ordinate of the scaling center. Default is current y position
  14317. * @public
  14318. * @since 2.1.000 (2008-01-07)
  14319. * @see StartTransform(), StopTransform()
  14320. */
  14321. public function ScaleX($s_x, $x='', $y='') {
  14322. $this->Scale($s_x, 100, $x, $y);
  14323. }
  14324. /**
  14325. * Vertical Scaling.
  14326. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  14327. * @param $x (int) abscissa of the scaling center. Default is current x position
  14328. * @param $y (int) ordinate of the scaling center. Default is current y position
  14329. * @public
  14330. * @since 2.1.000 (2008-01-07)
  14331. * @see StartTransform(), StopTransform()
  14332. */
  14333. public function ScaleY($s_y, $x='', $y='') {
  14334. $this->Scale(100, $s_y, $x, $y);
  14335. }
  14336. /**
  14337. * Vertical and horizontal proportional Scaling.
  14338. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  14339. * @param $x (int) abscissa of the scaling center. Default is current x position
  14340. * @param $y (int) ordinate of the scaling center. Default is current y position
  14341. * @public
  14342. * @since 2.1.000 (2008-01-07)
  14343. * @see StartTransform(), StopTransform()
  14344. */
  14345. public function ScaleXY($s, $x='', $y='') {
  14346. $this->Scale($s, $s, $x, $y);
  14347. }
  14348. /**
  14349. * Vertical and horizontal non-proportional Scaling.
  14350. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  14351. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  14352. * @param $x (int) abscissa of the scaling center. Default is current x position
  14353. * @param $y (int) ordinate of the scaling center. Default is current y position
  14354. * @public
  14355. * @since 2.1.000 (2008-01-07)
  14356. * @see StartTransform(), StopTransform()
  14357. */
  14358. public function Scale($s_x, $s_y, $x='', $y='') {
  14359. if ($x === '') {
  14360. $x = $this->x;
  14361. }
  14362. if ($y === '') {
  14363. $y = $this->y;
  14364. }
  14365. if (($s_x == 0) OR ($s_y == 0)) {
  14366. $this->Error('Please do not use values equal to zero for scaling');
  14367. }
  14368. $y = ($this->h - $y) * $this->k;
  14369. $x *= $this->k;
  14370. //calculate elements of transformation matrix
  14371. $s_x /= 100;
  14372. $s_y /= 100;
  14373. $tm = array();
  14374. $tm[0] = $s_x;
  14375. $tm[1] = 0;
  14376. $tm[2] = 0;
  14377. $tm[3] = $s_y;
  14378. $tm[4] = $x * (1 - $s_x);
  14379. $tm[5] = $y * (1 - $s_y);
  14380. //scale the coordinate system
  14381. $this->Transform($tm);
  14382. }
  14383. /**
  14384. * Horizontal Mirroring.
  14385. * @param $x (int) abscissa of the point. Default is current x position
  14386. * @public
  14387. * @since 2.1.000 (2008-01-07)
  14388. * @see StartTransform(), StopTransform()
  14389. */
  14390. public function MirrorH($x='') {
  14391. $this->Scale(-100, 100, $x);
  14392. }
  14393. /**
  14394. * Verical Mirroring.
  14395. * @param $y (int) ordinate of the point. Default is current y position
  14396. * @public
  14397. * @since 2.1.000 (2008-01-07)
  14398. * @see StartTransform(), StopTransform()
  14399. */
  14400. public function MirrorV($y='') {
  14401. $this->Scale(100, -100, '', $y);
  14402. }
  14403. /**
  14404. * Point reflection mirroring.
  14405. * @param $x (int) abscissa of the point. Default is current x position
  14406. * @param $y (int) ordinate of the point. Default is current y position
  14407. * @public
  14408. * @since 2.1.000 (2008-01-07)
  14409. * @see StartTransform(), StopTransform()
  14410. */
  14411. public function MirrorP($x='',$y='') {
  14412. $this->Scale(-100, -100, $x, $y);
  14413. }
  14414. /**
  14415. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  14416. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  14417. * @param $x (int) abscissa of the point. Default is current x position
  14418. * @param $y (int) ordinate of the point. Default is current y position
  14419. * @public
  14420. * @since 2.1.000 (2008-01-07)
  14421. * @see StartTransform(), StopTransform()
  14422. */
  14423. public function MirrorL($angle=0, $x='',$y='') {
  14424. $this->Scale(-100, 100, $x, $y);
  14425. $this->Rotate(-2*($angle-90), $x, $y);
  14426. }
  14427. /**
  14428. * Translate graphic object horizontally.
  14429. * @param $t_x (int) movement to the right (or left for RTL)
  14430. * @public
  14431. * @since 2.1.000 (2008-01-07)
  14432. * @see StartTransform(), StopTransform()
  14433. */
  14434. public function TranslateX($t_x) {
  14435. $this->Translate($t_x, 0);
  14436. }
  14437. /**
  14438. * Translate graphic object vertically.
  14439. * @param $t_y (int) movement to the bottom
  14440. * @public
  14441. * @since 2.1.000 (2008-01-07)
  14442. * @see StartTransform(), StopTransform()
  14443. */
  14444. public function TranslateY($t_y) {
  14445. $this->Translate(0, $t_y);
  14446. }
  14447. /**
  14448. * Translate graphic object horizontally and vertically.
  14449. * @param $t_x (int) movement to the right
  14450. * @param $t_y (int) movement to the bottom
  14451. * @public
  14452. * @since 2.1.000 (2008-01-07)
  14453. * @see StartTransform(), StopTransform()
  14454. */
  14455. public function Translate($t_x, $t_y) {
  14456. //calculate elements of transformation matrix
  14457. $tm = array();
  14458. $tm[0] = 1;
  14459. $tm[1] = 0;
  14460. $tm[2] = 0;
  14461. $tm[3] = 1;
  14462. $tm[4] = $t_x * $this->k;
  14463. $tm[5] = -$t_y * $this->k;
  14464. //translate the coordinate system
  14465. $this->Transform($tm);
  14466. }
  14467. /**
  14468. * Rotate object.
  14469. * @param $angle (float) angle in degrees for counter-clockwise rotation
  14470. * @param $x (int) abscissa of the rotation center. Default is current x position
  14471. * @param $y (int) ordinate of the rotation center. Default is current y position
  14472. * @public
  14473. * @since 2.1.000 (2008-01-07)
  14474. * @see StartTransform(), StopTransform()
  14475. */
  14476. public function Rotate($angle, $x='', $y='') {
  14477. if ($x === '') {
  14478. $x = $this->x;
  14479. }
  14480. if ($y === '') {
  14481. $y = $this->y;
  14482. }
  14483. $y = ($this->h - $y) * $this->k;
  14484. $x *= $this->k;
  14485. //calculate elements of transformation matrix
  14486. $tm = array();
  14487. $tm[0] = cos(deg2rad($angle));
  14488. $tm[1] = sin(deg2rad($angle));
  14489. $tm[2] = -$tm[1];
  14490. $tm[3] = $tm[0];
  14491. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  14492. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  14493. //rotate the coordinate system around ($x,$y)
  14494. $this->Transform($tm);
  14495. }
  14496. /**
  14497. * Skew horizontally.
  14498. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  14499. * @param $x (int) abscissa of the skewing center. default is current x position
  14500. * @param $y (int) ordinate of the skewing center. default is current y position
  14501. * @public
  14502. * @since 2.1.000 (2008-01-07)
  14503. * @see StartTransform(), StopTransform()
  14504. */
  14505. public function SkewX($angle_x, $x='', $y='') {
  14506. $this->Skew($angle_x, 0, $x, $y);
  14507. }
  14508. /**
  14509. * Skew vertically.
  14510. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  14511. * @param $x (int) abscissa of the skewing center. default is current x position
  14512. * @param $y (int) ordinate of the skewing center. default is current y position
  14513. * @public
  14514. * @since 2.1.000 (2008-01-07)
  14515. * @see StartTransform(), StopTransform()
  14516. */
  14517. public function SkewY($angle_y, $x='', $y='') {
  14518. $this->Skew(0, $angle_y, $x, $y);
  14519. }
  14520. /**
  14521. * Skew.
  14522. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  14523. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  14524. * @param $x (int) abscissa of the skewing center. default is current x position
  14525. * @param $y (int) ordinate of the skewing center. default is current y position
  14526. * @public
  14527. * @since 2.1.000 (2008-01-07)
  14528. * @see StartTransform(), StopTransform()
  14529. */
  14530. public function Skew($angle_x, $angle_y, $x='', $y='') {
  14531. if ($x === '') {
  14532. $x = $this->x;
  14533. }
  14534. if ($y === '') {
  14535. $y = $this->y;
  14536. }
  14537. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  14538. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  14539. }
  14540. $x *= $this->k;
  14541. $y = ($this->h - $y) * $this->k;
  14542. //calculate elements of transformation matrix
  14543. $tm = array();
  14544. $tm[0] = 1;
  14545. $tm[1] = tan(deg2rad($angle_y));
  14546. $tm[2] = tan(deg2rad($angle_x));
  14547. $tm[3] = 1;
  14548. $tm[4] = -$tm[2] * $y;
  14549. $tm[5] = -$tm[1] * $x;
  14550. //skew the coordinate system
  14551. $this->Transform($tm);
  14552. }
  14553. /**
  14554. * Apply graphic transformations.
  14555. * @param $tm (array) transformation matrix
  14556. * @protected
  14557. * @since 2.1.000 (2008-01-07)
  14558. * @see StartTransform(), StopTransform()
  14559. */
  14560. protected function Transform($tm) {
  14561. $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  14562. // add tranformation matrix
  14563. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  14564. // update transformation mark
  14565. if ($this->inxobj) {
  14566. // we are inside an XObject template
  14567. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  14568. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  14569. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  14570. }
  14571. } elseif (end($this->transfmrk[$this->page]) !== false) {
  14572. $key = key($this->transfmrk[$this->page]);
  14573. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  14574. }
  14575. }
  14576. // END TRANSFORMATIONS SECTION -------------------------
  14577. // START GRAPHIC FUNCTIONS SECTION ---------------------
  14578. // The following section is based on the code provided by David Hernandez Sanz
  14579. /**
  14580. * 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.
  14581. * @param $width (float) The width.
  14582. * @public
  14583. * @since 1.0
  14584. * @see Line(), Rect(), Cell(), MultiCell()
  14585. */
  14586. public function SetLineWidth($width) {
  14587. //Set line width
  14588. $this->LineWidth = $width;
  14589. $this->linestyleWidth = sprintf('%F w', ($width * $this->k));
  14590. if ($this->page > 0) {
  14591. $this->_out($this->linestyleWidth);
  14592. }
  14593. }
  14594. /**
  14595. * Returns the current the line width.
  14596. * @return int Line width
  14597. * @public
  14598. * @since 2.1.000 (2008-01-07)
  14599. * @see Line(), SetLineWidth()
  14600. */
  14601. public function GetLineWidth() {
  14602. return $this->LineWidth;
  14603. }
  14604. /**
  14605. * Set line style.
  14606. * @param $style (array) Line style. Array with keys among the following:
  14607. * <ul>
  14608. * <li>width (float): Width of the line in user units.</li>
  14609. * <li>cap (string): Type of cap to put on the line. Possible values are:
  14610. * butt, round, square. The difference between "square" and "butt" is that
  14611. * "square" projects a flat end past the end of the line.</li>
  14612. * <li>join (string): Type of join. Possible values are: miter, round,
  14613. * bevel.</li>
  14614. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  14615. * series of length values, which are the lengths of the on and off dashes.
  14616. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  14617. * 1 off, 2 on, 1 off, ...</li>
  14618. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  14619. * the point at which the pattern starts.</li>
  14620. * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
  14621. * </ul>
  14622. * @param $ret (boolean) if true do not send the command.
  14623. * @return string the PDF command
  14624. * @public
  14625. * @since 2.1.000 (2008-01-08)
  14626. */
  14627. public function SetLineStyle($style, $ret=false) {
  14628. $s = ''; // string to be returned
  14629. if (!is_array($style)) {
  14630. return;
  14631. }
  14632. if (isset($style['width'])) {
  14633. $this->LineWidth = $style['width'];
  14634. $this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
  14635. $s .= $this->linestyleWidth.' ';
  14636. }
  14637. if (isset($style['cap'])) {
  14638. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  14639. if (isset($ca[$style['cap']])) {
  14640. $this->linestyleCap = $ca[$style['cap']].' J';
  14641. $s .= $this->linestyleCap.' ';
  14642. }
  14643. }
  14644. if (isset($style['join'])) {
  14645. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  14646. if (isset($ja[$style['join']])) {
  14647. $this->linestyleJoin = $ja[$style['join']].' j';
  14648. $s .= $this->linestyleJoin.' ';
  14649. }
  14650. }
  14651. if (isset($style['dash'])) {
  14652. $dash_string = '';
  14653. if ($style['dash']) {
  14654. if (preg_match('/^.+,/', $style['dash']) > 0) {
  14655. $tab = explode(',', $style['dash']);
  14656. } else {
  14657. $tab = array($style['dash']);
  14658. }
  14659. $dash_string = '';
  14660. foreach ($tab as $i => $v) {
  14661. if ($i) {
  14662. $dash_string .= ' ';
  14663. }
  14664. $dash_string .= sprintf('%F', $v);
  14665. }
  14666. }
  14667. if (!isset($style['phase']) OR !$style['dash']) {
  14668. $style['phase'] = 0;
  14669. }
  14670. $this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
  14671. $s .= $this->linestyleDash.' ';
  14672. }
  14673. if (isset($style['color'])) {
  14674. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  14675. }
  14676. if (!$ret) {
  14677. $this->_out($s);
  14678. }
  14679. return $s;
  14680. }
  14681. /**
  14682. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  14683. * @param $x (float) Abscissa of point.
  14684. * @param $y (float) Ordinate of point.
  14685. * @protected
  14686. * @since 2.1.000 (2008-01-08)
  14687. */
  14688. protected function _outPoint($x, $y) {
  14689. $this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
  14690. }
  14691. /**
  14692. * Append a straight line segment from the current point to the point (x, y).
  14693. * The new current point shall be (x, y).
  14694. * @param $x (float) Abscissa of end point.
  14695. * @param $y (float) Ordinate of end point.
  14696. * @protected
  14697. * @since 2.1.000 (2008-01-08)
  14698. */
  14699. protected function _outLine($x, $y) {
  14700. $this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
  14701. }
  14702. /**
  14703. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  14704. * @param $x (float) Abscissa of upper-left corner.
  14705. * @param $y (float) Ordinate of upper-left corner.
  14706. * @param $w (float) Width.
  14707. * @param $h (float) Height.
  14708. * @param $op (string) options
  14709. * @protected
  14710. * @since 2.1.000 (2008-01-08)
  14711. */
  14712. protected function _outRect($x, $y, $w, $h, $op) {
  14713. $this->_out(sprintf('%F %F %F %F re %s', $x * $this->k, ($this->h - $y) * $this->k, $w * $this->k, -$h * $this->k, $op));
  14714. }
  14715. /**
  14716. * 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.
  14717. * The new current point shall be (x3, y3).
  14718. * @param $x1 (float) Abscissa of control point 1.
  14719. * @param $y1 (float) Ordinate of control point 1.
  14720. * @param $x2 (float) Abscissa of control point 2.
  14721. * @param $y2 (float) Ordinate of control point 2.
  14722. * @param $x3 (float) Abscissa of end point.
  14723. * @param $y3 (float) Ordinate of end point.
  14724. * @protected
  14725. * @since 2.1.000 (2008-01-08)
  14726. */
  14727. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  14728. $this->_out(sprintf('%F %F %F %F %F %F c', $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  14729. }
  14730. /**
  14731. * 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.
  14732. * The new current point shall be (x3, y3).
  14733. * @param $x2 (float) Abscissa of control point 2.
  14734. * @param $y2 (float) Ordinate of control point 2.
  14735. * @param $x3 (float) Abscissa of end point.
  14736. * @param $y3 (float) Ordinate of end point.
  14737. * @protected
  14738. * @since 4.9.019 (2010-04-26)
  14739. */
  14740. protected function _outCurveV($x2, $y2, $x3, $y3) {
  14741. $this->_out(sprintf('%F %F %F %F v', $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  14742. }
  14743. /**
  14744. * 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.
  14745. * The new current point shall be (x3, y3).
  14746. * @param $x1 (float) Abscissa of control point 1.
  14747. * @param $y1 (float) Ordinate of control point 1.
  14748. * @param $x3 (float) Abscissa of end point.
  14749. * @param $y3 (float) Ordinate of end point.
  14750. * @protected
  14751. * @since 2.1.000 (2008-01-08)
  14752. */
  14753. protected function _outCurveY($x1, $y1, $x3, $y3) {
  14754. $this->_out(sprintf('%F %F %F %F y', $x1 * $this->k, ($this->h - $y1) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  14755. }
  14756. /**
  14757. * Draws a line between two points.
  14758. * @param $x1 (float) Abscissa of first point.
  14759. * @param $y1 (float) Ordinate of first point.
  14760. * @param $x2 (float) Abscissa of second point.
  14761. * @param $y2 (float) Ordinate of second point.
  14762. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  14763. * @public
  14764. * @since 1.0
  14765. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  14766. */
  14767. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  14768. if (is_array($style)) {
  14769. $this->SetLineStyle($style);
  14770. }
  14771. $this->_outPoint($x1, $y1);
  14772. $this->_outLine($x2, $y2);
  14773. $this->_out('S');
  14774. }
  14775. /**
  14776. * Draws a rectangle.
  14777. * @param $x (float) Abscissa of upper-left corner.
  14778. * @param $y (float) Ordinate of upper-left corner.
  14779. * @param $w (float) Width.
  14780. * @param $h (float) Height.
  14781. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14782. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  14783. * <ul>
  14784. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  14785. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  14786. * </ul>
  14787. * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
  14788. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  14789. * @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).
  14790. * @public
  14791. * @since 1.0
  14792. * @see SetLineStyle()
  14793. */
  14794. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  14795. if (!(false === strpos($style, 'F')) AND !empty($fill_color)) {
  14796. $this->SetFillColorArray($fill_color);
  14797. }
  14798. $op = $this->getPathPaintOperator($style);
  14799. if ((!$border_style) OR (isset($border_style['all']))) {
  14800. if (isset($border_style['all']) AND $border_style['all']) {
  14801. $this->SetLineStyle($border_style['all']);
  14802. $border_style = array();
  14803. }
  14804. }
  14805. $this->_outRect($x, $y, $w, $h, $op);
  14806. if ($border_style) {
  14807. $border_style2 = array();
  14808. foreach ($border_style as $line => $value) {
  14809. $length = strlen($line);
  14810. for ($i = 0; $i < $length; ++$i) {
  14811. $border_style2[$line[$i]] = $value;
  14812. }
  14813. }
  14814. $border_style = $border_style2;
  14815. if (isset($border_style['L']) AND $border_style['L']) {
  14816. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  14817. }
  14818. if (isset($border_style['T']) AND $border_style['T']) {
  14819. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  14820. }
  14821. if (isset($border_style['R']) AND $border_style['R']) {
  14822. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  14823. }
  14824. if (isset($border_style['B']) AND $border_style['B']) {
  14825. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  14826. }
  14827. }
  14828. }
  14829. /**
  14830. * Draws a Bezier curve.
  14831. * The Bezier curve is a tangent to the line between the control points at
  14832. * either end of the curve.
  14833. * @param $x0 (float) Abscissa of start point.
  14834. * @param $y0 (float) Ordinate of start point.
  14835. * @param $x1 (float) Abscissa of control point 1.
  14836. * @param $y1 (float) Ordinate of control point 1.
  14837. * @param $x2 (float) Abscissa of control point 2.
  14838. * @param $y2 (float) Ordinate of control point 2.
  14839. * @param $x3 (float) Abscissa of end point.
  14840. * @param $y3 (float) Ordinate of end point.
  14841. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14842. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  14843. * @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).
  14844. * @public
  14845. * @see SetLineStyle()
  14846. * @since 2.1.000 (2008-01-08)
  14847. */
  14848. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  14849. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14850. $this->SetFillColorArray($fill_color);
  14851. }
  14852. $op = $this->getPathPaintOperator($style);
  14853. if ($line_style) {
  14854. $this->SetLineStyle($line_style);
  14855. }
  14856. $this->_outPoint($x0, $y0);
  14857. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  14858. $this->_out($op);
  14859. }
  14860. /**
  14861. * Draws a poly-Bezier curve.
  14862. * Each Bezier curve segment is a tangent to the line between the control points at
  14863. * either end of the curve.
  14864. * @param $x0 (float) Abscissa of start point.
  14865. * @param $y0 (float) Ordinate of start point.
  14866. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  14867. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14868. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  14869. * @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).
  14870. * @public
  14871. * @see SetLineStyle()
  14872. * @since 3.0008 (2008-05-12)
  14873. */
  14874. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  14875. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14876. $this->SetFillColorArray($fill_color);
  14877. }
  14878. $op = $this->getPathPaintOperator($style);
  14879. if ($op == 'f') {
  14880. $line_style = array();
  14881. }
  14882. if ($line_style) {
  14883. $this->SetLineStyle($line_style);
  14884. }
  14885. $this->_outPoint($x0, $y0);
  14886. foreach ($segments as $segment) {
  14887. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  14888. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  14889. }
  14890. $this->_out($op);
  14891. }
  14892. /**
  14893. * Draws an ellipse.
  14894. * An ellipse is formed from n Bezier curves.
  14895. * @param $x0 (float) Abscissa of center point.
  14896. * @param $y0 (float) Ordinate of center point.
  14897. * @param $rx (float) Horizontal radius.
  14898. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  14899. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  14900. * @param $astart: (float) Angle start of draw line. Default value: 0.
  14901. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  14902. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14903. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  14904. * @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).
  14905. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  14906. * @author Nicola Asuni
  14907. * @public
  14908. * @since 2.1.000 (2008-01-08)
  14909. */
  14910. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  14911. if ($this->empty_string($ry) OR ($ry == 0)) {
  14912. $ry = $rx;
  14913. }
  14914. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  14915. $this->SetFillColorArray($fill_color);
  14916. }
  14917. $op = $this->getPathPaintOperator($style);
  14918. if ($op == 'f') {
  14919. $line_style = array();
  14920. }
  14921. if ($line_style) {
  14922. $this->SetLineStyle($line_style);
  14923. }
  14924. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  14925. $this->_out($op);
  14926. }
  14927. /**
  14928. * Append an elliptical arc to the current path.
  14929. * An ellipse is formed from n Bezier curves.
  14930. * @param $xc (float) Abscissa of center point.
  14931. * @param $yc (float) Ordinate of center point.
  14932. * @param $rx (float) Horizontal radius.
  14933. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  14934. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  14935. * @param $angs: (float) Angle start of draw line. Default value: 0.
  14936. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  14937. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  14938. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  14939. * @param $startpoint (boolean) if true output a starting point.
  14940. * @param $ccw (boolean) if true draws in counter-clockwise.
  14941. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  14942. * @return array bounding box coordinates (x min, y min, x max, y max)
  14943. * @author Nicola Asuni
  14944. * @protected
  14945. * @since 4.9.019 (2010-04-26)
  14946. */
  14947. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  14948. $k = $this->k;
  14949. if ($nc < 2) {
  14950. $nc = 2;
  14951. }
  14952. $xmin = 2147483647;
  14953. $ymin = 2147483647;
  14954. $xmax = 0;
  14955. $ymax = 0;
  14956. if ($pie) {
  14957. // center of the arc
  14958. $this->_outPoint($xc, $yc);
  14959. }
  14960. $xang = deg2rad((float) $xang);
  14961. $angs = deg2rad((float) $angs);
  14962. $angf = deg2rad((float) $angf);
  14963. if ($svg) {
  14964. $as = $angs;
  14965. $af = $angf;
  14966. } else {
  14967. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  14968. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  14969. }
  14970. if ($as < 0) {
  14971. $as += (2 * M_PI);
  14972. }
  14973. if ($af < 0) {
  14974. $af += (2 * M_PI);
  14975. }
  14976. if ($ccw AND ($as > $af)) {
  14977. // reverse rotation
  14978. $as -= (2 * M_PI);
  14979. } elseif (!$ccw AND ($as < $af)) {
  14980. // reverse rotation
  14981. $af -= (2 * M_PI);
  14982. }
  14983. $total_angle = ($af - $as);
  14984. if ($nc < 2) {
  14985. $nc = 2;
  14986. }
  14987. // total arcs to draw
  14988. $nc *= (2 * abs($total_angle) / M_PI);
  14989. $nc = round($nc) + 1;
  14990. // angle of each arc
  14991. $arcang = ($total_angle / $nc);
  14992. // center point in PDF coordinates
  14993. $x0 = $xc;
  14994. $y0 = ($this->h - $yc);
  14995. // starting angle
  14996. $ang = $as;
  14997. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  14998. $cos_xang = cos($xang);
  14999. $sin_xang = sin($xang);
  15000. $cos_ang = cos($ang);
  15001. $sin_ang = sin($ang);
  15002. // first arc point
  15003. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  15004. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  15005. // first Bezier control point
  15006. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  15007. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  15008. if ($pie) {
  15009. // line from center to arc starting point
  15010. $this->_outLine($px1, $this->h - $py1);
  15011. } elseif ($startpoint) {
  15012. // arc starting point
  15013. $this->_outPoint($px1, $this->h - $py1);
  15014. }
  15015. // draw arcs
  15016. for ($i = 1; $i <= $nc; ++$i) {
  15017. // starting angle
  15018. $ang = $as + ($i * $arcang);
  15019. if ($i == $nc) {
  15020. $ang = $af;
  15021. }
  15022. $cos_ang = cos($ang);
  15023. $sin_ang = sin($ang);
  15024. // second arc point
  15025. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  15026. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  15027. // second Bezier control point
  15028. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  15029. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  15030. // draw arc
  15031. $cx1 = ($px1 + $qx1);
  15032. $cy1 = ($this->h - ($py1 + $qy1));
  15033. $cx2 = ($px2 - $qx2);
  15034. $cy2 = ($this->h - ($py2 - $qy2));
  15035. $cx3 = $px2;
  15036. $cy3 = ($this->h - $py2);
  15037. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  15038. // get bounding box coordinates
  15039. $xmin = min($xmin, $cx1, $cx2, $cx3);
  15040. $ymin = min($ymin, $cy1, $cy2, $cy3);
  15041. $xmax = max($xmax, $cx1, $cx2, $cx3);
  15042. $ymax = max($ymax, $cy1, $cy2, $cy3);
  15043. // move to next point
  15044. $px1 = $px2;
  15045. $py1 = $py2;
  15046. $qx1 = $qx2;
  15047. $qy1 = $qy2;
  15048. }
  15049. if ($pie) {
  15050. $this->_outLine($xc, $yc);
  15051. // get bounding box coordinates
  15052. $xmin = min($xmin, $xc);
  15053. $ymin = min($ymin, $yc);
  15054. $xmax = max($xmax, $xc);
  15055. $ymax = max($ymax, $yc);
  15056. }
  15057. return array($xmin, $ymin, $xmax, $ymax);
  15058. }
  15059. /**
  15060. * Draws a circle.
  15061. * A circle is formed from n Bezier curves.
  15062. * @param $x0 (float) Abscissa of center point.
  15063. * @param $y0 (float) Ordinate of center point.
  15064. * @param $r (float) Radius.
  15065. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  15066. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  15067. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15068. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  15069. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  15070. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  15071. * @public
  15072. * @since 2.1.000 (2008-01-08)
  15073. */
  15074. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  15075. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  15076. }
  15077. /**
  15078. * Draws a polygonal line
  15079. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  15080. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15081. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  15082. * <ul>
  15083. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  15084. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  15085. * </ul>
  15086. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  15087. * @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).
  15088. * @since 4.8.003 (2009-09-15)
  15089. * @public
  15090. */
  15091. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  15092. $this->Polygon($p, $style, $line_style, $fill_color, false);
  15093. }
  15094. /**
  15095. * Draws a polygon.
  15096. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  15097. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15098. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  15099. * <ul>
  15100. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  15101. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  15102. * </ul>
  15103. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  15104. * @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).
  15105. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  15106. * @public
  15107. * @since 2.1.000 (2008-01-08)
  15108. */
  15109. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  15110. $nc = count($p); // number of coordinates
  15111. $np = $nc / 2; // number of points
  15112. if ($closed) {
  15113. // close polygon by adding the first 2 points at the end (one line)
  15114. for ($i = 0; $i < 4; ++$i) {
  15115. $p[$nc + $i] = $p[$i];
  15116. }
  15117. // copy style for the last added line
  15118. if (isset($line_style[0])) {
  15119. $line_style[$np] = $line_style[0];
  15120. }
  15121. $nc += 4;
  15122. }
  15123. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  15124. $this->SetFillColorArray($fill_color);
  15125. }
  15126. $op = $this->getPathPaintOperator($style);
  15127. if ($op == 'f') {
  15128. $line_style = array();
  15129. }
  15130. $draw = true;
  15131. if ($line_style) {
  15132. if (isset($line_style['all'])) {
  15133. $this->SetLineStyle($line_style['all']);
  15134. } else {
  15135. $draw = false;
  15136. if ($op == 'B') {
  15137. // draw fill
  15138. $op = 'f';
  15139. $this->_outPoint($p[0], $p[1]);
  15140. for ($i = 2; $i < $nc; $i = $i + 2) {
  15141. $this->_outLine($p[$i], $p[$i + 1]);
  15142. }
  15143. $this->_out($op);
  15144. }
  15145. // draw outline
  15146. $this->_outPoint($p[0], $p[1]);
  15147. for ($i = 2; $i < $nc; $i = $i + 2) {
  15148. $line_num = ($i / 2) - 1;
  15149. if (isset($line_style[$line_num])) {
  15150. if ($line_style[$line_num] != 0) {
  15151. if (is_array($line_style[$line_num])) {
  15152. $this->_out('S');
  15153. $this->SetLineStyle($line_style[$line_num]);
  15154. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  15155. $this->_outLine($p[$i], $p[$i + 1]);
  15156. $this->_out('S');
  15157. $this->_outPoint($p[$i], $p[$i + 1]);
  15158. } else {
  15159. $this->_outLine($p[$i], $p[$i + 1]);
  15160. }
  15161. }
  15162. } else {
  15163. $this->_outLine($p[$i], $p[$i + 1]);
  15164. }
  15165. }
  15166. $this->_out($op);
  15167. }
  15168. }
  15169. if ($draw) {
  15170. $this->_outPoint($p[0], $p[1]);
  15171. for ($i = 2; $i < $nc; $i = $i + 2) {
  15172. $this->_outLine($p[$i], $p[$i + 1]);
  15173. }
  15174. $this->_out($op);
  15175. }
  15176. }
  15177. /**
  15178. * Draws a regular polygon.
  15179. * @param $x0 (float) Abscissa of center point.
  15180. * @param $y0 (float) Ordinate of center point.
  15181. * @param $r: (float) Radius of inscribed circle.
  15182. * @param $ns (integer) Number of sides.
  15183. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  15184. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  15185. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15186. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  15187. * <ul>
  15188. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  15189. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  15190. * </ul>
  15191. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  15192. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  15193. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  15194. * <ul>
  15195. * <li>D or empty string: Draw (default).</li>
  15196. * <li>F: Fill.</li>
  15197. * <li>DF or FD: Draw and fill.</li>
  15198. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  15199. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  15200. * </ul>
  15201. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  15202. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  15203. * @public
  15204. * @since 2.1.000 (2008-01-08)
  15205. */
  15206. 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()) {
  15207. if (3 > $ns) {
  15208. $ns = 3;
  15209. }
  15210. if ($draw_circle) {
  15211. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  15212. }
  15213. $p = array();
  15214. for ($i = 0; $i < $ns; ++$i) {
  15215. $a = $angle + ($i * 360 / $ns);
  15216. $a_rad = deg2rad((float) $a);
  15217. $p[] = $x0 + ($r * sin($a_rad));
  15218. $p[] = $y0 + ($r * cos($a_rad));
  15219. }
  15220. $this->Polygon($p, $style, $line_style, $fill_color);
  15221. }
  15222. /**
  15223. * Draws a star polygon
  15224. * @param $x0 (float) Abscissa of center point.
  15225. * @param $y0 (float) Ordinate of center point.
  15226. * @param $r (float) Radius of inscribed circle.
  15227. * @param $nv (integer) Number of vertices.
  15228. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  15229. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  15230. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  15231. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15232. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  15233. * <ul>
  15234. * <li>all: Line style of all sides. Array like for
  15235. * SetLineStyle().</li>
  15236. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  15237. * </ul>
  15238. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  15239. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  15240. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  15241. * <ul>
  15242. * <li>D or empty string: Draw (default).</li>
  15243. * <li>F: Fill.</li>
  15244. * <li>DF or FD: Draw and fill.</li>
  15245. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  15246. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  15247. * </ul>
  15248. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  15249. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  15250. * @public
  15251. * @since 2.1.000 (2008-01-08)
  15252. */
  15253. 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()) {
  15254. if ($nv < 2) {
  15255. $nv = 2;
  15256. }
  15257. if ($draw_circle) {
  15258. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  15259. }
  15260. $p2 = array();
  15261. $visited = array();
  15262. for ($i = 0; $i < $nv; ++$i) {
  15263. $a = $angle + ($i * 360 / $nv);
  15264. $a_rad = deg2rad((float) $a);
  15265. $p2[] = $x0 + ($r * sin($a_rad));
  15266. $p2[] = $y0 + ($r * cos($a_rad));
  15267. $visited[] = false;
  15268. }
  15269. $p = array();
  15270. $i = 0;
  15271. do {
  15272. $p[] = $p2[$i * 2];
  15273. $p[] = $p2[($i * 2) + 1];
  15274. $visited[$i] = true;
  15275. $i += $ng;
  15276. $i %= $nv;
  15277. } while (!$visited[$i]);
  15278. $this->Polygon($p, $style, $line_style, $fill_color);
  15279. }
  15280. /**
  15281. * Draws a rounded rectangle.
  15282. * @param $x (float) Abscissa of upper-left corner.
  15283. * @param $y (float) Ordinate of upper-left corner.
  15284. * @param $w (float) Width.
  15285. * @param $h (float) Height.
  15286. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  15287. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  15288. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15289. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  15290. * @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).
  15291. * @public
  15292. * @since 2.1.000 (2008-01-08)
  15293. */
  15294. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  15295. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  15296. }
  15297. /**
  15298. * Draws a rounded rectangle.
  15299. * @param $x (float) Abscissa of upper-left corner.
  15300. * @param $y (float) Ordinate of upper-left corner.
  15301. * @param $w (float) Width.
  15302. * @param $h (float) Height.
  15303. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  15304. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  15305. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  15306. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  15307. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  15308. * @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).
  15309. * @public
  15310. * @since 4.9.019 (2010-04-22)
  15311. */
  15312. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  15313. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  15314. // Not rounded
  15315. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  15316. return;
  15317. }
  15318. // Rounded
  15319. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  15320. $this->SetFillColorArray($fill_color);
  15321. }
  15322. $op = $this->getPathPaintOperator($style);
  15323. if ($op == 'f') {
  15324. $border_style = array();
  15325. }
  15326. if ($border_style) {
  15327. $this->SetLineStyle($border_style);
  15328. }
  15329. $MyArc = 4 / 3 * (sqrt(2) - 1);
  15330. $this->_outPoint($x + $rx, $y);
  15331. $xc = $x + $w - $rx;
  15332. $yc = $y + $ry;
  15333. $this->_outLine($xc, $y);
  15334. if ($round_corner[0]) {
  15335. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  15336. } else {
  15337. $this->_outLine($x + $w, $y);
  15338. }
  15339. $xc = $x + $w - $rx;
  15340. $yc = $y + $h - $ry;
  15341. $this->_outLine($x + $w, $yc);
  15342. if ($round_corner[1]) {
  15343. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  15344. } else {
  15345. $this->_outLine($x + $w, $y + $h);
  15346. }
  15347. $xc = $x + $rx;
  15348. $yc = $y + $h - $ry;
  15349. $this->_outLine($xc, $y + $h);
  15350. if ($round_corner[2]) {
  15351. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  15352. } else {
  15353. $this->_outLine($x, $y + $h);
  15354. }
  15355. $xc = $x + $rx;
  15356. $yc = $y + $ry;
  15357. $this->_outLine($x, $yc);
  15358. if ($round_corner[3]) {
  15359. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  15360. } else {
  15361. $this->_outLine($x, $y);
  15362. $this->_outLine($x + $rx, $y);
  15363. }
  15364. $this->_out($op);
  15365. }
  15366. /**
  15367. * Draws a grahic arrow.
  15368. * @param $x0 (float) Abscissa of first point.
  15369. * @param $y0 (float) Ordinate of first point.
  15370. * @param $x1 (float) Abscissa of second point.
  15371. * @param $y1 (float) Ordinate of second point.
  15372. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  15373. * @param $arm_size (float) length of arrowhead arms
  15374. * @param $arm_angle (int) angle between an arm and the shaft
  15375. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  15376. * @since 4.6.018 (2009-07-10)
  15377. */
  15378. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  15379. // getting arrow direction angle
  15380. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  15381. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  15382. if ($dir_angle < 0) {
  15383. $dir_angle += (2 * M_PI);
  15384. }
  15385. $arm_angle = deg2rad($arm_angle);
  15386. $sx1 = $x1;
  15387. $sy1 = $y1;
  15388. if ($head_style > 0) {
  15389. // calculate the stopping point for the arrow shaft
  15390. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  15391. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  15392. }
  15393. // main arrow line / shaft
  15394. $this->Line($x0, $y0, $sx1, $sy1);
  15395. // left arrowhead arm tip
  15396. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  15397. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  15398. // right arrowhead arm tip
  15399. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  15400. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  15401. $mode = 'D';
  15402. $style = array();
  15403. switch ($head_style) {
  15404. case 0: {
  15405. // draw only arrowhead arms
  15406. $mode = 'D';
  15407. $style = array(1, 1, 0);
  15408. break;
  15409. }
  15410. case 1: {
  15411. // draw closed arrowhead, but no fill
  15412. $mode = 'D';
  15413. break;
  15414. }
  15415. case 2: {
  15416. // closed and filled arrowhead
  15417. $mode = 'DF';
  15418. break;
  15419. }
  15420. case 3: {
  15421. // filled arrowhead
  15422. $mode = 'F';
  15423. break;
  15424. }
  15425. }
  15426. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  15427. }
  15428. // END GRAPHIC FUNCTIONS SECTION -----------------------
  15429. // BIDIRECTIONAL TEXT SECTION --------------------------
  15430. /**
  15431. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  15432. * @param $str (string) string to manipulate.
  15433. * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
  15434. * @param $forcertl (bool) if true forces RTL text direction
  15435. * @return string
  15436. * @protected
  15437. * @author Nicola Asuni
  15438. * @since 2.1.000 (2008-01-08)
  15439. */
  15440. protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
  15441. return $this->utf8StrArrRev($this->UTF8StringToArray($str), $str, $setbom, $forcertl);
  15442. }
  15443. /**
  15444. * Reverse the RLT substrings array using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  15445. * @param $arr (array) array of unicode values.
  15446. * @param $str (string) string to manipulate (or empty value).
  15447. * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
  15448. * @param $forcertl (bool) if true forces RTL text direction
  15449. * @return string
  15450. * @protected
  15451. * @author Nicola Asuni
  15452. * @since 4.9.000 (2010-03-27)
  15453. */
  15454. protected function utf8StrArrRev($arr, $str='', $setbom=false, $forcertl=false) {
  15455. return $this->arrUTF8ToUTF16BE($this->utf8Bidi($arr, $str, $forcertl), $setbom);
  15456. }
  15457. /**
  15458. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  15459. * @param $ta (array) array of characters composing the string.
  15460. * @param $str (string) string to process
  15461. * @param $forcertl (bool) if 'R' forces RTL, if 'L' forces LTR
  15462. * @return array of unicode chars
  15463. * @author Nicola Asuni
  15464. * @protected
  15465. * @since 2.4.000 (2008-03-06)
  15466. */
  15467. protected function utf8Bidi($ta, $str='', $forcertl=false) {
  15468. // paragraph embedding level
  15469. $pel = 0;
  15470. // max level
  15471. $maxlevel = 0;
  15472. if ($this->empty_string($str)) {
  15473. // create string from array
  15474. $str = $this->UTF8ArrSubString($ta);
  15475. }
  15476. // check if string contains arabic text
  15477. if (preg_match($this->unicode->uni_RE_PATTERN_ARABIC, $str)) {
  15478. $arabic = true;
  15479. } else {
  15480. $arabic = false;
  15481. }
  15482. // check if string contains RTL text
  15483. if (!($forcertl OR $arabic OR preg_match($this->unicode->uni_RE_PATTERN_RTL, $str))) {
  15484. return $ta;
  15485. }
  15486. // get number of chars
  15487. $numchars = count($ta);
  15488. if ($forcertl == 'R') {
  15489. $pel = 1;
  15490. } elseif ($forcertl == 'L') {
  15491. $pel = 0;
  15492. } else {
  15493. // P2. In each paragraph, find the first character of type L, AL, or R.
  15494. // 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.
  15495. for ($i=0; $i < $numchars; ++$i) {
  15496. $type = $this->unicode->uni_type[$ta[$i]];
  15497. if ($type == 'L') {
  15498. $pel = 0;
  15499. break;
  15500. } elseif (($type == 'AL') OR ($type == 'R')) {
  15501. $pel = 1;
  15502. break;
  15503. }
  15504. }
  15505. }
  15506. // Current Embedding Level
  15507. $cel = $pel;
  15508. // directional override status
  15509. $dos = 'N';
  15510. $remember = array();
  15511. // start-of-level-run
  15512. $sor = $pel % 2 ? 'R' : 'L';
  15513. $eor = $sor;
  15514. // Array of characters data
  15515. $chardata = Array();
  15516. // 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.
  15517. // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
  15518. for ($i=0; $i < $numchars; ++$i) {
  15519. if ($ta[$i] == $this->unicode->uni_RLE) {
  15520. // X2. With each RLE, compute the least greater odd embedding level.
  15521. // 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.
  15522. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15523. $next_level = $cel + ($cel % 2) + 1;
  15524. if ($next_level < 62) {
  15525. $remember[] = array('num' => $this->unicode->uni_RLE, 'cel' => $cel, 'dos' => $dos);
  15526. $cel = $next_level;
  15527. $dos = 'N';
  15528. $sor = $eor;
  15529. $eor = $cel % 2 ? 'R' : 'L';
  15530. }
  15531. } elseif ($ta[$i] == $this->unicode->uni_LRE) {
  15532. // X3. With each LRE, compute the least greater even embedding level.
  15533. // 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.
  15534. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15535. $next_level = $cel + 2 - ($cel % 2);
  15536. if ( $next_level < 62 ) {
  15537. $remember[] = array('num' => $this->unicode->uni_LRE, 'cel' => $cel, 'dos' => $dos);
  15538. $cel = $next_level;
  15539. $dos = 'N';
  15540. $sor = $eor;
  15541. $eor = $cel % 2 ? 'R' : 'L';
  15542. }
  15543. } elseif ($ta[$i] == $this->unicode->uni_RLO) {
  15544. // X4. With each RLO, compute the least greater odd embedding level.
  15545. // 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.
  15546. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15547. $next_level = $cel + ($cel % 2) + 1;
  15548. if ($next_level < 62) {
  15549. $remember[] = array('num' => $this->unicode->uni_RLO, 'cel' => $cel, 'dos' => $dos);
  15550. $cel = $next_level;
  15551. $dos = 'R';
  15552. $sor = $eor;
  15553. $eor = $cel % 2 ? 'R' : 'L';
  15554. }
  15555. } elseif ($ta[$i] == $this->unicode->uni_LRO) {
  15556. // X5. With each LRO, compute the least greater even embedding level.
  15557. // 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.
  15558. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  15559. $next_level = $cel + 2 - ($cel % 2);
  15560. if ( $next_level < 62 ) {
  15561. $remember[] = array('num' => $this->unicode->uni_LRO, 'cel' => $cel, 'dos' => $dos);
  15562. $cel = $next_level;
  15563. $dos = 'L';
  15564. $sor = $eor;
  15565. $eor = $cel % 2 ? 'R' : 'L';
  15566. }
  15567. } elseif ($ta[$i] == $this->unicode->uni_PDF) {
  15568. // 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.
  15569. if (count($remember)) {
  15570. $last = count($remember ) - 1;
  15571. if (($remember[$last]['num'] == $this->unicode->uni_RLE) OR
  15572. ($remember[$last]['num'] == $this->unicode->uni_LRE) OR
  15573. ($remember[$last]['num'] == $this->unicode->uni_RLO) OR
  15574. ($remember[$last]['num'] == $this->unicode->uni_LRO)) {
  15575. $match = array_pop($remember);
  15576. $cel = $match['cel'];
  15577. $dos = $match['dos'];
  15578. $sor = $eor;
  15579. $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
  15580. }
  15581. }
  15582. } elseif (($ta[$i] != $this->unicode->uni_RLE) AND
  15583. ($ta[$i] != $this->unicode->uni_LRE) AND
  15584. ($ta[$i] != $this->unicode->uni_RLO) AND
  15585. ($ta[$i] != $this->unicode->uni_LRO) AND
  15586. ($ta[$i] != $this->unicode->uni_PDF)) {
  15587. // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
  15588. // a. Set the level of the current character to the current embedding level.
  15589. // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
  15590. if ($dos != 'N') {
  15591. $chardir = $dos;
  15592. } else {
  15593. if (isset($this->unicode->uni_type[$ta[$i]])) {
  15594. $chardir = $this->unicode->uni_type[$ta[$i]];
  15595. } else {
  15596. $chardir = 'L';
  15597. }
  15598. }
  15599. // stores string characters and other information
  15600. $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
  15601. }
  15602. } // end for each char
  15603. // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
  15604. // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
  15605. // 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.
  15606. // 3.3.3 Resolving Weak Types
  15607. // 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.
  15608. // Nonspacing marks are now resolved based on the previous characters.
  15609. $numchars = count($chardata);
  15610. // 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.
  15611. $prevlevel = -1; // track level changes
  15612. $levcount = 0; // counts consecutive chars at the same level
  15613. for ($i=0; $i < $numchars; ++$i) {
  15614. if ($chardata[$i]['type'] == 'NSM') {
  15615. if ($levcount) {
  15616. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15617. } elseif ($i > 0) {
  15618. $chardata[$i]['type'] = $chardata[($i-1)]['type'];
  15619. }
  15620. }
  15621. if ($chardata[$i]['level'] != $prevlevel) {
  15622. $levcount = 0;
  15623. } else {
  15624. ++$levcount;
  15625. }
  15626. $prevlevel = $chardata[$i]['level'];
  15627. }
  15628. // 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.
  15629. $prevlevel = -1;
  15630. $levcount = 0;
  15631. for ($i=0; $i < $numchars; ++$i) {
  15632. if ($chardata[$i]['char'] == 'EN') {
  15633. for ($j=$levcount; $j >= 0; $j--) {
  15634. if ($chardata[$j]['type'] == 'AL') {
  15635. $chardata[$i]['type'] = 'AN';
  15636. } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
  15637. break;
  15638. }
  15639. }
  15640. }
  15641. if ($chardata[$i]['level'] != $prevlevel) {
  15642. $levcount = 0;
  15643. } else {
  15644. ++$levcount;
  15645. }
  15646. $prevlevel = $chardata[$i]['level'];
  15647. }
  15648. // W3. Change all ALs to R.
  15649. for ($i=0; $i < $numchars; ++$i) {
  15650. if ($chardata[$i]['type'] == 'AL') {
  15651. $chardata[$i]['type'] = 'R';
  15652. }
  15653. }
  15654. // 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.
  15655. $prevlevel = -1;
  15656. $levcount = 0;
  15657. for ($i=0; $i < $numchars; ++$i) {
  15658. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  15659. if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  15660. $chardata[$i]['type'] = 'EN';
  15661. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  15662. $chardata[$i]['type'] = 'EN';
  15663. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
  15664. $chardata[$i]['type'] = 'AN';
  15665. }
  15666. }
  15667. if ($chardata[$i]['level'] != $prevlevel) {
  15668. $levcount = 0;
  15669. } else {
  15670. ++$levcount;
  15671. }
  15672. $prevlevel = $chardata[$i]['level'];
  15673. }
  15674. // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
  15675. $prevlevel = -1;
  15676. $levcount = 0;
  15677. for ($i=0; $i < $numchars; ++$i) {
  15678. if ($chardata[$i]['type'] == 'ET') {
  15679. if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
  15680. $chardata[$i]['type'] = 'EN';
  15681. } else {
  15682. $j = $i+1;
  15683. while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
  15684. if ($chardata[$j]['type'] == 'EN') {
  15685. $chardata[$i]['type'] = 'EN';
  15686. break;
  15687. } elseif ($chardata[$j]['type'] != 'ET') {
  15688. break;
  15689. }
  15690. ++$j;
  15691. }
  15692. }
  15693. }
  15694. if ($chardata[$i]['level'] != $prevlevel) {
  15695. $levcount = 0;
  15696. } else {
  15697. ++$levcount;
  15698. }
  15699. $prevlevel = $chardata[$i]['level'];
  15700. }
  15701. // W6. Otherwise, separators and terminators change to Other Neutral.
  15702. $prevlevel = -1;
  15703. $levcount = 0;
  15704. for ($i=0; $i < $numchars; ++$i) {
  15705. if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
  15706. $chardata[$i]['type'] = 'ON';
  15707. }
  15708. if ($chardata[$i]['level'] != $prevlevel) {
  15709. $levcount = 0;
  15710. } else {
  15711. ++$levcount;
  15712. }
  15713. $prevlevel = $chardata[$i]['level'];
  15714. }
  15715. //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.
  15716. $prevlevel = -1;
  15717. $levcount = 0;
  15718. for ($i=0; $i < $numchars; ++$i) {
  15719. if ($chardata[$i]['char'] == 'EN') {
  15720. for ($j=$levcount; $j >= 0; $j--) {
  15721. if ($chardata[$j]['type'] == 'L') {
  15722. $chardata[$i]['type'] = 'L';
  15723. } elseif ($chardata[$j]['type'] == 'R') {
  15724. break;
  15725. }
  15726. }
  15727. }
  15728. if ($chardata[$i]['level'] != $prevlevel) {
  15729. $levcount = 0;
  15730. } else {
  15731. ++$levcount;
  15732. }
  15733. $prevlevel = $chardata[$i]['level'];
  15734. }
  15735. // 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.
  15736. $prevlevel = -1;
  15737. $levcount = 0;
  15738. for ($i=0; $i < $numchars; ++$i) {
  15739. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  15740. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  15741. $chardata[$i]['type'] = 'L';
  15742. } elseif (($chardata[$i]['type'] == 'N') AND
  15743. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  15744. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  15745. $chardata[$i]['type'] = 'R';
  15746. } elseif ($chardata[$i]['type'] == 'N') {
  15747. // N2. Any remaining neutrals take the embedding direction
  15748. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15749. }
  15750. } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  15751. // first char
  15752. if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  15753. $chardata[$i]['type'] = 'L';
  15754. } elseif (($chardata[$i]['type'] == 'N') AND
  15755. (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
  15756. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  15757. $chardata[$i]['type'] = 'R';
  15758. } elseif ($chardata[$i]['type'] == 'N') {
  15759. // N2. Any remaining neutrals take the embedding direction
  15760. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15761. }
  15762. } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
  15763. //last char
  15764. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
  15765. $chardata[$i]['type'] = 'L';
  15766. } elseif (($chardata[$i]['type'] == 'N') AND
  15767. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  15768. (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
  15769. $chardata[$i]['type'] = 'R';
  15770. } elseif ($chardata[$i]['type'] == 'N') {
  15771. // N2. Any remaining neutrals take the embedding direction
  15772. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15773. }
  15774. } elseif ($chardata[$i]['type'] == 'N') {
  15775. // N2. Any remaining neutrals take the embedding direction
  15776. $chardata[$i]['type'] = $chardata[$i]['sor'];
  15777. }
  15778. if ($chardata[$i]['level'] != $prevlevel) {
  15779. $levcount = 0;
  15780. } else {
  15781. ++$levcount;
  15782. }
  15783. $prevlevel = $chardata[$i]['level'];
  15784. }
  15785. // 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.
  15786. // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
  15787. for ($i=0; $i < $numchars; ++$i) {
  15788. $odd = $chardata[$i]['level'] % 2;
  15789. if ($odd) {
  15790. if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  15791. $chardata[$i]['level'] += 1;
  15792. }
  15793. } else {
  15794. if ($chardata[$i]['type'] == 'R') {
  15795. $chardata[$i]['level'] += 1;
  15796. } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  15797. $chardata[$i]['level'] += 2;
  15798. }
  15799. }
  15800. $maxlevel = max($chardata[$i]['level'],$maxlevel);
  15801. }
  15802. // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
  15803. // 1. Segment separators,
  15804. // 2. Paragraph separators,
  15805. // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
  15806. // 4. Any sequence of white space characters at the end of the line.
  15807. for ($i=0; $i < $numchars; ++$i) {
  15808. if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
  15809. $chardata[$i]['level'] = $pel;
  15810. } elseif ($chardata[$i]['type'] == 'WS') {
  15811. $j = $i+1;
  15812. while ($j < $numchars) {
  15813. if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
  15814. (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
  15815. $chardata[$i]['level'] = $pel;
  15816. break;
  15817. } elseif ($chardata[$j]['type'] != 'WS') {
  15818. break;
  15819. }
  15820. ++$j;
  15821. }
  15822. }
  15823. }
  15824. // Arabic Shaping
  15825. // 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.
  15826. if ($arabic) {
  15827. $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
  15828. $alfletter = array(1570,1571,1573,1575);
  15829. $chardata2 = $chardata;
  15830. $laaletter = false;
  15831. $charAL = array();
  15832. $x = 0;
  15833. for ($i=0; $i < $numchars; ++$i) {
  15834. if (($this->unicode->uni_type[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
  15835. $charAL[$x] = $chardata[$i];
  15836. $charAL[$x]['i'] = $i;
  15837. $chardata[$i]['x'] = $x;
  15838. ++$x;
  15839. }
  15840. }
  15841. $numAL = $x;
  15842. for ($i=0; $i < $numchars; ++$i) {
  15843. $thischar = $chardata[$i];
  15844. if ($i > 0) {
  15845. $prevchar = $chardata[($i-1)];
  15846. } else {
  15847. $prevchar = false;
  15848. }
  15849. if (($i+1) < $numchars) {
  15850. $nextchar = $chardata[($i+1)];
  15851. } else {
  15852. $nextchar = false;
  15853. }
  15854. if ($this->unicode->uni_type[$thischar['char']] == 'AL') {
  15855. $x = $thischar['x'];
  15856. if ($x > 0) {
  15857. $prevchar = $charAL[($x-1)];
  15858. } else {
  15859. $prevchar = false;
  15860. }
  15861. if (($x+1) < $numAL) {
  15862. $nextchar = $charAL[($x+1)];
  15863. } else {
  15864. $nextchar = false;
  15865. }
  15866. // if laa letter
  15867. if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
  15868. $arabicarr = $this->unicode->uni_laa_array;
  15869. $laaletter = true;
  15870. if ($x > 1) {
  15871. $prevchar = $charAL[($x-2)];
  15872. } else {
  15873. $prevchar = false;
  15874. }
  15875. } else {
  15876. $arabicarr = $this->unicode->uni_arabicsubst;
  15877. $laaletter = false;
  15878. }
  15879. if (($prevchar !== false) AND ($nextchar !== false) AND
  15880. (($this->unicode->uni_type[$prevchar['char']] == 'AL') OR ($this->unicode->uni_type[$prevchar['char']] == 'NSM')) AND
  15881. (($this->unicode->uni_type[$nextchar['char']] == 'AL') OR ($this->unicode->uni_type[$nextchar['char']] == 'NSM')) AND
  15882. ($prevchar['type'] == $thischar['type']) AND
  15883. ($nextchar['type'] == $thischar['type']) AND
  15884. ($nextchar['char'] != 1567)) {
  15885. if (in_array($prevchar['char'], $endedletter)) {
  15886. if (isset($arabicarr[$thischar['char']][2])) {
  15887. // initial
  15888. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  15889. }
  15890. } else {
  15891. if (isset($arabicarr[$thischar['char']][3])) {
  15892. // medial
  15893. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
  15894. }
  15895. }
  15896. } elseif (($nextchar !== false) AND
  15897. (($this->unicode->uni_type[$nextchar['char']] == 'AL') OR ($this->unicode->uni_type[$nextchar['char']] == 'NSM')) AND
  15898. ($nextchar['type'] == $thischar['type']) AND
  15899. ($nextchar['char'] != 1567)) {
  15900. if (isset($arabicarr[$chardata[$i]['char']][2])) {
  15901. // initial
  15902. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  15903. }
  15904. } elseif ((($prevchar !== false) AND
  15905. (($this->unicode->uni_type[$prevchar['char']] == 'AL') OR ($this->unicode->uni_type[$prevchar['char']] == 'NSM')) AND
  15906. ($prevchar['type'] == $thischar['type'])) OR
  15907. (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
  15908. // final
  15909. if (($i > 1) AND ($thischar['char'] == 1607) AND
  15910. ($chardata[$i-1]['char'] == 1604) AND
  15911. ($chardata[$i-2]['char'] == 1604)) {
  15912. //Allah Word
  15913. // mark characters to delete with false
  15914. $chardata2[$i-2]['char'] = false;
  15915. $chardata2[$i-1]['char'] = false;
  15916. $chardata2[$i]['char'] = 65010;
  15917. } else {
  15918. if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
  15919. if (isset($arabicarr[$thischar['char']][0])) {
  15920. // isolated
  15921. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  15922. }
  15923. } else {
  15924. if (isset($arabicarr[$thischar['char']][1])) {
  15925. // final
  15926. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
  15927. }
  15928. }
  15929. }
  15930. } elseif (isset($arabicarr[$thischar['char']][0])) {
  15931. // isolated
  15932. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  15933. }
  15934. // if laa letter
  15935. if ($laaletter) {
  15936. // mark characters to delete with false
  15937. $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
  15938. }
  15939. } // end if AL (Arabic Letter)
  15940. } // end for each char
  15941. /*
  15942. * Combining characters that can occur with Arabic Shadda (0651 HEX, 1617 DEC) are replaced.
  15943. * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
  15944. */
  15945. for ($i = 0; $i < ($numchars-1); ++$i) {
  15946. if (($chardata2[$i]['char'] == 1617) AND (isset($this->unicode->uni_diacritics[($chardata2[$i+1]['char'])]))) {
  15947. // check if the subtitution font is defined on current font
  15948. if (isset($this->CurrentFont['cw'][($this->unicode->uni_diacritics[($chardata2[$i+1]['char'])])])) {
  15949. $chardata2[$i]['char'] = false;
  15950. $chardata2[$i+1]['char'] = $this->unicode->uni_diacritics[($chardata2[$i+1]['char'])];
  15951. }
  15952. }
  15953. }
  15954. // remove marked characters
  15955. foreach ($chardata2 as $key => $value) {
  15956. if ($value['char'] === false) {
  15957. unset($chardata2[$key]);
  15958. }
  15959. }
  15960. $chardata = array_values($chardata2);
  15961. $numchars = count($chardata);
  15962. unset($chardata2);
  15963. unset($arabicarr);
  15964. unset($laaletter);
  15965. unset($charAL);
  15966. }
  15967. // 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.
  15968. for ($j=$maxlevel; $j > 0; $j--) {
  15969. $ordarray = Array();
  15970. $revarr = Array();
  15971. $onlevel = false;
  15972. for ($i=0; $i < $numchars; ++$i) {
  15973. if ($chardata[$i]['level'] >= $j) {
  15974. $onlevel = true;
  15975. if (isset($this->unicode->uni_mirror[$chardata[$i]['char']])) {
  15976. // 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.
  15977. $chardata[$i]['char'] = $this->unicode->uni_mirror[$chardata[$i]['char']];
  15978. }
  15979. $revarr[] = $chardata[$i];
  15980. } else {
  15981. if ($onlevel) {
  15982. $revarr = array_reverse($revarr);
  15983. $ordarray = array_merge($ordarray, $revarr);
  15984. $revarr = Array();
  15985. $onlevel = false;
  15986. }
  15987. $ordarray[] = $chardata[$i];
  15988. }
  15989. }
  15990. if ($onlevel) {
  15991. $revarr = array_reverse($revarr);
  15992. $ordarray = array_merge($ordarray, $revarr);
  15993. }
  15994. $chardata = $ordarray;
  15995. }
  15996. $ordarray = array();
  15997. for ($i=0; $i < $numchars; ++$i) {
  15998. $ordarray[] = $chardata[$i]['char'];
  15999. // store char values for subsetting
  16000. $this->CurrentFont['subsetchars'][$chardata[$i]['char']] = true;
  16001. }
  16002. // update font subsetchars
  16003. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  16004. return $ordarray;
  16005. }
  16006. // END OF BIDIRECTIONAL TEXT SECTION -------------------
  16007. /**
  16008. * Encode a name object.
  16009. * @param $name (string) Name object to encode.
  16010. * @return (string) Encoded name object.
  16011. * @protected
  16012. * @author Nicola Asuni
  16013. * @since 5.9.097 (2011-06-23)
  16014. */
  16015. protected function encodeNameObject($name) {
  16016. $escname = '';
  16017. $length = strlen($name);
  16018. for ($i = 0; $i < $length; ++$i) {
  16019. $chr = $name[$i];
  16020. if (preg_match('/[0-9a-zA-Z]/', $chr) == 1) {
  16021. $escname .= $chr;
  16022. } else {
  16023. $escname .= sprintf('#%02X', ord($chr));
  16024. }
  16025. }
  16026. return $escname;
  16027. }
  16028. /**
  16029. * Add a Named Destination.
  16030. * NOTE: destination names are unique, so only last entry will be saved.
  16031. * @param $name (string) Destination name.
  16032. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  16033. * @param $page (int) Target page number (leave empty for current page).
  16034. * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
  16035. * @return (string) Stripped named destination identifier or false in case of error.
  16036. * @public
  16037. * @author Christian Deligant, Nicola Asuni
  16038. * @since 5.9.097 (2011-06-23)
  16039. */
  16040. public function setDestination($name, $y=-1, $page='', $x=-1) {
  16041. // remove unsupported characters
  16042. $name = $this->encodeNameObject($name);
  16043. if ($this->empty_string($name)) {
  16044. return false;
  16045. }
  16046. if ($y == -1) {
  16047. $y = $this->GetY();
  16048. } elseif ($y < 0) {
  16049. $y = 0;
  16050. } elseif ($y > $this->h) {
  16051. $y = $this->h;
  16052. }
  16053. if ($x == -1) {
  16054. $x = $this->GetX();
  16055. } elseif ($x < 0) {
  16056. $x = 0;
  16057. } elseif ($x > $this->w) {
  16058. $x = $this->w;
  16059. }
  16060. if (empty($page)) {
  16061. $page = $this->PageNo();
  16062. if (empty($page)) {
  16063. return;
  16064. }
  16065. }
  16066. $this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page);
  16067. return $name;
  16068. }
  16069. /**
  16070. * Return the Named Destination array.
  16071. * @return (array) Named Destination array.
  16072. * @public
  16073. * @author Nicola Asuni
  16074. * @since 5.9.097 (2011-06-23)
  16075. */
  16076. public function getDestination() {
  16077. return $this->dests;
  16078. }
  16079. /**
  16080. * Create a javascript PDF string.
  16081. * @protected
  16082. * @author Johannes Güntert, Nicola Asuni
  16083. * @since 5.9.098 (2011-06-23)
  16084. */
  16085. protected function _putdests() {
  16086. if (empty($this->dests)) {
  16087. return;
  16088. }
  16089. $this->n_dests = $this->_newobj();
  16090. $out = ' <<';
  16091. foreach($this->dests as $name => $o) {
  16092. $out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  16093. }
  16094. $out .= ' >>';
  16095. $out .= "\n".'endobj';
  16096. $this->_out($out);
  16097. }
  16098. /**
  16099. * Adds a bookmark - alias for Bookmark().
  16100. * @param $txt (string) Bookmark description.
  16101. * @param $level (int) Bookmark level (minimum value is 0).
  16102. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  16103. * @param $page (int) Target page number (leave empty for current page).
  16104. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  16105. * @param $color (array) RGB color array (values from 0 to 255).
  16106. * @public
  16107. */
  16108. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0)) {
  16109. $this->Bookmark($txt, $level, $y, $page, $style, $color);
  16110. }
  16111. /**
  16112. * Adds a bookmark.
  16113. * @param $txt (string) Bookmark description.
  16114. * @param $level (int) Bookmark level (minimum value is 0).
  16115. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  16116. * @param $page (int) Target page number (leave empty for current page).
  16117. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  16118. * @param $color (array) RGB color array (values from 0 to 255).
  16119. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  16120. * @public
  16121. * @author Olivier Plathey, Nicola Asuni
  16122. * @since 2.1.002 (2008-02-12)
  16123. */
  16124. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1) {
  16125. if ($level < 0) {
  16126. $level = 0;
  16127. }
  16128. if (isset($this->outlines[0])) {
  16129. $lastoutline = end($this->outlines);
  16130. $maxlevel = $lastoutline['l'] + 1;
  16131. } else {
  16132. $maxlevel = 0;
  16133. }
  16134. if ($level > $maxlevel) {
  16135. $level = $maxlevel;
  16136. }
  16137. if ($y == -1) {
  16138. $y = $this->GetY();
  16139. } elseif ($y < 0) {
  16140. $y = 0;
  16141. } elseif ($y > $this->h) {
  16142. $y = $this->h;
  16143. }
  16144. if ($x == -1) {
  16145. $x = $this->GetX();
  16146. } elseif ($x < 0) {
  16147. $x = 0;
  16148. } elseif ($x > $this->w) {
  16149. $x = $this->w;
  16150. }
  16151. if (empty($page)) {
  16152. $page = $this->PageNo();
  16153. if (empty($page)) {
  16154. return;
  16155. }
  16156. }
  16157. $this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 's' => strtoupper($style), 'c' => $color);
  16158. }
  16159. /**
  16160. * Sort bookmarks for page and key.
  16161. * @protected
  16162. * @since 5.9.119 (2011-09-19)
  16163. */
  16164. protected function sortBookmarks() {
  16165. // get sorting columns
  16166. $outline_p = array();
  16167. $outline_y = array();
  16168. foreach ($this->outlines as $key => $row) {
  16169. $outline_p[$key] = $row['p'];
  16170. $outline_k[$key] = $key;
  16171. }
  16172. // sort outlines by page and original position
  16173. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  16174. }
  16175. /**
  16176. * Create a bookmark PDF string.
  16177. * @protected
  16178. * @author Olivier Plathey, Nicola Asuni
  16179. * @since 2.1.002 (2008-02-12)
  16180. */
  16181. protected function _putbookmarks() {
  16182. $nb = count($this->outlines);
  16183. if ($nb == 0) {
  16184. return;
  16185. }
  16186. // sort bookmarks
  16187. $this->sortBookmarks();
  16188. $lru = array();
  16189. $level = 0;
  16190. foreach ($this->outlines as $i => $o) {
  16191. if ($o['l'] > 0) {
  16192. $parent = $lru[($o['l'] - 1)];
  16193. //Set parent and last pointers
  16194. $this->outlines[$i]['parent'] = $parent;
  16195. $this->outlines[$parent]['last'] = $i;
  16196. if ($o['l'] > $level) {
  16197. //Level increasing: set first pointer
  16198. $this->outlines[$parent]['first'] = $i;
  16199. }
  16200. } else {
  16201. $this->outlines[$i]['parent'] = $nb;
  16202. }
  16203. if (($o['l'] <= $level) AND ($i > 0)) {
  16204. //Set prev and next pointers
  16205. $prev = $lru[$o['l']];
  16206. $this->outlines[$prev]['next'] = $i;
  16207. $this->outlines[$i]['prev'] = $prev;
  16208. }
  16209. $lru[$o['l']] = $i;
  16210. $level = $o['l'];
  16211. }
  16212. //Outline items
  16213. $n = $this->n + 1;
  16214. $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';
  16215. foreach ($this->outlines as $i => $o) {
  16216. $oid = $this->_newobj();
  16217. // covert HTML title to string
  16218. $title = preg_replace($nltags, "\n", $o['t']);
  16219. $title = preg_replace("/[\r]+/si", '', $title);
  16220. $title = preg_replace("/[\n]+/si", "\n", $title);
  16221. $title = strip_tags($title);
  16222. $title = $this->stringTrim($title);
  16223. $out = '<</Title '.$this->_textstring($title, $oid);
  16224. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  16225. if (isset($o['prev'])) {
  16226. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  16227. }
  16228. if (isset($o['next'])) {
  16229. $out .= ' /Next '.($n + $o['next']).' 0 R';
  16230. }
  16231. if (isset($o['first'])) {
  16232. $out .= ' /First '.($n + $o['first']).' 0 R';
  16233. }
  16234. if (isset($o['last'])) {
  16235. $out .= ' /Last '.($n + $o['last']).' 0 R';
  16236. }
  16237. if (isset($this->page_obj_id[($o['p'])])) {
  16238. $out .= ' '.sprintf('/Dest [%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  16239. }
  16240. // set font style
  16241. $style = 0;
  16242. if (!empty($o['s'])) {
  16243. // bold
  16244. if (strpos($o['s'], 'B') !== false) {
  16245. $style |= 2;
  16246. }
  16247. // oblique
  16248. if (strpos($o['s'], 'I') !== false) {
  16249. $style |= 1;
  16250. }
  16251. }
  16252. $out .= sprintf(' /F %d', $style);
  16253. // set bookmark color
  16254. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  16255. $color = array_values($o['c']);
  16256. $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  16257. } else {
  16258. // black
  16259. $out .= ' /C [0.0 0.0 0.0]';
  16260. }
  16261. $out .= ' /Count 0'; // normally closed item
  16262. $out .= ' >>';
  16263. $out .= "\n".'endobj';
  16264. $this->_out($out);
  16265. }
  16266. //Outline root
  16267. $this->OutlineRoot = $this->_newobj();
  16268. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  16269. }
  16270. // --- JAVASCRIPT ------------------------------------------------------
  16271. /**
  16272. * Adds a javascript
  16273. * @param $script (string) Javascript code
  16274. * @public
  16275. * @author Johannes Güntert, Nicola Asuni
  16276. * @since 2.1.002 (2008-02-12)
  16277. */
  16278. public function IncludeJS($script) {
  16279. $this->javascript .= $script;
  16280. }
  16281. /**
  16282. * Adds a javascript object and return object ID
  16283. * @param $script (string) Javascript code
  16284. * @param $onload (boolean) if true executes this object when opening the document
  16285. * @return int internal object ID
  16286. * @public
  16287. * @author Nicola Asuni
  16288. * @since 4.8.000 (2009-09-07)
  16289. */
  16290. public function addJavascriptObject($script, $onload=false) {
  16291. if ($this->pdfa_mode) {
  16292. // javascript is not allowed in PDF/A mode
  16293. return false;
  16294. }
  16295. ++$this->n;
  16296. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  16297. return $this->n;
  16298. }
  16299. /**
  16300. * Create a javascript PDF string.
  16301. * @protected
  16302. * @author Johannes Güntert, Nicola Asuni
  16303. * @since 2.1.002 (2008-02-12)
  16304. */
  16305. protected function _putjavascript() {
  16306. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  16307. return;
  16308. }
  16309. if (strpos($this->javascript, 'this.addField') > 0) {
  16310. if (!$this->ur['enabled']) {
  16311. //$this->setUserRights();
  16312. }
  16313. // the following two lines are used to avoid form fields duplication after saving
  16314. // The addField method only works when releasing user rights (UR3)
  16315. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  16316. $jsb = "getField('tcpdfdocsaved').value='saved';";
  16317. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  16318. }
  16319. $this->n_js = $this->_newobj();
  16320. $out = ' << /Names [';
  16321. if (!empty($this->javascript)) {
  16322. $out .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  16323. }
  16324. if (!empty($this->js_objects)) {
  16325. foreach ($this->js_objects as $key => $val) {
  16326. if ($val['onload']) {
  16327. $out .= ' (JS'.$key.') '.$key.' 0 R';
  16328. }
  16329. }
  16330. }
  16331. $out .= ' ] >>';
  16332. $out .= "\n".'endobj';
  16333. $this->_out($out);
  16334. // default Javascript object
  16335. if (!empty($this->javascript)) {
  16336. $obj_id = $this->_newobj();
  16337. $out = '<< /S /JavaScript';
  16338. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  16339. $out .= ' >>';
  16340. $out .= "\n".'endobj';
  16341. $this->_out($out);
  16342. }
  16343. // additional Javascript objects
  16344. if (!empty($this->js_objects)) {
  16345. foreach ($this->js_objects as $key => $val) {
  16346. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  16347. $this->_out($out);
  16348. }
  16349. }
  16350. }
  16351. /**
  16352. * Convert color to javascript color.
  16353. * @param $color (string) color name or "#RRGGBB"
  16354. * @protected
  16355. * @author Denis Van Nuffelen, Nicola Asuni
  16356. * @since 2.1.002 (2008-02-12)
  16357. */
  16358. protected function _JScolor($color) {
  16359. static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
  16360. if (substr($color,0,1) == '#') {
  16361. return sprintf("['RGB',%F,%F,%F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
  16362. }
  16363. if (!in_array($color,$aColors)) {
  16364. $this->Error('Invalid color: '.$color);
  16365. }
  16366. return 'color.'.$color;
  16367. }
  16368. /**
  16369. * Adds a javascript form field.
  16370. * @param $type (string) field type
  16371. * @param $name (string) field name
  16372. * @param $x (int) horizontal position
  16373. * @param $y (int) vertical position
  16374. * @param $w (int) width
  16375. * @param $h (int) height
  16376. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16377. * @protected
  16378. * @author Denis Van Nuffelen, Nicola Asuni
  16379. * @since 2.1.002 (2008-02-12)
  16380. */
  16381. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  16382. if ($this->rtl) {
  16383. $x = $x - $w;
  16384. }
  16385. // the followind avoid fields duplication after saving the document
  16386. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  16387. $k = $this->k;
  16388. $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%F,%F,%F,%F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
  16389. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  16390. while (list($key, $val) = each($prop)) {
  16391. if (strcmp(substr($key, -5), 'Color') == 0) {
  16392. $val = $this->_JScolor($val);
  16393. } else {
  16394. $val = "'".$val."'";
  16395. }
  16396. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  16397. }
  16398. if ($this->rtl) {
  16399. $this->x -= $w;
  16400. } else {
  16401. $this->x += $w;
  16402. }
  16403. $this->javascript .= '}';
  16404. }
  16405. // --- FORM FIELDS -----------------------------------------------------
  16406. /**
  16407. * Convert JavaScript form fields properties array to Annotation Properties array.
  16408. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16409. * @return array of annotation properties
  16410. * @protected
  16411. * @author Nicola Asuni
  16412. * @since 4.8.000 (2009-09-06)
  16413. */
  16414. protected function getAnnotOptFromJSProp($prop) {
  16415. if (isset($prop['aopt']) AND is_array($prop['aopt'])) {
  16416. // the annotation options area lready defined
  16417. return $prop['aopt'];
  16418. }
  16419. $opt = array(); // value to be returned
  16420. // alignment: Controls how the text is laid out within the text field.
  16421. if (isset($prop['alignment'])) {
  16422. switch ($prop['alignment']) {
  16423. case 'left': {
  16424. $opt['q'] = 0;
  16425. break;
  16426. }
  16427. case 'center': {
  16428. $opt['q'] = 1;
  16429. break;
  16430. }
  16431. case 'right': {
  16432. $opt['q'] = 2;
  16433. break;
  16434. }
  16435. default: {
  16436. $opt['q'] = ($this->rtl)?2:0;
  16437. break;
  16438. }
  16439. }
  16440. }
  16441. // lineWidth: Specifies the thickness of the border when stroking the perimeter of a field's rectangle.
  16442. if (isset($prop['lineWidth'])) {
  16443. $linewidth = intval($prop['lineWidth']);
  16444. } else {
  16445. $linewidth = 1;
  16446. }
  16447. // borderStyle: The border style for a field.
  16448. if (isset($prop['borderStyle'])) {
  16449. switch ($prop['borderStyle']) {
  16450. case 'border.d':
  16451. case 'dashed': {
  16452. $opt['border'] = array(0, 0, $linewidth, array(3, 2));
  16453. $opt['bs'] = array('w'=>$linewidth, 's'=>'D', 'd'=>array(3, 2));
  16454. break;
  16455. }
  16456. case 'border.b':
  16457. case 'beveled': {
  16458. $opt['border'] = array(0, 0, $linewidth);
  16459. $opt['bs'] = array('w'=>$linewidth, 's'=>'B');
  16460. break;
  16461. }
  16462. case 'border.i':
  16463. case 'inset': {
  16464. $opt['border'] = array(0, 0, $linewidth);
  16465. $opt['bs'] = array('w'=>$linewidth, 's'=>'I');
  16466. break;
  16467. }
  16468. case 'border.u':
  16469. case 'underline': {
  16470. $opt['border'] = array(0, 0, $linewidth);
  16471. $opt['bs'] = array('w'=>$linewidth, 's'=>'U');
  16472. break;
  16473. }
  16474. case 'border.s':
  16475. case 'solid': {
  16476. $opt['border'] = array(0, 0, $linewidth);
  16477. $opt['bs'] = array('w'=>$linewidth, 's'=>'S');
  16478. break;
  16479. }
  16480. default: {
  16481. break;
  16482. }
  16483. }
  16484. }
  16485. if (isset($prop['border']) AND is_array($prop['border'])) {
  16486. $opt['border'] = $prop['border'];
  16487. }
  16488. if (!isset($opt['mk'])) {
  16489. $opt['mk'] = array();
  16490. }
  16491. if (!isset($opt['mk']['if'])) {
  16492. $opt['mk']['if'] = array();
  16493. }
  16494. $opt['mk']['if']['a'] = array(0.5, 0.5);
  16495. // buttonAlignX: Controls how space is distributed from the left of the button face with respect to the icon.
  16496. if (isset($prop['buttonAlignX'])) {
  16497. $opt['mk']['if']['a'][0] = $prop['buttonAlignX'];
  16498. }
  16499. // buttonAlignY: Controls how unused space is distributed from the bottom of the button face with respect to the icon.
  16500. if (isset($prop['buttonAlignY'])) {
  16501. $opt['mk']['if']['a'][1] = $prop['buttonAlignY'];
  16502. }
  16503. // buttonFitBounds: If true, the extent to which the icon may be scaled is set to the bounds of the button field.
  16504. if (isset($prop['buttonFitBounds']) AND ($prop['buttonFitBounds'] == 'true')) {
  16505. $opt['mk']['if']['fb'] = true;
  16506. }
  16507. // buttonScaleHow: Controls how the icon is scaled (if necessary) to fit inside the button face.
  16508. if (isset($prop['buttonScaleHow'])) {
  16509. switch ($prop['buttonScaleHow']) {
  16510. case 'scaleHow.proportional': {
  16511. $opt['mk']['if']['s'] = 'P';
  16512. break;
  16513. }
  16514. case 'scaleHow.anamorphic': {
  16515. $opt['mk']['if']['s'] = 'A';
  16516. break;
  16517. }
  16518. }
  16519. }
  16520. // buttonScaleWhen: Controls when an icon is scaled to fit inside the button face.
  16521. if (isset($prop['buttonScaleWhen'])) {
  16522. switch ($prop['buttonScaleWhen']) {
  16523. case 'scaleWhen.always': {
  16524. $opt['mk']['if']['sw'] = 'A';
  16525. break;
  16526. }
  16527. case 'scaleWhen.never': {
  16528. $opt['mk']['if']['sw'] = 'N';
  16529. break;
  16530. }
  16531. case 'scaleWhen.tooBig': {
  16532. $opt['mk']['if']['sw'] = 'B';
  16533. break;
  16534. }
  16535. case 'scaleWhen.tooSmall': {
  16536. $opt['mk']['if']['sw'] = 'S';
  16537. break;
  16538. }
  16539. }
  16540. }
  16541. // buttonPosition: Controls how the text and the icon of the button are positioned with respect to each other within the button face.
  16542. if (isset($prop['buttonPosition'])) {
  16543. switch ($prop['buttonPosition']) {
  16544. case 0:
  16545. case 'position.textOnly': {
  16546. $opt['mk']['tp'] = 0;
  16547. break;
  16548. }
  16549. case 1:
  16550. case 'position.iconOnly': {
  16551. $opt['mk']['tp'] = 1;
  16552. break;
  16553. }
  16554. case 2:
  16555. case 'position.iconTextV': {
  16556. $opt['mk']['tp'] = 2;
  16557. break;
  16558. }
  16559. case 3:
  16560. case 'position.textIconV': {
  16561. $opt['mk']['tp'] = 3;
  16562. break;
  16563. }
  16564. case 4:
  16565. case 'position.iconTextH': {
  16566. $opt['mk']['tp'] = 4;
  16567. break;
  16568. }
  16569. case 5:
  16570. case 'position.textIconH': {
  16571. $opt['mk']['tp'] = 5;
  16572. break;
  16573. }
  16574. case 6:
  16575. case 'position.overlay': {
  16576. $opt['mk']['tp'] = 6;
  16577. break;
  16578. }
  16579. }
  16580. }
  16581. // fillColor: Specifies the background color for a field.
  16582. if (isset($prop['fillColor'])) {
  16583. if (is_array($prop['fillColor'])) {
  16584. $opt['mk']['bg'] = $prop['fillColor'];
  16585. } else {
  16586. $opt['mk']['bg'] = $this->convertHTMLColorToDec($prop['fillColor']);
  16587. }
  16588. }
  16589. // 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.
  16590. if (isset($prop['strokeColor'])) {
  16591. if (is_array($prop['strokeColor'])) {
  16592. $opt['mk']['bc'] = $prop['strokeColor'];
  16593. } else {
  16594. $opt['mk']['bc'] = $this->convertHTMLColorToDec($prop['strokeColor']);
  16595. }
  16596. }
  16597. // rotation: The rotation of a widget in counterclockwise increments.
  16598. if (isset($prop['rotation'])) {
  16599. $opt['mk']['r'] = $prop['rotation'];
  16600. }
  16601. // charLimit: Limits the number of characters that a user can type into a text field.
  16602. if (isset($prop['charLimit'])) {
  16603. $opt['maxlen'] = intval($prop['charLimit']);
  16604. }
  16605. if (!isset($ff)) {
  16606. $ff = 0; // default value
  16607. }
  16608. // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
  16609. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
  16610. $ff += 1 << 0;
  16611. }
  16612. // required: Specifies whether a field requires a value.
  16613. if (isset($prop['required']) AND ($prop['required'] == 'true')) {
  16614. $ff += 1 << 1;
  16615. }
  16616. // multiline: Controls how text is wrapped within the field.
  16617. if (isset($prop['multiline']) AND ($prop['multiline'] == 'true')) {
  16618. $ff += 1 << 12;
  16619. }
  16620. // password: Specifies whether the field should display asterisks when data is entered in the field.
  16621. if (isset($prop['password']) AND ($prop['password'] == 'true')) {
  16622. $ff += 1 << 13;
  16623. }
  16624. // NoToggleToOff: If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect.
  16625. if (isset($prop['NoToggleToOff']) AND ($prop['NoToggleToOff'] == 'true')) {
  16626. $ff += 1 << 14;
  16627. }
  16628. // Radio: If set, the field is a set of radio buttons.
  16629. if (isset($prop['Radio']) AND ($prop['Radio'] == 'true')) {
  16630. $ff += 1 << 15;
  16631. }
  16632. // Pushbutton: If set, the field is a pushbutton that does not retain a permanent value.
  16633. if (isset($prop['Pushbutton']) AND ($prop['Pushbutton'] == 'true')) {
  16634. $ff += 1 << 16;
  16635. }
  16636. // Combo: If set, the field is a combo box; if clear, the field is a list box.
  16637. if (isset($prop['Combo']) AND ($prop['Combo'] == 'true')) {
  16638. $ff += 1 << 17;
  16639. }
  16640. // editable: Controls whether a combo box is editable.
  16641. if (isset($prop['editable']) AND ($prop['editable'] == 'true')) {
  16642. $ff += 1 << 18;
  16643. }
  16644. // Sort: If set, the field's option items shall be sorted alphabetically.
  16645. if (isset($prop['Sort']) AND ($prop['Sort'] == 'true')) {
  16646. $ff += 1 << 19;
  16647. }
  16648. // fileSelect: If true, sets the file-select flag in the Options tab of the text field (Field is Used for File Selection).
  16649. if (isset($prop['fileSelect']) AND ($prop['fileSelect'] == 'true')) {
  16650. $ff += 1 << 20;
  16651. }
  16652. // multipleSelection: If true, indicates that a list box allows a multiple selection of items.
  16653. if (isset($prop['multipleSelection']) AND ($prop['multipleSelection'] == 'true')) {
  16654. $ff += 1 << 21;
  16655. }
  16656. // doNotSpellCheck: If true, spell checking is not performed on this editable text field.
  16657. if (isset($prop['doNotSpellCheck']) AND ($prop['doNotSpellCheck'] == 'true')) {
  16658. $ff += 1 << 22;
  16659. }
  16660. // doNotScroll: If true, the text field does not scroll and the user, therefore, is limited by the rectangular region designed for the field.
  16661. if (isset($prop['doNotScroll']) AND ($prop['doNotScroll'] == 'true')) {
  16662. $ff += 1 << 23;
  16663. }
  16664. // 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.
  16665. if (isset($prop['comb']) AND ($prop['comb'] == 'true')) {
  16666. $ff += 1 << 24;
  16667. }
  16668. // 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.
  16669. if (isset($prop['radiosInUnison']) AND ($prop['radiosInUnison'] == 'true')) {
  16670. $ff += 1 << 25;
  16671. }
  16672. // richText: If true, the field allows rich text formatting.
  16673. if (isset($prop['richText']) AND ($prop['richText'] == 'true')) {
  16674. $ff += 1 << 25;
  16675. }
  16676. // commitOnSelChange: Controls whether a field value is committed after a selection change.
  16677. if (isset($prop['commitOnSelChange']) AND ($prop['commitOnSelChange'] == 'true')) {
  16678. $ff += 1 << 26;
  16679. }
  16680. $opt['ff'] = $ff;
  16681. // defaultValue: The default value of a field - that is, the value that the field is set to when the form is reset.
  16682. if (isset($prop['defaultValue'])) {
  16683. $opt['dv'] = $prop['defaultValue'];
  16684. }
  16685. $f = 4; // default value for annotation flags
  16686. // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
  16687. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
  16688. $f += 1 << 6;
  16689. }
  16690. // display: Controls whether the field is hidden or visible on screen and in print.
  16691. if (isset($prop['display'])) {
  16692. if ($prop['display'] == 'display.visible') {
  16693. //
  16694. } elseif ($prop['display'] == 'display.hidden') {
  16695. $f += 1 << 1;
  16696. } elseif ($prop['display'] == 'display.noPrint') {
  16697. $f -= 1 << 2;
  16698. } elseif ($prop['display'] == 'display.noView') {
  16699. $f += 1 << 5;
  16700. }
  16701. }
  16702. $opt['f'] = $f;
  16703. // currentValueIndices: Reads and writes single or multiple values of a list box or combo box.
  16704. if (isset($prop['currentValueIndices']) AND is_array($prop['currentValueIndices'])) {
  16705. $opt['i'] = $prop['currentValueIndices'];
  16706. }
  16707. // value: The value of the field data that the user has entered.
  16708. if (isset($prop['value'])) {
  16709. if (is_array($prop['value'])) {
  16710. $opt['opt'] = array();
  16711. foreach ($prop['value'] AS $key => $optval) {
  16712. // exportValues: An array of strings representing the export values for the field.
  16713. if (isset($prop['exportValues'][$key])) {
  16714. $opt['opt'][$key] = array($prop['exportValues'][$key], $prop['value'][$key]);
  16715. } else {
  16716. $opt['opt'][$key] = $prop['value'][$key];
  16717. }
  16718. }
  16719. } else {
  16720. $opt['v'] = $prop['value'];
  16721. }
  16722. }
  16723. // richValue: This property specifies the text contents and formatting of a rich text field.
  16724. if (isset($prop['richValue'])) {
  16725. $opt['rv'] = $prop['richValue'];
  16726. }
  16727. // submitName: If nonempty, used during form submission instead of name. Only applicable if submitting in HTML format (that is, URL-encoded).
  16728. if (isset($prop['submitName'])) {
  16729. $opt['tm'] = $prop['submitName'];
  16730. }
  16731. // name: Fully qualified field name.
  16732. if (isset($prop['name'])) {
  16733. $opt['t'] = $prop['name'];
  16734. }
  16735. // userName: The user name (short description string) of the field.
  16736. if (isset($prop['userName'])) {
  16737. $opt['tu'] = $prop['userName'];
  16738. }
  16739. // highlight: Defines how a button reacts when a user clicks it.
  16740. if (isset($prop['highlight'])) {
  16741. switch ($prop['highlight']) {
  16742. case 'none':
  16743. case 'highlight.n': {
  16744. $opt['h'] = 'N';
  16745. break;
  16746. }
  16747. case 'invert':
  16748. case 'highlight.i': {
  16749. $opt['h'] = 'i';
  16750. break;
  16751. }
  16752. case 'push':
  16753. case 'highlight.p': {
  16754. $opt['h'] = 'P';
  16755. break;
  16756. }
  16757. case 'outline':
  16758. case 'highlight.o': {
  16759. $opt['h'] = 'O';
  16760. break;
  16761. }
  16762. }
  16763. }
  16764. // Unsupported options:
  16765. // - calcOrderIndex: Changes the calculation order of fields in the document.
  16766. // - delay: Delays the redrawing of a field's appearance.
  16767. // - defaultStyle: This property defines the default style attributes for the form field.
  16768. // - style: Allows the user to set the glyph style of a check box or radio button.
  16769. // - textColor, textFont, textSize
  16770. return $opt;
  16771. }
  16772. /**
  16773. * Set default properties for form fields.
  16774. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16775. * @public
  16776. * @author Nicola Asuni
  16777. * @since 4.8.000 (2009-09-06)
  16778. */
  16779. public function setFormDefaultProp($prop=array()) {
  16780. $this->default_form_prop = $prop;
  16781. }
  16782. /**
  16783. * Return the default properties for form fields.
  16784. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16785. * @public
  16786. * @author Nicola Asuni
  16787. * @since 4.8.000 (2009-09-06)
  16788. */
  16789. public function getFormDefaultProp() {
  16790. return $this->default_form_prop;
  16791. }
  16792. /**
  16793. * Creates a text field
  16794. * @param $name (string) field name
  16795. * @param $w (float) Width of the rectangle
  16796. * @param $h (float) Height of the rectangle
  16797. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16798. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16799. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16800. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16801. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16802. * @public
  16803. * @author Nicola Asuni
  16804. * @since 4.8.000 (2009-09-07)
  16805. */
  16806. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  16807. if ($x === '') {
  16808. $x = $this->x;
  16809. }
  16810. if ($y === '') {
  16811. $y = $this->y;
  16812. }
  16813. // check page for no-write regions and adapt page margins if necessary
  16814. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  16815. if ($js) {
  16816. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  16817. return;
  16818. }
  16819. // get default style
  16820. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16821. // get annotation data
  16822. $popt = $this->getAnnotOptFromJSProp($prop);
  16823. // set default appearance stream
  16824. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  16825. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  16826. $popt['da'] = $fontstyle;
  16827. // build appearance stream
  16828. $popt['ap'] = array();
  16829. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  16830. $text = '';
  16831. if (isset($prop['value']) AND !empty($prop['value'])) {
  16832. $text = $prop['value'];
  16833. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  16834. $text = $opt['v'];
  16835. }
  16836. $tmpid = $this->startTemplate($w, $h, false);
  16837. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  16838. $this->endTemplate();
  16839. --$this->n;
  16840. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  16841. unset($this->xobjects[$tmpid]);
  16842. $popt['ap']['n'] .= 'Q EMC';
  16843. // merge options
  16844. $opt = array_merge($popt, $opt);
  16845. // remove some conflicting options
  16846. unset($opt['bs']);
  16847. // set remaining annotation data
  16848. $opt['Subtype'] = 'Widget';
  16849. $opt['ft'] = 'Tx';
  16850. $opt['t'] = $name;
  16851. // Additional annotation's parameters (check _putannotsobj() method):
  16852. //$opt['f']
  16853. //$opt['as']
  16854. //$opt['bs']
  16855. //$opt['be']
  16856. //$opt['c']
  16857. //$opt['border']
  16858. //$opt['h']
  16859. //$opt['mk'];
  16860. //$opt['mk']['r']
  16861. //$opt['mk']['bc'];
  16862. //$opt['mk']['bg'];
  16863. unset($opt['mk']['ca']);
  16864. unset($opt['mk']['rc']);
  16865. unset($opt['mk']['ac']);
  16866. unset($opt['mk']['i']);
  16867. unset($opt['mk']['ri']);
  16868. unset($opt['mk']['ix']);
  16869. unset($opt['mk']['if']);
  16870. //$opt['mk']['if']['sw'];
  16871. //$opt['mk']['if']['s'];
  16872. //$opt['mk']['if']['a'];
  16873. //$opt['mk']['if']['fb'];
  16874. unset($opt['mk']['tp']);
  16875. //$opt['tu']
  16876. //$opt['tm']
  16877. //$opt['ff']
  16878. //$opt['v']
  16879. //$opt['dv']
  16880. //$opt['a']
  16881. //$opt['aa']
  16882. //$opt['q']
  16883. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  16884. if ($this->rtl) {
  16885. $this->x -= $w;
  16886. } else {
  16887. $this->x += $w;
  16888. }
  16889. }
  16890. /**
  16891. * Creates a RadioButton field.
  16892. * @param $name (string) Field name.
  16893. * @param $w (int) Width or the radio button.
  16894. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16895. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16896. * @param $onvalue (string) Value to be returned if selected.
  16897. * @param $checked (boolean) Define the initial state.
  16898. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  16899. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  16900. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  16901. * @public
  16902. * @author Nicola Asuni
  16903. * @since 4.8.000 (2009-09-07)
  16904. */
  16905. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  16906. if ($x === '') {
  16907. $x = $this->x;
  16908. }
  16909. if ($y === '') {
  16910. $y = $this->y;
  16911. }
  16912. // check page for no-write regions and adapt page margins if necessary
  16913. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  16914. if ($js) {
  16915. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  16916. return;
  16917. }
  16918. if ($this->empty_string($onvalue)) {
  16919. $onvalue = 'On';
  16920. }
  16921. if ($checked) {
  16922. $defval = $onvalue;
  16923. } else {
  16924. $defval = 'Off';
  16925. }
  16926. // set font
  16927. $font = 'zapfdingbats';
  16928. if ($this->pdfa_mode) {
  16929. // all fonts must be embedded
  16930. $font = 'pdfa'.$font;
  16931. }
  16932. $this->AddFont($font);
  16933. $tmpfont = $this->getFontBuffer($font);
  16934. // set data for parent group
  16935. if (!isset($this->radiobutton_groups[$this->page])) {
  16936. $this->radiobutton_groups[$this->page] = array();
  16937. }
  16938. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  16939. $this->radiobutton_groups[$this->page][$name] = array();
  16940. ++$this->n;
  16941. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  16942. $this->radio_groups[] = $this->n;
  16943. }
  16944. $kid = ($this->n + 1);
  16945. // save object ID to be added on Kids entry on parent object
  16946. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  16947. // get default style
  16948. $prop = array_merge($this->getFormDefaultProp(), $prop);
  16949. $prop['NoToggleToOff'] = 'true';
  16950. $prop['Radio'] = 'true';
  16951. $prop['borderStyle'] = 'inset';
  16952. // get annotation data
  16953. $popt = $this->getAnnotOptFromJSProp($prop);
  16954. // set additional default options
  16955. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  16956. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  16957. $popt['da'] = $fontstyle;
  16958. // build appearance stream
  16959. $popt['ap'] = array();
  16960. $popt['ap']['n'] = array();
  16961. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  16962. $popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(108).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  16963. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(109).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  16964. if (!isset($popt['mk'])) {
  16965. $popt['mk'] = array();
  16966. }
  16967. $popt['mk']['ca'] = '(l)';
  16968. // merge options
  16969. $opt = array_merge($popt, $opt);
  16970. // set remaining annotation data
  16971. $opt['Subtype'] = 'Widget';
  16972. $opt['ft'] = 'Btn';
  16973. if ($checked) {
  16974. $opt['v'] = array('/'.$onvalue);
  16975. $opt['as'] = $onvalue;
  16976. } else {
  16977. $opt['as'] = 'Off';
  16978. }
  16979. // store readonly flag
  16980. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  16981. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  16982. }
  16983. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  16984. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  16985. if ($this->rtl) {
  16986. $this->x -= $w;
  16987. } else {
  16988. $this->x += $w;
  16989. }
  16990. }
  16991. /**
  16992. * Creates a List-box field
  16993. * @param $name (string) field name
  16994. * @param $w (int) width
  16995. * @param $h (int) height
  16996. * @param $values (array) array containing the list of values.
  16997. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  16998. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  16999. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  17000. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  17001. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  17002. * @public
  17003. * @author Nicola Asuni
  17004. * @since 4.8.000 (2009-09-07)
  17005. */
  17006. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  17007. if ($x === '') {
  17008. $x = $this->x;
  17009. }
  17010. if ($y === '') {
  17011. $y = $this->y;
  17012. }
  17013. // check page for no-write regions and adapt page margins if necessary
  17014. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  17015. if ($js) {
  17016. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  17017. $s = '';
  17018. foreach ($values as $value) {
  17019. if (is_array($value)) {
  17020. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  17021. } else {
  17022. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  17023. }
  17024. }
  17025. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  17026. return;
  17027. }
  17028. // get default style
  17029. $prop = array_merge($this->getFormDefaultProp(), $prop);
  17030. // get annotation data
  17031. $popt = $this->getAnnotOptFromJSProp($prop);
  17032. // set additional default values
  17033. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  17034. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  17035. $popt['da'] = $fontstyle;
  17036. // build appearance stream
  17037. $popt['ap'] = array();
  17038. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  17039. $text = '';
  17040. foreach($values as $item) {
  17041. if (is_array($item)) {
  17042. $text .= $item[1]."\n";
  17043. } else {
  17044. $text .= $item."\n";
  17045. }
  17046. }
  17047. $tmpid = $this->startTemplate($w, $h, false);
  17048. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  17049. $this->endTemplate();
  17050. --$this->n;
  17051. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  17052. unset($this->xobjects[$tmpid]);
  17053. $popt['ap']['n'] .= 'Q EMC';
  17054. // merge options
  17055. $opt = array_merge($popt, $opt);
  17056. // set remaining annotation data
  17057. $opt['Subtype'] = 'Widget';
  17058. $opt['ft'] = 'Ch';
  17059. $opt['t'] = $name;
  17060. $opt['opt'] = $values;
  17061. unset($opt['mk']['ca']);
  17062. unset($opt['mk']['rc']);
  17063. unset($opt['mk']['ac']);
  17064. unset($opt['mk']['i']);
  17065. unset($opt['mk']['ri']);
  17066. unset($opt['mk']['ix']);
  17067. unset($opt['mk']['if']);
  17068. unset($opt['mk']['tp']);
  17069. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  17070. if ($this->rtl) {
  17071. $this->x -= $w;
  17072. } else {
  17073. $this->x += $w;
  17074. }
  17075. }
  17076. /**
  17077. * Creates a Combo-box field
  17078. * @param $name (string) field name
  17079. * @param $w (int) width
  17080. * @param $h (int) height
  17081. * @param $values (array) array containing the list of values.
  17082. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  17083. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  17084. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  17085. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  17086. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  17087. * @public
  17088. * @author Nicola Asuni
  17089. * @since 4.8.000 (2009-09-07)
  17090. */
  17091. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  17092. if ($x === '') {
  17093. $x = $this->x;
  17094. }
  17095. if ($y === '') {
  17096. $y = $this->y;
  17097. }
  17098. // check page for no-write regions and adapt page margins if necessary
  17099. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  17100. if ($js) {
  17101. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  17102. $s = '';
  17103. foreach ($values as $value) {
  17104. if (is_array($value)) {
  17105. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  17106. } else {
  17107. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  17108. }
  17109. }
  17110. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  17111. return;
  17112. }
  17113. // get default style
  17114. $prop = array_merge($this->getFormDefaultProp(), $prop);
  17115. $prop['Combo'] = true;
  17116. // get annotation data
  17117. $popt = $this->getAnnotOptFromJSProp($prop);
  17118. // set additional default options
  17119. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  17120. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  17121. $popt['da'] = $fontstyle;
  17122. // build appearance stream
  17123. $popt['ap'] = array();
  17124. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  17125. $text = '';
  17126. foreach($values as $item) {
  17127. if (is_array($item)) {
  17128. $text .= $item[1]."\n";
  17129. } else {
  17130. $text .= $item."\n";
  17131. }
  17132. }
  17133. $tmpid = $this->startTemplate($w, $h, false);
  17134. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  17135. $this->endTemplate();
  17136. --$this->n;
  17137. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  17138. unset($this->xobjects[$tmpid]);
  17139. $popt['ap']['n'] .= 'Q EMC';
  17140. // merge options
  17141. $opt = array_merge($popt, $opt);
  17142. // set remaining annotation data
  17143. $opt['Subtype'] = 'Widget';
  17144. $opt['ft'] = 'Ch';
  17145. $opt['t'] = $name;
  17146. $opt['opt'] = $values;
  17147. unset($opt['mk']['ca']);
  17148. unset($opt['mk']['rc']);
  17149. unset($opt['mk']['ac']);
  17150. unset($opt['mk']['i']);
  17151. unset($opt['mk']['ri']);
  17152. unset($opt['mk']['ix']);
  17153. unset($opt['mk']['if']);
  17154. unset($opt['mk']['tp']);
  17155. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  17156. if ($this->rtl) {
  17157. $this->x -= $w;
  17158. } else {
  17159. $this->x += $w;
  17160. }
  17161. }
  17162. /**
  17163. * Creates a CheckBox field
  17164. * @param $name (string) field name
  17165. * @param $w (int) width
  17166. * @param $checked (boolean) define the initial state.
  17167. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  17168. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  17169. * @param $onvalue (string) value to be returned if selected.
  17170. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  17171. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  17172. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  17173. * @public
  17174. * @author Nicola Asuni
  17175. * @since 4.8.000 (2009-09-07)
  17176. */
  17177. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  17178. if ($x === '') {
  17179. $x = $this->x;
  17180. }
  17181. if ($y === '') {
  17182. $y = $this->y;
  17183. }
  17184. // check page for no-write regions and adapt page margins if necessary
  17185. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  17186. if ($js) {
  17187. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  17188. return;
  17189. }
  17190. if (!isset($prop['value'])) {
  17191. $prop['value'] = array('Yes');
  17192. }
  17193. // get default style
  17194. $prop = array_merge($this->getFormDefaultProp(), $prop);
  17195. $prop['borderStyle'] = 'inset';
  17196. // get annotation data
  17197. $popt = $this->getAnnotOptFromJSProp($prop);
  17198. // set additional default options
  17199. $font = 'zapfdingbats';
  17200. if ($this->pdfa_mode) {
  17201. // all fonts must be embedded
  17202. $font = 'pdfa'.$font;
  17203. }
  17204. $this->AddFont($font);
  17205. $tmpfont = $this->getFontBuffer($font);
  17206. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  17207. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  17208. $popt['da'] = $fontstyle;
  17209. // build appearance stream
  17210. $popt['ap'] = array();
  17211. $popt['ap']['n'] = array();
  17212. $fy = ((($tmpfont['desc']['Ascent'] + $tmpfont['desc']['Descent']) * $this->FontSizePt) / (1000 * $this->k));
  17213. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  17214. $popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(110).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  17215. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(111).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, 0, $fy);
  17216. // merge options
  17217. $opt = array_merge($popt, $opt);
  17218. // set remaining annotation data
  17219. $opt['Subtype'] = 'Widget';
  17220. $opt['ft'] = 'Btn';
  17221. $opt['t'] = $name;
  17222. if ($this->empty_string($onvalue)) {
  17223. $onvalue = 'Yes';
  17224. }
  17225. $opt['opt'] = array($onvalue);
  17226. if ($checked) {
  17227. $opt['v'] = array('/Yes');
  17228. $opt['as'] = 'Yes';
  17229. } else {
  17230. $opt['v'] = array('/Off');
  17231. $opt['as'] = 'Off';
  17232. }
  17233. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  17234. if ($this->rtl) {
  17235. $this->x -= $w;
  17236. } else {
  17237. $this->x += $w;
  17238. }
  17239. }
  17240. /**
  17241. * Creates a button field
  17242. * @param $name (string) field name
  17243. * @param $w (int) width
  17244. * @param $h (int) height
  17245. * @param $caption (string) caption.
  17246. * @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.
  17247. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  17248. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  17249. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  17250. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  17251. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  17252. * @public
  17253. * @author Nicola Asuni
  17254. * @since 4.8.000 (2009-09-07)
  17255. */
  17256. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  17257. if ($x === '') {
  17258. $x = $this->x;
  17259. }
  17260. if ($y === '') {
  17261. $y = $this->y;
  17262. }
  17263. // check page for no-write regions and adapt page margins if necessary
  17264. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  17265. if ($js) {
  17266. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  17267. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  17268. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  17269. $this->javascript .= 'f'.$name.".highlight='push';\n";
  17270. $this->javascript .= 'f'.$name.".print=false;\n";
  17271. return;
  17272. }
  17273. // get default style
  17274. $prop = array_merge($this->getFormDefaultProp(), $prop);
  17275. $prop['Pushbutton'] = 'true';
  17276. $prop['highlight'] = 'push';
  17277. $prop['display'] = 'display.noPrint';
  17278. // get annotation data
  17279. $popt = $this->getAnnotOptFromJSProp($prop);
  17280. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  17281. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  17282. $popt['da'] = $fontstyle;
  17283. // build appearance stream
  17284. $popt['ap'] = array();
  17285. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  17286. $tmpid = $this->startTemplate($w, $h, false);
  17287. $bw = (2 / $this->k); // border width
  17288. $border = array(
  17289. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  17290. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  17291. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  17292. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  17293. $this->SetFillColor(204);
  17294. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  17295. $this->endTemplate();
  17296. --$this->n;
  17297. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  17298. unset($this->xobjects[$tmpid]);
  17299. $popt['ap']['n'] .= 'Q EMC';
  17300. // set additional default options
  17301. if (!isset($popt['mk'])) {
  17302. $popt['mk'] = array();
  17303. }
  17304. $ann_obj_id = ($this->n + 1);
  17305. if (!empty($action) AND !is_array($action)) {
  17306. $ann_obj_id = ($this->n + 2);
  17307. }
  17308. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  17309. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  17310. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  17311. // merge options
  17312. $opt = array_merge($popt, $opt);
  17313. // set remaining annotation data
  17314. $opt['Subtype'] = 'Widget';
  17315. $opt['ft'] = 'Btn';
  17316. $opt['t'] = $caption;
  17317. $opt['v'] = $name;
  17318. if (!empty($action)) {
  17319. if (is_array($action)) {
  17320. // form action options as on section 12.7.5 of PDF32000_2008.
  17321. $opt['aa'] = '/D <<';
  17322. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  17323. foreach ($action AS $key => $val) {
  17324. if (($key == 'S') AND in_array($val, $bmode)) {
  17325. $opt['aa'] .= ' /S /'.$val;
  17326. } elseif (($key == 'F') AND (!empty($val))) {
  17327. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  17328. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  17329. $opt['aa'] .= ' /Fields [';
  17330. foreach ($val AS $field) {
  17331. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  17332. }
  17333. $opt['aa'] .= ']';
  17334. } elseif (($key == 'Flags')) {
  17335. $ff = 0;
  17336. if (is_array($val)) {
  17337. foreach ($val AS $flag) {
  17338. switch ($flag) {
  17339. case 'Include/Exclude': {
  17340. $ff += 1 << 0;
  17341. break;
  17342. }
  17343. case 'IncludeNoValueFields': {
  17344. $ff += 1 << 1;
  17345. break;
  17346. }
  17347. case 'ExportFormat': {
  17348. $ff += 1 << 2;
  17349. break;
  17350. }
  17351. case 'GetMethod': {
  17352. $ff += 1 << 3;
  17353. break;
  17354. }
  17355. case 'SubmitCoordinates': {
  17356. $ff += 1 << 4;
  17357. break;
  17358. }
  17359. case 'XFDF': {
  17360. $ff += 1 << 5;
  17361. break;
  17362. }
  17363. case 'IncludeAppendSaves': {
  17364. $ff += 1 << 6;
  17365. break;
  17366. }
  17367. case 'IncludeAnnotations': {
  17368. $ff += 1 << 7;
  17369. break;
  17370. }
  17371. case 'SubmitPDF': {
  17372. $ff += 1 << 8;
  17373. break;
  17374. }
  17375. case 'CanonicalFormat': {
  17376. $ff += 1 << 9;
  17377. break;
  17378. }
  17379. case 'ExclNonUserAnnots': {
  17380. $ff += 1 << 10;
  17381. break;
  17382. }
  17383. case 'ExclFKey': {
  17384. $ff += 1 << 11;
  17385. break;
  17386. }
  17387. case 'EmbedForm': {
  17388. $ff += 1 << 13;
  17389. break;
  17390. }
  17391. }
  17392. }
  17393. } else {
  17394. $ff = intval($val);
  17395. }
  17396. $opt['aa'] .= ' /Flags '.$ff;
  17397. }
  17398. }
  17399. $opt['aa'] .= ' >>';
  17400. } else {
  17401. // Javascript action or raw action command
  17402. $js_obj_id = $this->addJavascriptObject($action);
  17403. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  17404. }
  17405. }
  17406. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  17407. if ($this->rtl) {
  17408. $this->x -= $w;
  17409. } else {
  17410. $this->x += $w;
  17411. }
  17412. }
  17413. // --- END FORMS FIELDS ------------------------------------------------
  17414. /**
  17415. * Add certification signature (DocMDP or UR3)
  17416. * You can set only one signature type
  17417. * @protected
  17418. * @author Nicola Asuni
  17419. * @since 4.6.008 (2009-05-07)
  17420. */
  17421. protected function _putsignature() {
  17422. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  17423. return;
  17424. }
  17425. $sigobjid = ($this->sig_obj_id + 1);
  17426. $out = $this->_getobj($sigobjid)."\n";
  17427. $out .= '<< /Type /Sig';
  17428. $out .= ' /Filter /Adobe.PPKLite';
  17429. $out .= ' /SubFilter /adbe.pkcs7.detached';
  17430. $out .= ' '.$this->byterange_string;
  17431. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  17432. $out .= ' /Reference ['; // array of signature reference dictionaries
  17433. $out .= ' << /Type /SigRef';
  17434. if ($this->signature_data['cert_type'] > 0) {
  17435. $out .= ' /TransformMethod /DocMDP';
  17436. $out .= ' /TransformParams <<';
  17437. $out .= ' /Type /TransformParams';
  17438. $out .= ' /P '.$this->signature_data['cert_type'];
  17439. $out .= ' /V /1.2';
  17440. } else {
  17441. $out .= ' /TransformMethod /UR3';
  17442. $out .= ' /TransformParams <<';
  17443. $out .= ' /Type /TransformParams';
  17444. $out .= ' /V /2.2';
  17445. if (!$this->empty_string($this->ur['document'])) {
  17446. $out .= ' /Document['.$this->ur['document'].']';
  17447. }
  17448. if (!$this->empty_string($this->ur['form'])) {
  17449. $out .= ' /Form['.$this->ur['form'].']';
  17450. }
  17451. if (!$this->empty_string($this->ur['signature'])) {
  17452. $out .= ' /Signature['.$this->ur['signature'].']';
  17453. }
  17454. if (!$this->empty_string($this->ur['annots'])) {
  17455. $out .= ' /Annots['.$this->ur['annots'].']';
  17456. }
  17457. if (!$this->empty_string($this->ur['ef'])) {
  17458. $out .= ' /EF['.$this->ur['ef'].']';
  17459. }
  17460. if (!$this->empty_string($this->ur['formex'])) {
  17461. $out .= ' /FormEX['.$this->ur['formex'].']';
  17462. }
  17463. }
  17464. $out .= ' >>'; // close TransformParams
  17465. // optional digest data (values must be calculated and replaced later)
  17466. //$out .= ' /Data ********** 0 R';
  17467. //$out .= ' /DigestMethod/MD5';
  17468. //$out .= ' /DigestLocation[********** 34]';
  17469. //$out .= ' /DigestValue<********************************>';
  17470. $out .= ' >>';
  17471. $out .= ' ]'; // end of reference
  17472. if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
  17473. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  17474. }
  17475. if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
  17476. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  17477. }
  17478. if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
  17479. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  17480. }
  17481. if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
  17482. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  17483. }
  17484. $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
  17485. $out .= ' >>';
  17486. $out .= "\n".'endobj';
  17487. $this->_out($out);
  17488. }
  17489. /**
  17490. * Set User's Rights for PDF Reader
  17491. * WARNING: This is experimental and currently do not work.
  17492. * Check the PDF Reference 8.7.1 Transform Methods,
  17493. * Table 8.105 Entries in the UR transform parameters dictionary
  17494. * @param $enable (boolean) if true enable user's rights on PDF reader
  17495. * @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.
  17496. * @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.
  17497. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  17498. * @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.
  17499. * @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
  17500. Names specifying additional embedded-files-related usage rights for the document.
  17501. * @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.
  17502. * @public
  17503. * @author Nicola Asuni
  17504. * @since 2.9.000 (2008-03-26)
  17505. */
  17506. public function setUserRights(
  17507. $enable=true,
  17508. $document='/FullSave',
  17509. $annots='/Create/Delete/Modify/Copy/Import/Export',
  17510. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  17511. $signature='/Modify',
  17512. $ef='/Create/Delete/Modify/Import',
  17513. $formex='') {
  17514. $this->ur['enabled'] = $enable;
  17515. $this->ur['document'] = $document;
  17516. $this->ur['annots'] = $annots;
  17517. $this->ur['form'] = $form;
  17518. $this->ur['signature'] = $signature;
  17519. $this->ur['ef'] = $ef;
  17520. $this->ur['formex'] = $formex;
  17521. if (!$this->sign) {
  17522. $this->setSignature('', '', '', '', 0, array());
  17523. }
  17524. }
  17525. /**
  17526. * Enable document signature (requires the OpenSSL Library).
  17527. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  17528. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  17529. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  17530. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  17531. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  17532. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  17533. * @param $private_key_password (string) password
  17534. * @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.
  17535. * @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.
  17536. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  17537. * @public
  17538. * @author Nicola Asuni
  17539. * @since 4.6.005 (2009-04-24)
  17540. */
  17541. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
  17542. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  17543. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  17544. // to convert pfx certificate to pem: openssl
  17545. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  17546. $this->sign = true;
  17547. ++$this->n;
  17548. $this->sig_obj_id = $this->n; // signature widget
  17549. ++$this->n; // signature object ($this->sig_obj_id + 1)
  17550. $this->signature_data = array();
  17551. if (strlen($signing_cert) == 0) {
  17552. $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.crt';
  17553. $private_key_password = 'tcpdfdemo';
  17554. }
  17555. if (strlen($private_key) == 0) {
  17556. $private_key = $signing_cert;
  17557. }
  17558. $this->signature_data['signcert'] = $signing_cert;
  17559. $this->signature_data['privkey'] = $private_key;
  17560. $this->signature_data['password'] = $private_key_password;
  17561. $this->signature_data['extracerts'] = $extracerts;
  17562. $this->signature_data['cert_type'] = $cert_type;
  17563. $this->signature_data['info'] = $info;
  17564. }
  17565. /**
  17566. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  17567. * @param $x (float) Abscissa of the upper-left corner.
  17568. * @param $y (float) Ordinate of the upper-left corner.
  17569. * @param $w (float) Width of the signature area.
  17570. * @param $h (float) Height of the signature area.
  17571. * @param $page (int) option page number (if < 0 the current page is used).
  17572. * @public
  17573. * @author Nicola Asuni
  17574. * @since 5.3.011 (2010-06-17)
  17575. */
  17576. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) {
  17577. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page);
  17578. }
  17579. /**
  17580. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  17581. * @param $x (float) Abscissa of the upper-left corner.
  17582. * @param $y (float) Ordinate of the upper-left corner.
  17583. * @param $w (float) Width of the signature area.
  17584. * @param $h (float) Height of the signature area.
  17585. * @param $page (int) option page number (if < 0 the current page is used).
  17586. * @public
  17587. * @author Nicola Asuni
  17588. * @since 5.9.101 (2011-07-06)
  17589. */
  17590. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) {
  17591. ++$this->n;
  17592. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page);
  17593. }
  17594. /**
  17595. * Get the array that defines the signature appearance (page and rectangle coordinates).
  17596. * @param $x (float) Abscissa of the upper-left corner.
  17597. * @param $y (float) Ordinate of the upper-left corner.
  17598. * @param $w (float) Width of the signature area.
  17599. * @param $h (float) Height of the signature area.
  17600. * @param $page (int) option page number (if < 0 the current page is used).
  17601. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  17602. * @protected
  17603. * @author Nicola Asuni
  17604. * @since 5.9.101 (2011-07-06)
  17605. */
  17606. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1) {
  17607. $sigapp = array();
  17608. if (($page < 1) OR ($page > $this->numpages)) {
  17609. $sigapp['page'] = $this->page;
  17610. } else {
  17611. $sigapp['page'] = intval($page);
  17612. }
  17613. $a = $x * $this->k;
  17614. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  17615. $c = $w * $this->k;
  17616. $d = $h * $this->k;
  17617. $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
  17618. return $sigapp;
  17619. }
  17620. /**
  17621. * Create a new page group.
  17622. * NOTE: call this function before calling AddPage()
  17623. * @param $page (int) starting group page (leave empty for next page).
  17624. * @public
  17625. * @since 3.0.000 (2008-03-27)
  17626. */
  17627. public function startPageGroup($page='') {
  17628. if (empty($page)) {
  17629. $page = $this->page + 1;
  17630. }
  17631. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  17632. }
  17633. /**
  17634. * This method is DEPRECATED and doesn't have any effect.
  17635. * Please remove any reference to this method.
  17636. * @param $s (string) Empty parameter.
  17637. * @deprecated deprecated since version 5.9.089 (2011-06-13)
  17638. * @public
  17639. */
  17640. public function AliasNbPages($s='') {}
  17641. /**
  17642. * This method is DEPRECATED and doesn't have any effect.
  17643. * Please remove any reference to this method.
  17644. * @param $s (string) Empty parameter.
  17645. * @deprecated deprecated since version 5.9.089 (2011-06-13)
  17646. * @public
  17647. */
  17648. public function AliasNumPage($s='') {}
  17649. /**
  17650. * Set the starting page number.
  17651. * @param $num (int) Starting page number.
  17652. * @since 5.9.093 (2011-06-16)
  17653. * @public
  17654. */
  17655. public function setStartingPageNumber($num=1) {
  17656. $this->starting_page_number = max(0, intval($num));
  17657. }
  17658. /**
  17659. * Returns the string alias used right align page numbers.
  17660. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  17661. * @return string
  17662. * @since 5.9.099 (2011-06-27)
  17663. * @public
  17664. */
  17665. public function getAliasRightShift() {
  17666. // calculate aproximatively the ratio between widths of aliases and replacements.
  17667. $ref = '{'.$this->alias_right_shift.'}{'.$this->alias_tot_pages.'}{'.$this->alias_num_page.'}';
  17668. $rep = str_repeat(' ', $this->GetNumChars($ref));
  17669. $wdiff = max(1, ($this->GetStringWidth($ref) / $this->GetStringWidth($rep)));
  17670. $sdiff = sprintf('%F', $wdiff);
  17671. $alias = $this->alias_right_shift.$sdiff.'}';
  17672. if ($this->isUnicodeFont()) {
  17673. $alias = '{'.$alias;
  17674. }
  17675. return $alias;
  17676. }
  17677. /**
  17678. * Returns the string alias used for the total number of pages.
  17679. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17680. * This alias will be replaced by the total number of pages in the document.
  17681. * @return string
  17682. * @since 4.0.018 (2008-08-08)
  17683. * @public
  17684. */
  17685. public function getAliasNbPages() {
  17686. if ($this->isUnicodeFont()) {
  17687. return '{'.$this->alias_tot_pages.'}';
  17688. }
  17689. return $this->alias_tot_pages;
  17690. }
  17691. /**
  17692. * Returns the string alias used for the page number.
  17693. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17694. * This alias will be replaced by the page number.
  17695. * @return string
  17696. * @since 4.5.000 (2009-01-02)
  17697. * @public
  17698. */
  17699. public function getAliasNumPage() {
  17700. if ($this->isUnicodeFont()) {
  17701. return '{'.$this->alias_num_page.'}';
  17702. }
  17703. return $this->alias_num_page;
  17704. }
  17705. /**
  17706. * Return the alias for the total number of pages in the current page group.
  17707. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17708. * This alias will be replaced by the total number of pages in this group.
  17709. * @return alias of the current page group
  17710. * @public
  17711. * @since 3.0.000 (2008-03-27)
  17712. */
  17713. public function getPageGroupAlias() {
  17714. if ($this->isUnicodeFont()) {
  17715. return '{'.$this->alias_group_tot_pages.'}';
  17716. }
  17717. return $this->alias_group_tot_pages;
  17718. }
  17719. /**
  17720. * Return the alias for the page number on the current page group.
  17721. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  17722. * This alias will be replaced by the page number (relative to the belonging group).
  17723. * @return alias of the current page group
  17724. * @public
  17725. * @since 4.5.000 (2009-01-02)
  17726. */
  17727. public function getPageNumGroupAlias() {
  17728. if ($this->isUnicodeFont()) {
  17729. return '{'.$this->alias_group_num_page.'}';
  17730. }
  17731. return $this->alias_group_num_page;
  17732. }
  17733. /**
  17734. * Return the current page in the group.
  17735. * @return current page in the group
  17736. * @public
  17737. * @since 3.0.000 (2008-03-27)
  17738. */
  17739. public function getGroupPageNo() {
  17740. return $this->pagegroups[$this->currpagegroup];
  17741. }
  17742. /**
  17743. * Returns the current group page number formatted as a string.
  17744. * @public
  17745. * @since 4.3.003 (2008-11-18)
  17746. * @see PaneNo(), formatPageNumber()
  17747. */
  17748. public function getGroupPageNoFormatted() {
  17749. return $this->formatPageNumber($this->getGroupPageNo());
  17750. }
  17751. /**
  17752. * Format the page numbers.
  17753. * This method can be overriden for custom formats.
  17754. * @param $num (int) page number
  17755. * @protected
  17756. * @since 4.2.005 (2008-11-06)
  17757. */
  17758. protected function formatPageNumber($num) {
  17759. return number_format((float)$num, 0, '', '.');
  17760. }
  17761. /**
  17762. * Format the page numbers on the Table Of Content.
  17763. * This method can be overriden for custom formats.
  17764. * @param $num (int) page number
  17765. * @protected
  17766. * @since 4.5.001 (2009-01-04)
  17767. * @see addTOC(), addHTMLTOC()
  17768. */
  17769. protected function formatTOCPageNumber($num) {
  17770. return number_format((float)$num, 0, '', '.');
  17771. }
  17772. /**
  17773. * Returns the current page number formatted as a string.
  17774. * @public
  17775. * @since 4.2.005 (2008-11-06)
  17776. * @see PaneNo(), formatPageNumber()
  17777. */
  17778. public function PageNoFormatted() {
  17779. return $this->formatPageNumber($this->PageNo());
  17780. }
  17781. /**
  17782. * Put pdf layers.
  17783. * @protected
  17784. * @since 3.0.000 (2008-03-27)
  17785. */
  17786. protected function _putocg() {
  17787. if (empty($this->pdflayers)) {
  17788. return;
  17789. }
  17790. foreach ($this->pdflayers as $key => $layer) {
  17791. $this->pdflayers[$key]['objid'] = $this->_newobj();
  17792. $out = '<< /Type /OCG';
  17793. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  17794. $out .= ' /Usage <<';
  17795. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  17796. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  17797. $out .= ' >> >>';
  17798. $out .= "\n".'endobj';
  17799. $this->_out($out);
  17800. }
  17801. }
  17802. /**
  17803. * Start a new pdf layer.
  17804. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  17805. * @param $print (boolean) Set to true to print this layer.
  17806. * @param $view (boolean) Set to true to view this layer.
  17807. * @public
  17808. * @since 5.9.102 (2011-07-13)
  17809. */
  17810. public function startLayer($name='', $print=true, $view=true) {
  17811. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  17812. if (empty($name)) {
  17813. $name = $layer;
  17814. } else {
  17815. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  17816. }
  17817. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view);
  17818. $this->openMarkedContent = true;
  17819. $this->_out('/OC /'.$layer.' BDC');
  17820. }
  17821. /**
  17822. * End the current PDF layer.
  17823. * @public
  17824. * @since 5.9.102 (2011-07-13)
  17825. */
  17826. public function endLayer() {
  17827. if ($this->openMarkedContent) {
  17828. // close existing open marked-content layer
  17829. $this->_out('EMC');
  17830. $this->openMarkedContent = false;
  17831. }
  17832. }
  17833. /**
  17834. * Set the visibility of the successive elements.
  17835. * This can be useful, for instance, to put a background
  17836. * image or color that will show on screen but won't print.
  17837. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  17838. * @public
  17839. * @since 3.0.000 (2008-03-27)
  17840. */
  17841. public function setVisibility($v) {
  17842. $this->endLayer();
  17843. switch($v) {
  17844. case 'print': {
  17845. $this->startLayer('Print', true, false);
  17846. break;
  17847. }
  17848. case 'view':
  17849. case 'screen': {
  17850. $this->startLayer('View', false, true);
  17851. break;
  17852. }
  17853. case 'all': {
  17854. $this->_out('');
  17855. break;
  17856. }
  17857. default: {
  17858. $this->Error('Incorrect visibility: '.$v);
  17859. break;
  17860. }
  17861. }
  17862. }
  17863. /**
  17864. * Add transparency parameters to the current extgstate
  17865. * @param $parms (array) parameters
  17866. * @return the number of extgstates
  17867. * @protected
  17868. * @since 3.0.000 (2008-03-27)
  17869. */
  17870. protected function addExtGState($parms) {
  17871. if ($this->pdfa_mode) {
  17872. // transparencies are not allowed in PDF/A mode
  17873. return;
  17874. }
  17875. // check if this ExtGState already exist
  17876. foreach ($this->extgstates as $i => $ext) {
  17877. if ($ext['parms'] == $parms) {
  17878. if ($this->inxobj) {
  17879. // we are inside an XObject template
  17880. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  17881. }
  17882. // return reference to existing ExtGState
  17883. return $i;
  17884. }
  17885. }
  17886. $n = (count($this->extgstates) + 1);
  17887. $this->extgstates[$n] = array('parms' => $parms);
  17888. if ($this->inxobj) {
  17889. // we are inside an XObject template
  17890. $this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
  17891. }
  17892. return $n;
  17893. }
  17894. /**
  17895. * Add an extgstate
  17896. * @param $gs (array) extgstate
  17897. * @protected
  17898. * @since 3.0.000 (2008-03-27)
  17899. */
  17900. protected function setExtGState($gs) {
  17901. if ($this->pdfa_mode) {
  17902. // transparency is not allowed in PDF/A mode
  17903. return;
  17904. }
  17905. $this->_out(sprintf('/GS%d gs', $gs));
  17906. }
  17907. /**
  17908. * Put extgstates for object transparency
  17909. * @protected
  17910. * @since 3.0.000 (2008-03-27)
  17911. */
  17912. protected function _putextgstates() {
  17913. foreach ($this->extgstates as $i => $ext) {
  17914. $this->extgstates[$i]['n'] = $this->_newobj();
  17915. $out = '<< /Type /ExtGState';
  17916. foreach ($ext['parms'] as $k => $v) {
  17917. if (is_float($v)) {
  17918. $v = sprintf('%F', $v);
  17919. } elseif ($v === true) {
  17920. $v = 'true';
  17921. } elseif ($v === false) {
  17922. $v = 'false';
  17923. }
  17924. $out .= ' /'.$k.' '.$v;
  17925. }
  17926. $out .= ' >>';
  17927. $out .= "\n".'endobj';
  17928. $this->_out($out);
  17929. }
  17930. }
  17931. /**
  17932. * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
  17933. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  17934. * @param $stroking (boolean) If true apply overprint for stroking operations.
  17935. * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
  17936. * @param $mode (integer) Overprint mode: (0 = each source colour component value replaces the value previously painted for the corresponding device colorant; 1 = a tint value of 0.0 for a source colour component shall leave the corresponding component of the previously painted colour unchanged).
  17937. * @public
  17938. * @since 5.9.152 (2012-03-23)
  17939. */
  17940. public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
  17941. $stroking = $stroking ? true : false;
  17942. if ($this->empty_string($nonstroking)) {
  17943. // default value if not set
  17944. $nonstroking = $stroking;
  17945. } else {
  17946. $nonstroking = $nonstroking ? true : false;
  17947. }
  17948. if (($mode != 0) AND ($mode != 1)) {
  17949. $mode = 0;
  17950. }
  17951. $this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
  17952. $gs = $this->addExtGState($this->overprint);
  17953. $this->setExtGState($gs);
  17954. }
  17955. /**
  17956. * Get the overprint mode array (OP, op, OPM).
  17957. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  17958. * @return array.
  17959. * @public
  17960. * @since 5.9.152 (2012-03-23)
  17961. */
  17962. public function getOverprint() {
  17963. return $this->overprint;
  17964. }
  17965. /**
  17966. * Set alpha for stroking (CA) and non-stroking (ca) operations.
  17967. * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
  17968. * @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
  17969. * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
  17970. * @param $ais (boolean)
  17971. * @public
  17972. * @since 3.0.000 (2008-03-27)
  17973. */
  17974. public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
  17975. if ($this->pdfa_mode) {
  17976. // transparency is not allowed in PDF/A mode
  17977. return;
  17978. }
  17979. $stroking = floatval($stroking);
  17980. if ($this->empty_string($nonstroking)) {
  17981. // default value if not set
  17982. $nonstroking = $stroking;
  17983. } else {
  17984. $nonstroking = floatval($nonstroking);
  17985. }
  17986. if ($bm[0] == '/') {
  17987. // remove trailing slash
  17988. $bm = substr($bm, 1);
  17989. }
  17990. if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
  17991. $bm = 'Normal';
  17992. }
  17993. $ais = $ais ? true : false;
  17994. $this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
  17995. $gs = $this->addExtGState($this->alpha);
  17996. $this->setExtGState($gs);
  17997. }
  17998. /**
  17999. * Get the alpha mode array (CA, ca, BM, AIS).
  18000. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  18001. * @return array.
  18002. * @public
  18003. * @since 5.9.152 (2012-03-23)
  18004. */
  18005. public function getAlpha() {
  18006. return $this->alpha;
  18007. }
  18008. /**
  18009. * Set the default JPEG compression quality (1-100)
  18010. * @param $quality (int) JPEG quality, integer between 1 and 100
  18011. * @public
  18012. * @since 3.0.000 (2008-03-27)
  18013. */
  18014. public function setJPEGQuality($quality) {
  18015. if (($quality < 1) OR ($quality > 100)) {
  18016. $quality = 75;
  18017. }
  18018. $this->jpeg_quality = intval($quality);
  18019. }
  18020. /**
  18021. * Set the default number of columns in a row for HTML tables.
  18022. * @param $cols (int) number of columns
  18023. * @public
  18024. * @since 3.0.014 (2008-06-04)
  18025. */
  18026. public function setDefaultTableColumns($cols=4) {
  18027. $this->default_table_columns = intval($cols);
  18028. }
  18029. /**
  18030. * Set the height of the cell (line height) respect the font height.
  18031. * @param $h (int) cell proportion respect font height (typical value = 1.25).
  18032. * @public
  18033. * @since 3.0.014 (2008-06-04)
  18034. */
  18035. public function setCellHeightRatio($h) {
  18036. $this->cell_height_ratio = $h;
  18037. }
  18038. /**
  18039. * return the height of cell repect font height.
  18040. * @public
  18041. * @since 4.0.012 (2008-07-24)
  18042. */
  18043. public function getCellHeightRatio() {
  18044. return $this->cell_height_ratio;
  18045. }
  18046. /**
  18047. * Set the PDF version (check PDF reference for valid values).
  18048. * @param $version (string) PDF document version.
  18049. * @public
  18050. * @since 3.1.000 (2008-06-09)
  18051. */
  18052. public function setPDFVersion($version='1.7') {
  18053. if ($this->pdfa_mode) {
  18054. // PDF/A mode
  18055. $this->PDFVersion = '1.4';
  18056. } else {
  18057. $this->PDFVersion = $version;
  18058. }
  18059. }
  18060. /**
  18061. * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
  18062. * (see Section 8.1 of PDF reference, "Viewer Preferences").
  18063. * <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>
  18064. * @param $preferences (array) array of options.
  18065. * @author Nicola Asuni
  18066. * @public
  18067. * @since 3.1.000 (2008-06-09)
  18068. */
  18069. public function setViewerPreferences($preferences) {
  18070. $this->viewer_preferences = $preferences;
  18071. }
  18072. /**
  18073. * Paints color transition registration bars
  18074. * @param $x (float) abscissa of the top left corner of the rectangle.
  18075. * @param $y (float) ordinate of the top left corner of the rectangle.
  18076. * @param $w (float) width of the rectangle.
  18077. * @param $h (float) height of the rectangle.
  18078. * @param $transition (boolean) if true prints tcolor transitions to white.
  18079. * @param $vertical (boolean) if true prints bar vertically.
  18080. * @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.
  18081. * @author Nicola Asuni
  18082. * @since 4.9.000 (2010-03-26)
  18083. * @public
  18084. */
  18085. public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
  18086. $bars = explode(',', $colors);
  18087. $numbars = count($bars); // number of bars to print
  18088. // set bar measures
  18089. if ($vertical) {
  18090. $coords = array(0, 0, 0, 1);
  18091. $wb = $w / $numbars; // bar width
  18092. $hb = $h; // bar height
  18093. $xd = $wb; // delta x
  18094. $yd = 0; // delta y
  18095. } else {
  18096. $coords = array(1, 0, 0, 0);
  18097. $wb = $w; // bar width
  18098. $hb = $h / $numbars; // bar height
  18099. $xd = 0; // delta x
  18100. $yd = $hb; // delta y
  18101. }
  18102. $xb = $x;
  18103. $yb = $y;
  18104. foreach ($bars as $col) {
  18105. switch ($col) {
  18106. // set transition colors
  18107. case 'A': { // BLACK
  18108. $col_a = array(255);
  18109. $col_b = array(0);
  18110. break;
  18111. }
  18112. case 'W': { // WHITE
  18113. $col_a = array(0);
  18114. $col_b = array(255);
  18115. break;
  18116. }
  18117. case 'R': { // R
  18118. $col_a = array(255,255,255);
  18119. $col_b = array(255,0,0);
  18120. break;
  18121. }
  18122. case 'G': { // G
  18123. $col_a = array(255,255,255);
  18124. $col_b = array(0,255,0);
  18125. break;
  18126. }
  18127. case 'B': { // B
  18128. $col_a = array(255,255,255);
  18129. $col_b = array(0,0,255);
  18130. break;
  18131. }
  18132. case 'C': { // C
  18133. $col_a = array(0,0,0,0);
  18134. $col_b = array(100,0,0,0);
  18135. break;
  18136. }
  18137. case 'M': { // M
  18138. $col_a = array(0,0,0,0);
  18139. $col_b = array(0,100,0,0);
  18140. break;
  18141. }
  18142. case 'Y': { // Y
  18143. $col_a = array(0,0,0,0);
  18144. $col_b = array(0,0,100,0);
  18145. break;
  18146. }
  18147. case 'K': { // K
  18148. $col_a = array(0,0,0,0);
  18149. $col_b = array(0,0,0,100);
  18150. break;
  18151. }
  18152. default: { // GRAY
  18153. $col_a = array(255);
  18154. $col_b = array(0);
  18155. break;
  18156. }
  18157. }
  18158. if ($transition) {
  18159. // color gradient
  18160. $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
  18161. } else {
  18162. // color rectangle
  18163. $this->SetFillColorArray($col_b);
  18164. $this->Rect($xb, $yb, $wb, $hb, 'F', array());
  18165. }
  18166. $xb += $xd;
  18167. $yb += $yd;
  18168. }
  18169. }
  18170. /**
  18171. * Paints crop marks.
  18172. * @param $x (float) abscissa of the crop mark center.
  18173. * @param $y (float) ordinate of the crop mark center.
  18174. * @param $w (float) width of the crop mark.
  18175. * @param $h (float) height of the crop mark.
  18176. * @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.
  18177. * @param $color (array) crop mark color (default black).
  18178. * @author Nicola Asuni
  18179. * @since 4.9.000 (2010-03-26)
  18180. * @public
  18181. */
  18182. public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(0,0,0)) {
  18183. $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
  18184. $type = strtoupper($type);
  18185. $type = preg_replace('/[^A-Z\-\,]*/', '', $type);
  18186. // split type in single components
  18187. $type = str_replace('-', ',', $type);
  18188. $type = str_replace('TL', 'T,L', $type);
  18189. $type = str_replace('TR', 'T,R', $type);
  18190. $type = str_replace('BL', 'F,L', $type);
  18191. $type = str_replace('BR', 'F,R', $type);
  18192. $type = str_replace('A', 'T,L', $type);
  18193. $type = str_replace('B', 'T,R', $type);
  18194. $type = str_replace('T,RO', 'BO', $type);
  18195. $type = str_replace('C', 'F,L', $type);
  18196. $type = str_replace('D', 'F,R', $type);
  18197. $crops = explode(',', strtoupper($type));
  18198. // remove duplicates
  18199. $crops = array_unique($crops);
  18200. $dw = ($w / 4); // horizontal space to leave before the intersection point
  18201. $dh = ($h / 4); // vertical space to leave before the intersection point
  18202. foreach ($crops as $crop) {
  18203. switch ($crop) {
  18204. case 'T':
  18205. case 'TOP': {
  18206. $x1 = $x;
  18207. $y1 = ($y - $h);
  18208. $x2 = $x;
  18209. $y2 = ($y - $dh);
  18210. break;
  18211. }
  18212. case 'F':
  18213. case 'BOTTOM': {
  18214. $x1 = $x;
  18215. $y1 = ($y + $dh);
  18216. $x2 = $x;
  18217. $y2 = ($y + $h);
  18218. break;
  18219. }
  18220. case 'L':
  18221. case 'LEFT': {
  18222. $x1 = ($x - $w);
  18223. $y1 = $y;
  18224. $x2 = ($x - $dw);
  18225. $y2 = $y;
  18226. break;
  18227. }
  18228. case 'R':
  18229. case 'RIGHT': {
  18230. $x1 = ($x + $dw);
  18231. $y1 = $y;
  18232. $x2 = ($x + $w);
  18233. $y2 = $y;
  18234. break;
  18235. }
  18236. }
  18237. $this->Line($x1, $y1, $x2, $y2);
  18238. }
  18239. }
  18240. /**
  18241. * Paints a registration mark
  18242. * @param $x (float) abscissa of the registration mark center.
  18243. * @param $y (float) ordinate of the registration mark center.
  18244. * @param $r (float) radius of the crop mark.
  18245. * @param $double (boolean) if true print two concentric crop marks.
  18246. * @param $cola (array) crop mark color (default black).
  18247. * @param $colb (array) second crop mark color.
  18248. * @author Nicola Asuni
  18249. * @since 4.9.000 (2010-03-26)
  18250. * @public
  18251. */
  18252. public function registrationMark($x, $y, $r, $double=false, $cola=array(0,0,0), $colb=array(255,255,255)) {
  18253. $line_style = array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
  18254. $this->SetFillColorArray($cola);
  18255. $this->PieSector($x, $y, $r, 90, 180, 'F');
  18256. $this->PieSector($x, $y, $r, 270, 360, 'F');
  18257. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  18258. if ($double) {
  18259. $r2 = $r * 0.5;
  18260. $this->SetFillColorArray($colb);
  18261. $this->PieSector($x, $y, $r2, 90, 180, 'F');
  18262. $this->PieSector($x, $y, $r2, 270, 360, 'F');
  18263. $this->SetFillColorArray($cola);
  18264. $this->PieSector($x, $y, $r2, 0, 90, 'F');
  18265. $this->PieSector($x, $y, $r2, 180, 270, 'F');
  18266. $this->Circle($x, $y, $r2, 0, 360, 'C', $line_style, array(), 8);
  18267. }
  18268. }
  18269. /**
  18270. * Paints a linear colour gradient.
  18271. * @param $x (float) abscissa of the top left corner of the rectangle.
  18272. * @param $y (float) ordinate of the top left corner of the rectangle.
  18273. * @param $w (float) width of the rectangle.
  18274. * @param $h (float) height of the rectangle.
  18275. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  18276. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  18277. * @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).
  18278. * @author Andreas Würmser, Nicola Asuni
  18279. * @since 3.1.000 (2008-06-09)
  18280. * @public
  18281. */
  18282. public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
  18283. $this->Clip($x, $y, $w, $h);
  18284. $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  18285. }
  18286. /**
  18287. * Paints a radial colour gradient.
  18288. * @param $x (float) abscissa of the top left corner of the rectangle.
  18289. * @param $y (float) ordinate of the top left corner of the rectangle.
  18290. * @param $w (float) width of the rectangle.
  18291. * @param $h (float) height of the rectangle.
  18292. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  18293. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  18294. * @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.
  18295. * @author Andreas Würmser, Nicola Asuni
  18296. * @since 3.1.000 (2008-06-09)
  18297. * @public
  18298. */
  18299. public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
  18300. $this->Clip($x, $y, $w, $h);
  18301. $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  18302. }
  18303. /**
  18304. * Paints a coons patch mesh.
  18305. * @param $x (float) abscissa of the top left corner of the rectangle.
  18306. * @param $y (float) ordinate of the top left corner of the rectangle.
  18307. * @param $w (float) width of the rectangle.
  18308. * @param $h (float) height of the rectangle.
  18309. * @param $col1 (array) first color (lower left corner) (RGB components).
  18310. * @param $col2 (array) second color (lower right corner) (RGB components).
  18311. * @param $col3 (array) third color (upper right corner) (RGB components).
  18312. * @param $col4 (array) fourth color (upper left corner) (RGB components).
  18313. * @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>
  18314. * @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
  18315. * @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
  18316. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  18317. * @author Andreas Würmser, Nicola Asuni
  18318. * @since 3.1.000 (2008-06-09)
  18319. * @public
  18320. */
  18321. 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) {
  18322. if ($this->pdfa_mode) {
  18323. return;
  18324. }
  18325. $this->Clip($x, $y, $w, $h);
  18326. $n = count($this->gradients) + 1;
  18327. $this->gradients[$n] = array();
  18328. $this->gradients[$n]['type'] = 6; //coons patch mesh
  18329. $this->gradients[$n]['coords'] = array();
  18330. $this->gradients[$n]['antialias'] = $antialias;
  18331. $this->gradients[$n]['colors'] = array();
  18332. $this->gradients[$n]['transparency'] = false;
  18333. //check the coords array if it is the simple array or the multi patch array
  18334. if (!isset($coords[0]['f'])) {
  18335. //simple array -> convert to multi patch array
  18336. if (!isset($col1[1])) {
  18337. $col1[1] = $col1[2] = $col1[0];
  18338. }
  18339. if (!isset($col2[1])) {
  18340. $col2[1] = $col2[2] = $col2[0];
  18341. }
  18342. if (!isset($col3[1])) {
  18343. $col3[1] = $col3[2] = $col3[0];
  18344. }
  18345. if (!isset($col4[1])) {
  18346. $col4[1] = $col4[2] = $col4[0];
  18347. }
  18348. $patch_array[0]['f'] = 0;
  18349. $patch_array[0]['points'] = $coords;
  18350. $patch_array[0]['colors'][0]['r'] = $col1[0];
  18351. $patch_array[0]['colors'][0]['g'] = $col1[1];
  18352. $patch_array[0]['colors'][0]['b'] = $col1[2];
  18353. $patch_array[0]['colors'][1]['r'] = $col2[0];
  18354. $patch_array[0]['colors'][1]['g'] = $col2[1];
  18355. $patch_array[0]['colors'][1]['b'] = $col2[2];
  18356. $patch_array[0]['colors'][2]['r'] = $col3[0];
  18357. $patch_array[0]['colors'][2]['g'] = $col3[1];
  18358. $patch_array[0]['colors'][2]['b'] = $col3[2];
  18359. $patch_array[0]['colors'][3]['r'] = $col4[0];
  18360. $patch_array[0]['colors'][3]['g'] = $col4[1];
  18361. $patch_array[0]['colors'][3]['b'] = $col4[2];
  18362. } else {
  18363. //multi patch array
  18364. $patch_array = $coords;
  18365. }
  18366. $bpcd = 65535; //16 bits per coordinate
  18367. //build the data stream
  18368. $this->gradients[$n]['stream'] = '';
  18369. $count_patch = count($patch_array);
  18370. for ($i=0; $i < $count_patch; ++$i) {
  18371. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
  18372. $count_points = count($patch_array[$i]['points']);
  18373. for ($j=0; $j < $count_points; ++$j) {
  18374. //each point as 16 bit
  18375. $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
  18376. if ($patch_array[$i]['points'][$j] < 0) {
  18377. $patch_array[$i]['points'][$j] = 0;
  18378. }
  18379. if ($patch_array[$i]['points'][$j] > $bpcd) {
  18380. $patch_array[$i]['points'][$j] = $bpcd;
  18381. }
  18382. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
  18383. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
  18384. }
  18385. $count_cols = count($patch_array[$i]['colors']);
  18386. for ($j=0; $j < $count_cols; ++$j) {
  18387. //each color component as 8 bit
  18388. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
  18389. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
  18390. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
  18391. }
  18392. }
  18393. //paint the gradient
  18394. $this->_out('/Sh'.$n.' sh');
  18395. //restore previous Graphic State
  18396. $this->_out('Q');
  18397. if ($this->inxobj) {
  18398. // we are inside an XObject template
  18399. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  18400. }
  18401. }
  18402. /**
  18403. * Set a rectangular clipping area.
  18404. * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
  18405. * @param $y (float) ordinate of the top left corner of the rectangle.
  18406. * @param $w (float) width of the rectangle.
  18407. * @param $h (float) height of the rectangle.
  18408. * @author Andreas Würmser, Nicola Asuni
  18409. * @since 3.1.000 (2008-06-09)
  18410. * @protected
  18411. */
  18412. protected function Clip($x, $y, $w, $h) {
  18413. if ($this->rtl) {
  18414. $x = $this->w - $x - $w;
  18415. }
  18416. //save current Graphic State
  18417. $s = 'q';
  18418. //set clipping area
  18419. $s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
  18420. //set up transformation matrix for gradient
  18421. $s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
  18422. $this->_out($s);
  18423. }
  18424. /**
  18425. * Output gradient.
  18426. * @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)
  18427. * @param $coords (array) array of coordinates.
  18428. * @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).
  18429. * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
  18430. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  18431. * @author Nicola Asuni
  18432. * @since 3.1.000 (2008-06-09)
  18433. * @public
  18434. */
  18435. public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
  18436. if ($this->pdfa_mode) {
  18437. return;
  18438. }
  18439. $n = count($this->gradients) + 1;
  18440. $this->gradients[$n] = array();
  18441. $this->gradients[$n]['type'] = $type;
  18442. $this->gradients[$n]['coords'] = $coords;
  18443. $this->gradients[$n]['antialias'] = $antialias;
  18444. $this->gradients[$n]['colors'] = array();
  18445. $this->gradients[$n]['transparency'] = false;
  18446. // color space
  18447. $numcolspace = count($stops[0]['color']);
  18448. $bcolor = array_values($background);
  18449. switch($numcolspace) {
  18450. case 4: { // CMYK
  18451. $this->gradients[$n]['colspace'] = 'DeviceCMYK';
  18452. if (!empty($background)) {
  18453. $this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
  18454. }
  18455. break;
  18456. }
  18457. case 3: { // RGB
  18458. $this->gradients[$n]['colspace'] = 'DeviceRGB';
  18459. if (!empty($background)) {
  18460. $this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
  18461. }
  18462. break;
  18463. }
  18464. case 1: { // Gray scale
  18465. $this->gradients[$n]['colspace'] = 'DeviceGray';
  18466. if (!empty($background)) {
  18467. $this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
  18468. }
  18469. break;
  18470. }
  18471. }
  18472. $num_stops = count($stops);
  18473. $last_stop_id = $num_stops - 1;
  18474. foreach ($stops as $key => $stop) {
  18475. $this->gradients[$n]['colors'][$key] = array();
  18476. // offset represents a location along the gradient vector
  18477. if (isset($stop['offset'])) {
  18478. $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
  18479. } else {
  18480. if ($key == 0) {
  18481. $this->gradients[$n]['colors'][$key]['offset'] = 0;
  18482. } elseif ($key == $last_stop_id) {
  18483. $this->gradients[$n]['colors'][$key]['offset'] = 1;
  18484. } else {
  18485. $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
  18486. $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
  18487. }
  18488. }
  18489. if (isset($stop['opacity'])) {
  18490. $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
  18491. if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
  18492. $this->gradients[$n]['transparency'] = true;
  18493. }
  18494. } else {
  18495. $this->gradients[$n]['colors'][$key]['opacity'] = 1;
  18496. }
  18497. // exponent for the exponential interpolation function
  18498. if (isset($stop['exponent'])) {
  18499. $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
  18500. } else {
  18501. $this->gradients[$n]['colors'][$key]['exponent'] = 1;
  18502. }
  18503. // set colors
  18504. $color = array_values($stop['color']);
  18505. switch($numcolspace) {
  18506. case 4: { // CMYK
  18507. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
  18508. break;
  18509. }
  18510. case 3: { // RGB
  18511. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
  18512. break;
  18513. }
  18514. case 1: { // Gray scale
  18515. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
  18516. break;
  18517. }
  18518. }
  18519. }
  18520. if ($this->gradients[$n]['transparency']) {
  18521. // paint luminosity gradient
  18522. $this->_out('/TGS'.$n.' gs');
  18523. }
  18524. //paint the gradient
  18525. $this->_out('/Sh'.$n.' sh');
  18526. //restore previous Graphic State
  18527. $this->_out('Q');
  18528. if ($this->inxobj) {
  18529. // we are inside an XObject template
  18530. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  18531. }
  18532. }
  18533. /**
  18534. * Output gradient shaders.
  18535. * @author Nicola Asuni
  18536. * @since 3.1.000 (2008-06-09)
  18537. * @protected
  18538. */
  18539. function _putshaders() {
  18540. if ($this->pdfa_mode) {
  18541. return;
  18542. }
  18543. $idt = count($this->gradients); //index for transparency gradients
  18544. foreach ($this->gradients as $id => $grad) {
  18545. if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
  18546. $fc = $this->_newobj();
  18547. $out = '<<';
  18548. $out .= ' /FunctionType 3';
  18549. $out .= ' /Domain [0 1]';
  18550. $functions = '';
  18551. $bounds = '';
  18552. $encode = '';
  18553. $i = 1;
  18554. $num_cols = count($grad['colors']);
  18555. $lastcols = $num_cols - 1;
  18556. for ($i = 1; $i < $num_cols; ++$i) {
  18557. $functions .= ($fc + $i).' 0 R ';
  18558. if ($i < $lastcols) {
  18559. $bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
  18560. }
  18561. $encode .= '0 1 ';
  18562. }
  18563. $out .= ' /Functions ['.trim($functions).']';
  18564. $out .= ' /Bounds ['.trim($bounds).']';
  18565. $out .= ' /Encode ['.trim($encode).']';
  18566. $out .= ' >>';
  18567. $out .= "\n".'endobj';
  18568. $this->_out($out);
  18569. for ($i = 1; $i < $num_cols; ++$i) {
  18570. $this->_newobj();
  18571. $out = '<<';
  18572. $out .= ' /FunctionType 2';
  18573. $out .= ' /Domain [0 1]';
  18574. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
  18575. $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
  18576. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  18577. $out .= ' >>';
  18578. $out .= "\n".'endobj';
  18579. $this->_out($out);
  18580. }
  18581. // set transparency fuctions
  18582. if ($grad['transparency']) {
  18583. $ft = $this->_newobj();
  18584. $out = '<<';
  18585. $out .= ' /FunctionType 3';
  18586. $out .= ' /Domain [0 1]';
  18587. $functions = '';
  18588. $i = 1;
  18589. $num_cols = count($grad['colors']);
  18590. for ($i = 1; $i < $num_cols; ++$i) {
  18591. $functions .= ($ft + $i).' 0 R ';
  18592. }
  18593. $out .= ' /Functions ['.trim($functions).']';
  18594. $out .= ' /Bounds ['.trim($bounds).']';
  18595. $out .= ' /Encode ['.trim($encode).']';
  18596. $out .= ' >>';
  18597. $out .= "\n".'endobj';
  18598. $this->_out($out);
  18599. for ($i = 1; $i < $num_cols; ++$i) {
  18600. $this->_newobj();
  18601. $out = '<<';
  18602. $out .= ' /FunctionType 2';
  18603. $out .= ' /Domain [0 1]';
  18604. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
  18605. $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
  18606. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  18607. $out .= ' >>';
  18608. $out .= "\n".'endobj';
  18609. $this->_out($out);
  18610. }
  18611. }
  18612. }
  18613. // set shading object
  18614. $this->_newobj();
  18615. $out = '<< /ShadingType '.$grad['type'];
  18616. if (isset($grad['colspace'])) {
  18617. $out .= ' /ColorSpace /'.$grad['colspace'];
  18618. } else {
  18619. $out .= ' /ColorSpace /DeviceRGB';
  18620. }
  18621. if (isset($grad['background']) AND !empty($grad['background'])) {
  18622. $out .= ' /Background ['.$grad['background'].']';
  18623. }
  18624. if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
  18625. $out .= ' /AntiAlias true';
  18626. }
  18627. if ($grad['type'] == 2) {
  18628. $out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
  18629. $out .= ' /Domain [0 1]';
  18630. $out .= ' /Function '.$fc.' 0 R';
  18631. $out .= ' /Extend [true true]';
  18632. $out .= ' >>';
  18633. } elseif ($grad['type'] == 3) {
  18634. //x0, y0, r0, x1, y1, r1
  18635. //at this this time radius of inner circle is 0
  18636. $out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
  18637. $out .= ' /Domain [0 1]';
  18638. $out .= ' /Function '.$fc.' 0 R';
  18639. $out .= ' /Extend [true true]';
  18640. $out .= ' >>';
  18641. } elseif ($grad['type'] == 6) {
  18642. $out .= ' /BitsPerCoordinate 16';
  18643. $out .= ' /BitsPerComponent 8';
  18644. $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
  18645. $out .= ' /BitsPerFlag 8';
  18646. $stream = $this->_getrawstream($grad['stream']);
  18647. $out .= ' /Length '.strlen($stream);
  18648. $out .= ' >>';
  18649. $out .= ' stream'."\n".$stream."\n".'endstream';
  18650. }
  18651. $out .= "\n".'endobj';
  18652. $this->_out($out);
  18653. if ($grad['transparency']) {
  18654. $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
  18655. $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
  18656. }
  18657. $this->gradients[$id]['id'] = $this->n;
  18658. // set pattern object
  18659. $this->_newobj();
  18660. $out = '<< /Type /Pattern /PatternType 2';
  18661. $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
  18662. $out .= ' >>';
  18663. $out .= "\n".'endobj';
  18664. $this->_out($out);
  18665. $this->gradients[$id]['pattern'] = $this->n;
  18666. // set shading and pattern for transparency mask
  18667. if ($grad['transparency']) {
  18668. // luminosity pattern
  18669. $idgs = $id + $idt;
  18670. $this->_newobj();
  18671. $this->_out($shading_transparency);
  18672. $this->gradients[$idgs]['id'] = $this->n;
  18673. $this->_newobj();
  18674. $out = '<< /Type /Pattern /PatternType 2';
  18675. $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
  18676. $out .= ' >>';
  18677. $out .= "\n".'endobj';
  18678. $this->_out($out);
  18679. $this->gradients[$idgs]['pattern'] = $this->n;
  18680. // luminosity XObject
  18681. $oid = $this->_newobj();
  18682. $this->xobjects['LX'.$oid] = array('n' => $oid);
  18683. $filter = '';
  18684. $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
  18685. if ($this->compress) {
  18686. $filter = ' /Filter /FlateDecode';
  18687. $stream = gzcompress($stream);
  18688. }
  18689. $stream = $this->_getrawstream($stream);
  18690. $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
  18691. $out .= ' /Length '.strlen($stream);
  18692. $rect = sprintf('%F %F', $this->wPt, $this->hPt);
  18693. $out .= ' /BBox [0 0 '.$rect.']';
  18694. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
  18695. $out .= ' /Resources <<';
  18696. $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
  18697. $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
  18698. $out .= ' >>';
  18699. $out .= ' >> ';
  18700. $out .= ' stream'."\n".$stream."\n".'endstream';
  18701. $out .= "\n".'endobj';
  18702. $this->_out($out);
  18703. // SMask
  18704. $this->_newobj();
  18705. $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
  18706. $this->_out($out);
  18707. // ExtGState
  18708. $this->_newobj();
  18709. $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
  18710. $this->_out($out);
  18711. $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
  18712. }
  18713. }
  18714. }
  18715. /**
  18716. * Draw the sector of a circle.
  18717. * It can be used for instance to render pie charts.
  18718. * @param $xc (float) abscissa of the center.
  18719. * @param $yc (float) ordinate of the center.
  18720. * @param $r (float) radius.
  18721. * @param $a (float) start angle (in degrees).
  18722. * @param $b (float) end angle (in degrees).
  18723. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  18724. * @param $cw: (float) indicates whether to go clockwise (default: true).
  18725. * @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.
  18726. * @author Maxime Delorme, Nicola Asuni
  18727. * @since 3.1.000 (2008-06-09)
  18728. * @public
  18729. */
  18730. public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
  18731. $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
  18732. }
  18733. /**
  18734. * Draw the sector of an ellipse.
  18735. * It can be used for instance to render pie charts.
  18736. * @param $xc (float) abscissa of the center.
  18737. * @param $yc (float) ordinate of the center.
  18738. * @param $rx (float) the x-axis radius.
  18739. * @param $ry (float) the y-axis radius.
  18740. * @param $a (float) start angle (in degrees).
  18741. * @param $b (float) end angle (in degrees).
  18742. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  18743. * @param $cw: (float) indicates whether to go clockwise.
  18744. * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
  18745. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
  18746. * @author Maxime Delorme, Nicola Asuni
  18747. * @since 3.1.000 (2008-06-09)
  18748. * @public
  18749. */
  18750. public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
  18751. if ($this->rtl) {
  18752. $xc = ($this->w - $xc);
  18753. }
  18754. $op = $this->getPathPaintOperator($style);
  18755. if ($op == 'f') {
  18756. $line_style = array();
  18757. }
  18758. if ($cw) {
  18759. $d = $b;
  18760. $b = (360 - $a + $o);
  18761. $a = (360 - $d + $o);
  18762. } else {
  18763. $b += $o;
  18764. $a += $o;
  18765. }
  18766. $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
  18767. $this->_out($op);
  18768. }
  18769. /**
  18770. * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
  18771. * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  18772. * Only vector drawing is supported, not text or bitmap.
  18773. * 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).
  18774. * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
  18775. * @param $x (float) Abscissa of the upper-left corner.
  18776. * @param $y (float) Ordinate of the upper-left corner.
  18777. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  18778. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  18779. * @param $link (mixed) URL or identifier returned by AddLink().
  18780. * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
  18781. * @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>
  18782. * @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>
  18783. * @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)))
  18784. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  18785. * @param $fixoutvals (boolean) if true remove values outside the bounding box.
  18786. * @author Valentin Schmidt, Nicola Asuni
  18787. * @since 3.1.000 (2008-06-09)
  18788. * @public
  18789. */
  18790. public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
  18791. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  18792. // convert EPS to raster image using GD or ImageMagick libraries
  18793. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  18794. }
  18795. if ($x === '') {
  18796. $x = $this->x;
  18797. }
  18798. if ($y === '') {
  18799. $y = $this->y;
  18800. }
  18801. // check page for no-write regions and adapt page margins if necessary
  18802. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  18803. $k = $this->k;
  18804. if ($file{0} === '@') { // image from string
  18805. $data = substr($file, 1);
  18806. } else { // EPS/AI file
  18807. $data = file_get_contents($file);
  18808. }
  18809. if ($data === false) {
  18810. $this->Error('EPS file not found: '.$file);
  18811. }
  18812. $regs = array();
  18813. // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
  18814. preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
  18815. if (count($regs) > 1) {
  18816. $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
  18817. if (strpos($version_str, 'Adobe Illustrator') !== false) {
  18818. $versexp = explode(' ', $version_str);
  18819. $version = (float)array_pop($versexp);
  18820. if ($version >= 9) {
  18821. $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
  18822. }
  18823. }
  18824. }
  18825. // strip binary bytes in front of PS-header
  18826. $start = strpos($data, '%!PS-Adobe');
  18827. if ($start > 0) {
  18828. $data = substr($data, $start);
  18829. }
  18830. // find BoundingBox params
  18831. preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
  18832. if (count($regs) > 1) {
  18833. list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
  18834. } else {
  18835. $this->Error('No BoundingBox found in EPS/AI file: '.$file);
  18836. }
  18837. $start = strpos($data, '%%EndSetup');
  18838. if ($start === false) {
  18839. $start = strpos($data, '%%EndProlog');
  18840. }
  18841. if ($start === false) {
  18842. $start = strpos($data, '%%BoundingBox');
  18843. }
  18844. $data = substr($data, $start);
  18845. $end = strpos($data, '%%PageTrailer');
  18846. if ($end===false) {
  18847. $end = strpos($data, 'showpage');
  18848. }
  18849. if ($end) {
  18850. $data = substr($data, 0, $end);
  18851. }
  18852. // calculate image width and height on document
  18853. if (($w <= 0) AND ($h <= 0)) {
  18854. $w = ($x2 - $x1) / $k;
  18855. $h = ($y2 - $y1) / $k;
  18856. } elseif ($w <= 0) {
  18857. $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
  18858. } elseif ($h <= 0) {
  18859. $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
  18860. }
  18861. // fit the image on available space
  18862. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  18863. if ($this->rasterize_vector_images) {
  18864. // convert EPS to raster image using GD or ImageMagick libraries
  18865. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  18866. }
  18867. // set scaling factors
  18868. $scale_x = $w / (($x2 - $x1) / $k);
  18869. $scale_y = $h / (($y2 - $y1) / $k);
  18870. // set alignment
  18871. $this->img_rb_y = $y + $h;
  18872. // set alignment
  18873. if ($this->rtl) {
  18874. if ($palign == 'L') {
  18875. $ximg = $this->lMargin;
  18876. } elseif ($palign == 'C') {
  18877. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  18878. } elseif ($palign == 'R') {
  18879. $ximg = $this->w - $this->rMargin - $w;
  18880. } else {
  18881. $ximg = $x - $w;
  18882. }
  18883. $this->img_rb_x = $ximg;
  18884. } else {
  18885. if ($palign == 'L') {
  18886. $ximg = $this->lMargin;
  18887. } elseif ($palign == 'C') {
  18888. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  18889. } elseif ($palign == 'R') {
  18890. $ximg = $this->w - $this->rMargin - $w;
  18891. } else {
  18892. $ximg = $x;
  18893. }
  18894. $this->img_rb_x = $ximg + $w;
  18895. }
  18896. if ($useBoundingBox) {
  18897. $dx = $ximg * $k - $x1;
  18898. $dy = $y * $k - $y1;
  18899. } else {
  18900. $dx = $ximg * $k;
  18901. $dy = $y * $k;
  18902. }
  18903. // save the current graphic state
  18904. $this->_out('q'.$this->epsmarker);
  18905. // translate
  18906. $this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
  18907. // scale
  18908. if (isset($scale_x)) {
  18909. $this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
  18910. }
  18911. // handle pc/unix/mac line endings
  18912. $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
  18913. $u=0;
  18914. $cnt = count($lines);
  18915. for ($i=0; $i < $cnt; ++$i) {
  18916. $line = $lines[$i];
  18917. if (($line == '') OR ($line{0} == '%')) {
  18918. continue;
  18919. }
  18920. $len = strlen($line);
  18921. // check for spot color names
  18922. $color_name = '';
  18923. if (strcasecmp('x', substr(trim($line), -1)) == 0) {
  18924. if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
  18925. // extract spot color name
  18926. $color_name = $matches[0];
  18927. // remove color name from string
  18928. $line = str_replace(' '.$color_name, '', $line);
  18929. // remove pharentesis from color name
  18930. $color_name = substr($color_name, 1, -1);
  18931. }
  18932. }
  18933. $chunks = explode(' ', $line);
  18934. $cmd = trim(array_pop($chunks));
  18935. // RGB
  18936. if (($cmd == 'Xa') OR ($cmd == 'XA')) {
  18937. $b = array_pop($chunks);
  18938. $g = array_pop($chunks);
  18939. $r = array_pop($chunks);
  18940. $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!
  18941. continue;
  18942. }
  18943. $skip = false;
  18944. if ($fixoutvals) {
  18945. // check for values outside the bounding box
  18946. switch ($cmd) {
  18947. case 'm':
  18948. case 'l':
  18949. case 'L': {
  18950. // skip values outside bounding box
  18951. foreach ($chunks as $key => $val) {
  18952. if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
  18953. $skip = true;
  18954. } elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
  18955. $skip = true;
  18956. }
  18957. }
  18958. }
  18959. }
  18960. }
  18961. switch ($cmd) {
  18962. case 'm':
  18963. case 'l':
  18964. case 'v':
  18965. case 'y':
  18966. case 'c':
  18967. case 'k':
  18968. case 'K':
  18969. case 'g':
  18970. case 'G':
  18971. case 's':
  18972. case 'S':
  18973. case 'J':
  18974. case 'j':
  18975. case 'w':
  18976. case 'M':
  18977. case 'd':
  18978. case 'n': {
  18979. if ($skip) {
  18980. break;
  18981. }
  18982. $this->_out($line);
  18983. break;
  18984. }
  18985. case 'x': {// custom fill color
  18986. if (empty($color_name)) {
  18987. // CMYK color
  18988. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  18989. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
  18990. } else {
  18991. // Spot Color (CMYK + tint)
  18992. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  18993. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  18994. $color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  18995. $this->_out($color_cmd);
  18996. }
  18997. break;
  18998. }
  18999. case 'X': { // custom stroke color
  19000. if (empty($color_name)) {
  19001. // CMYK color
  19002. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  19003. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
  19004. } else {
  19005. // Spot Color (CMYK + tint)
  19006. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  19007. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  19008. $color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  19009. $this->_out($color_cmd);
  19010. }
  19011. break;
  19012. }
  19013. case 'Y':
  19014. case 'N':
  19015. case 'V':
  19016. case 'L':
  19017. case 'C': {
  19018. if ($skip) {
  19019. break;
  19020. }
  19021. $line[($len - 1)] = strtolower($cmd);
  19022. $this->_out($line);
  19023. break;
  19024. }
  19025. case 'b':
  19026. case 'B': {
  19027. $this->_out($cmd . '*');
  19028. break;
  19029. }
  19030. case 'f':
  19031. case 'F': {
  19032. if ($u > 0) {
  19033. $isU = false;
  19034. $max = min(($i + 5), $cnt);
  19035. for ($j = ($i + 1); $j < $max; ++$j) {
  19036. $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
  19037. }
  19038. if ($isU) {
  19039. $this->_out('f*');
  19040. }
  19041. } else {
  19042. $this->_out('f*');
  19043. }
  19044. break;
  19045. }
  19046. case '*u': {
  19047. ++$u;
  19048. break;
  19049. }
  19050. case '*U': {
  19051. --$u;
  19052. break;
  19053. }
  19054. }
  19055. }
  19056. // restore previous graphic state
  19057. $this->_out($this->epsmarker.'Q');
  19058. if (!empty($border)) {
  19059. $bx = $this->x;
  19060. $by = $this->y;
  19061. $this->x = $ximg;
  19062. if ($this->rtl) {
  19063. $this->x += $w;
  19064. }
  19065. $this->y = $y;
  19066. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  19067. $this->x = $bx;
  19068. $this->y = $by;
  19069. }
  19070. if ($link) {
  19071. $this->Link($ximg, $y, $w, $h, $link, 0);
  19072. }
  19073. // set pointer to align the next text/objects
  19074. switch($align) {
  19075. case 'T':{
  19076. $this->y = $y;
  19077. $this->x = $this->img_rb_x;
  19078. break;
  19079. }
  19080. case 'M':{
  19081. $this->y = $y + round($h/2);
  19082. $this->x = $this->img_rb_x;
  19083. break;
  19084. }
  19085. case 'B':{
  19086. $this->y = $this->img_rb_y;
  19087. $this->x = $this->img_rb_x;
  19088. break;
  19089. }
  19090. case 'N':{
  19091. $this->SetY($this->img_rb_y);
  19092. break;
  19093. }
  19094. default:{
  19095. break;
  19096. }
  19097. }
  19098. $this->endlinex = $this->img_rb_x;
  19099. }
  19100. /**
  19101. * Set document barcode.
  19102. * @param $bc (string) barcode
  19103. * @public
  19104. */
  19105. public function setBarcode($bc='') {
  19106. $this->barcode = $bc;
  19107. }
  19108. /**
  19109. * Get current barcode.
  19110. * @return string
  19111. * @public
  19112. * @since 4.0.012 (2008-07-24)
  19113. */
  19114. public function getBarcode() {
  19115. return $this->barcode;
  19116. }
  19117. /**
  19118. * Print a Linear Barcode.
  19119. * @param $code (string) code to print
  19120. * @param $type (string) type of barcode (see barcodes.php for supported formats).
  19121. * @param $x (int) x position in user units (empty string = current x position)
  19122. * @param $y (int) y position in user units (empty string = current y position)
  19123. * @param $w (int) width in user units (empty string = remaining page width)
  19124. * @param $h (int) height in user units (empty string = remaining page height)
  19125. * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
  19126. * @param $style (array) array of options:<ul>
  19127. * <li>boolean $style['border'] if true prints a border</li>
  19128. * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
  19129. * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
  19130. * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
  19131. * <li>array $style['fgcolor'] color array for bars and text</li>
  19132. * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
  19133. * <li>boolean $style['text'] if true prints text below the barcode</li>
  19134. * <li>string $style['label'] override default label</li>
  19135. * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
  19136. * <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>
  19137. * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
  19138. * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
  19139. * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
  19140. * <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>
  19141. * <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>
  19142. * @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>
  19143. * @author Nicola Asuni
  19144. * @since 3.1.000 (2008-06-09)
  19145. * @public
  19146. */
  19147. public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style='', $align='') {
  19148. if ($this->empty_string(trim($code))) {
  19149. return;
  19150. }
  19151. require_once(dirname(__FILE__).'/barcodes.php');
  19152. // save current graphic settings
  19153. $gvars = $this->getGraphicVars();
  19154. // create new barcode object
  19155. $barcodeobj = new TCPDFBarcode($code, $type);
  19156. $arrcode = $barcodeobj->getBarcodeArray();
  19157. if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] == 0)) {
  19158. $this->Error('Error in 1D barcode string');
  19159. }
  19160. // set default values
  19161. if (!isset($style['position'])) {
  19162. $style['position'] = '';
  19163. } elseif ($style['position'] == 'S') {
  19164. // keep this for backward compatibility
  19165. $style['position'] = '';
  19166. $style['stretch'] = true;
  19167. }
  19168. if (!isset($style['fitwidth'])) {
  19169. if (!isset($style['stretch'])) {
  19170. $style['fitwidth'] = true;
  19171. } else {
  19172. $style['fitwidth'] = false;
  19173. }
  19174. }
  19175. if ($style['fitwidth']) {
  19176. // disable stretch
  19177. $style['stretch'] = false;
  19178. }
  19179. if (!isset($style['stretch'])) {
  19180. if (($w === '') OR ($w <= 0)) {
  19181. $style['stretch'] = false;
  19182. } else {
  19183. $style['stretch'] = true;
  19184. }
  19185. }
  19186. if (!isset($style['fgcolor'])) {
  19187. $style['fgcolor'] = array(0,0,0); // default black
  19188. }
  19189. if (!isset($style['bgcolor'])) {
  19190. $style['bgcolor'] = false; // default transparent
  19191. }
  19192. if (!isset($style['border'])) {
  19193. $style['border'] = false;
  19194. }
  19195. $fontsize = 0;
  19196. if (!isset($style['text'])) {
  19197. $style['text'] = false;
  19198. }
  19199. if ($style['text'] AND isset($style['font'])) {
  19200. if (isset($style['fontsize'])) {
  19201. $fontsize = $style['fontsize'];
  19202. }
  19203. $this->SetFont($style['font'], '', $fontsize);
  19204. }
  19205. if (!isset($style['stretchtext'])) {
  19206. $style['stretchtext'] = 4;
  19207. }
  19208. if ($x === '') {
  19209. $x = $this->x;
  19210. }
  19211. if ($y === '') {
  19212. $y = $this->y;
  19213. }
  19214. // check page for no-write regions and adapt page margins if necessary
  19215. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  19216. if (($w === '') OR ($w <= 0)) {
  19217. if ($this->rtl) {
  19218. $w = $x - $this->lMargin;
  19219. } else {
  19220. $w = $this->w - $this->rMargin - $x;
  19221. }
  19222. }
  19223. // padding
  19224. if (!isset($style['padding'])) {
  19225. $padding = 0;
  19226. } elseif ($style['padding'] === 'auto') {
  19227. $padding = 10 * ($w / ($arrcode['maxw'] + 20));
  19228. } else {
  19229. $padding = floatval($style['padding']);
  19230. }
  19231. // horizontal padding
  19232. if (!isset($style['hpadding'])) {
  19233. $hpadding = $padding;
  19234. } elseif ($style['hpadding'] === 'auto') {
  19235. $hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
  19236. } else {
  19237. $hpadding = floatval($style['hpadding']);
  19238. }
  19239. // vertical padding
  19240. if (!isset($style['vpadding'])) {
  19241. $vpadding = $padding;
  19242. } elseif ($style['vpadding'] === 'auto') {
  19243. $vpadding = ($hpadding / 2);
  19244. } else {
  19245. $vpadding = floatval($style['vpadding']);
  19246. }
  19247. // calculate xres (single bar width)
  19248. $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
  19249. if ($style['stretch']) {
  19250. $xres = $max_xres;
  19251. } else {
  19252. if ($this->empty_string($xres)) {
  19253. $xres = (0.141 * $this->k); // default bar width = 0.4 mm
  19254. }
  19255. if ($xres > $max_xres) {
  19256. // correct xres to fit on $w
  19257. $xres = $max_xres;
  19258. }
  19259. if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
  19260. OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
  19261. $hpadding = 10 * $xres;
  19262. if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
  19263. $vpadding = ($hpadding / 2);
  19264. }
  19265. }
  19266. }
  19267. if ($style['fitwidth']) {
  19268. $wold = $w;
  19269. $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
  19270. if (isset($style['cellfitalign'])) {
  19271. switch ($style['cellfitalign']) {
  19272. case 'L': {
  19273. if ($this->rtl) {
  19274. $x -= ($wold - $w);
  19275. }
  19276. break;
  19277. }
  19278. case 'R': {
  19279. if (!$this->rtl) {
  19280. $x += ($wold - $w);
  19281. }
  19282. break;
  19283. }
  19284. case 'C': {
  19285. if ($this->rtl) {
  19286. $x -= (($wold - $w) / 2);
  19287. } else {
  19288. $x += (($wold - $w) / 2);
  19289. }
  19290. break;
  19291. }
  19292. default : {
  19293. break;
  19294. }
  19295. }
  19296. }
  19297. }
  19298. $text_height = ($this->cell_height_ratio * $fontsize / $this->k);
  19299. // height
  19300. if (($h === '') OR ($h <= 0)) {
  19301. // set default height
  19302. $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
  19303. }
  19304. $barh = $h - $text_height - (2 * $vpadding);
  19305. if ($barh <=0) {
  19306. // try to reduce font or padding to fit barcode on available height
  19307. if ($text_height > $h) {
  19308. $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
  19309. $text_height = ($this->cell_height_ratio * $fontsize / $this->k);
  19310. $this->SetFont($style['font'], '', $fontsize);
  19311. }
  19312. if ($vpadding > 0) {
  19313. $vpadding = (($h - $text_height) / 4);
  19314. }
  19315. $barh = $h - $text_height - (2 * $vpadding);
  19316. }
  19317. // fit the barcode on available space
  19318. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  19319. // set alignment
  19320. $this->img_rb_y = $y + $h;
  19321. // set alignment
  19322. if ($this->rtl) {
  19323. if ($style['position'] == 'L') {
  19324. $xpos = $this->lMargin;
  19325. } elseif ($style['position'] == 'C') {
  19326. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  19327. } elseif ($style['position'] == 'R') {
  19328. $xpos = $this->w - $this->rMargin - $w;
  19329. } else {
  19330. $xpos = $x - $w;
  19331. }
  19332. $this->img_rb_x = $xpos;
  19333. } else {
  19334. if ($style['position'] == 'L') {
  19335. $xpos = $this->lMargin;
  19336. } elseif ($style['position'] == 'C') {
  19337. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  19338. } elseif ($style['position'] == 'R') {
  19339. $xpos = $this->w - $this->rMargin - $w;
  19340. } else {
  19341. $xpos = $x;
  19342. }
  19343. $this->img_rb_x = $xpos + $w;
  19344. }
  19345. $xpos_rect = $xpos;
  19346. if (!isset($style['align'])) {
  19347. $style['align'] = 'C';
  19348. }
  19349. switch ($style['align']) {
  19350. case 'L': {
  19351. $xpos = $xpos_rect + $hpadding;
  19352. break;
  19353. }
  19354. case 'R': {
  19355. $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
  19356. break;
  19357. }
  19358. case 'C':
  19359. default : {
  19360. $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
  19361. break;
  19362. }
  19363. }
  19364. $xpos_text = $xpos;
  19365. // barcode is always printed in LTR direction
  19366. $tempRTL = $this->rtl;
  19367. $this->rtl = false;
  19368. // print background color
  19369. if ($style['bgcolor']) {
  19370. $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  19371. } elseif ($style['border']) {
  19372. $this->Rect($xpos_rect, $y, $w, $h, 'D');
  19373. }
  19374. // set foreground color
  19375. $this->SetDrawColorArray($style['fgcolor']);
  19376. $this->SetTextColorArray($style['fgcolor']);
  19377. // print bars
  19378. foreach ($arrcode['bcode'] as $k => $v) {
  19379. $bw = ($v['w'] * $xres);
  19380. if ($v['t']) {
  19381. // draw a vertical bar
  19382. $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
  19383. $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
  19384. }
  19385. $xpos += $bw;
  19386. }
  19387. // print text
  19388. if ($style['text']) {
  19389. if (isset($style['label']) AND !$this->empty_string($style['label'])) {
  19390. $label = $style['label'];
  19391. } else {
  19392. $label = $code;
  19393. }
  19394. $txtwidth = ($arrcode['maxw'] * $xres);
  19395. if ($this->GetStringWidth($label) > $txtwidth) {
  19396. $style['stretchtext'] = 2;
  19397. }
  19398. // print text
  19399. $this->x = $xpos_text;
  19400. $this->y = $y + $vpadding + $barh;
  19401. $cellpadding = $this->cell_padding;
  19402. $this->SetCellPadding(0);
  19403. $this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
  19404. $this->cell_padding = $cellpadding;
  19405. }
  19406. // restore original direction
  19407. $this->rtl = $tempRTL;
  19408. // restore previous settings
  19409. $this->setGraphicVars($gvars);
  19410. // set pointer to align the next text/objects
  19411. switch($align) {
  19412. case 'T':{
  19413. $this->y = $y;
  19414. $this->x = $this->img_rb_x;
  19415. break;
  19416. }
  19417. case 'M':{
  19418. $this->y = $y + round($h / 2);
  19419. $this->x = $this->img_rb_x;
  19420. break;
  19421. }
  19422. case 'B':{
  19423. $this->y = $this->img_rb_y;
  19424. $this->x = $this->img_rb_x;
  19425. break;
  19426. }
  19427. case 'N':{
  19428. $this->SetY($this->img_rb_y);
  19429. break;
  19430. }
  19431. default:{
  19432. break;
  19433. }
  19434. }
  19435. $this->endlinex = $this->img_rb_x;
  19436. }
  19437. /**
  19438. * This function is DEPRECATED, please use the new write1DBarcode() function.
  19439. * @param $x (int) x position in user units
  19440. * @param $y (int) y position in user units
  19441. * @param $w (int) width in user units
  19442. * @param $h (int) height position in user units
  19443. * @param $type (string) type of barcode
  19444. * @param $style (string) barcode style
  19445. * @param $font (string) font for text
  19446. * @param $xres (int) x resolution
  19447. * @param $code (string) code to print
  19448. * @deprecated deprecated since version 3.1.000 (2008-06-10)
  19449. * @public
  19450. * @see write1DBarcode()
  19451. */
  19452. public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
  19453. // convert old settings for the new write1DBarcode() function.
  19454. $xres = 1 / $xres;
  19455. $newstyle = array(
  19456. 'position' => '',
  19457. 'align' => '',
  19458. 'stretch' => false,
  19459. 'fitwidth' => false,
  19460. 'cellfitalign' => '',
  19461. 'border' => false,
  19462. 'padding' => 0,
  19463. 'fgcolor' => array(0,0,0),
  19464. 'bgcolor' => false,
  19465. 'text' => true,
  19466. 'font' => $font,
  19467. 'fontsize' => 8,
  19468. 'stretchtext' => 4
  19469. );
  19470. if ($style & 1) {
  19471. $newstyle['border'] = true;
  19472. }
  19473. if ($style & 2) {
  19474. $newstyle['bgcolor'] = false;
  19475. }
  19476. if ($style & 4) {
  19477. $newstyle['position'] = 'C';
  19478. } elseif ($style & 8) {
  19479. $newstyle['position'] = 'L';
  19480. } elseif ($style & 16) {
  19481. $newstyle['position'] = 'R';
  19482. }
  19483. if ($style & 128) {
  19484. $newstyle['text'] = true;
  19485. }
  19486. if ($style & 256) {
  19487. $newstyle['stretchtext'] = 4;
  19488. }
  19489. $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
  19490. }
  19491. /**
  19492. * Print 2D Barcode.
  19493. * @param $code (string) code to print
  19494. * @param $type (string) type of barcode (see 2dbarcodes.php for supported formats).
  19495. * @param $x (int) x position in user units
  19496. * @param $y (int) y position in user units
  19497. * @param $w (int) width in user units
  19498. * @param $h (int) height in user units
  19499. * @param $style (array) array of options:<ul>
  19500. * <li>boolean $style['border'] if true prints a border around the barcode</li>
  19501. * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
  19502. * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
  19503. * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
  19504. * <li>int $style['module_width'] width of a single module in points</li>
  19505. * <li>int $style['module_height'] height of a single module in points</li>
  19506. * <li>array $style['fgcolor'] color array for bars and text</li>
  19507. * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
  19508. * <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>
  19509. * <li>$style['module_height'] height of a single module in points</li></ul>
  19510. * @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>
  19511. * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
  19512. * @author Nicola Asuni
  19513. * @since 4.5.037 (2009-04-07)
  19514. * @public
  19515. */
  19516. public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='', $distort=false) {
  19517. if ($this->empty_string(trim($code))) {
  19518. return;
  19519. }
  19520. require_once(dirname(__FILE__).'/2dbarcodes.php');
  19521. // save current graphic settings
  19522. $gvars = $this->getGraphicVars();
  19523. // create new barcode object
  19524. $barcodeobj = new TCPDF2DBarcode($code, $type);
  19525. $arrcode = $barcodeobj->getBarcodeArray();
  19526. if (($arrcode === false) OR empty($arrcode) OR !isset($arrcode['num_rows']) OR ($arrcode['num_rows'] == 0) OR !isset($arrcode['num_cols']) OR ($arrcode['num_cols'] == 0)) {
  19527. $this->Error('Error in 2D barcode string');
  19528. }
  19529. // set default values
  19530. if (!isset($style['position'])) {
  19531. $style['position'] = '';
  19532. }
  19533. if (!isset($style['fgcolor'])) {
  19534. $style['fgcolor'] = array(0,0,0); // default black
  19535. }
  19536. if (!isset($style['bgcolor'])) {
  19537. $style['bgcolor'] = false; // default transparent
  19538. }
  19539. if (!isset($style['border'])) {
  19540. $style['border'] = false;
  19541. }
  19542. // padding
  19543. if (!isset($style['padding'])) {
  19544. $style['padding'] = 0;
  19545. } elseif ($style['padding'] === 'auto') {
  19546. $style['padding'] = 4;
  19547. }
  19548. if (!isset($style['hpadding'])) {
  19549. $style['hpadding'] = $style['padding'];
  19550. } elseif ($style['hpadding'] === 'auto') {
  19551. $style['hpadding'] = 4;
  19552. }
  19553. if (!isset($style['vpadding'])) {
  19554. $style['vpadding'] = $style['padding'];
  19555. } elseif ($style['vpadding'] === 'auto') {
  19556. $style['vpadding'] = 4;
  19557. }
  19558. $hpad = (2 * $style['hpadding']);
  19559. $vpad = (2 * $style['vpadding']);
  19560. // cell (module) dimension
  19561. if (!isset($style['module_width'])) {
  19562. $style['module_width'] = 1; // width of a single module in points
  19563. }
  19564. if (!isset($style['module_height'])) {
  19565. $style['module_height'] = 1; // height of a single module in points
  19566. }
  19567. if ($x === '') {
  19568. $x = $this->x;
  19569. }
  19570. if ($y === '') {
  19571. $y = $this->y;
  19572. }
  19573. // check page for no-write regions and adapt page margins if necessary
  19574. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  19575. // number of barcode columns and rows
  19576. $rows = $arrcode['num_rows'];
  19577. $cols = $arrcode['num_cols'];
  19578. // module width and height
  19579. $mw = $style['module_width'];
  19580. $mh = $style['module_height'];
  19581. if (($mw == 0) OR ($mh == 0)) {
  19582. $this->Error('Error in 2D barcode string');
  19583. }
  19584. // get max dimensions
  19585. if ($this->rtl) {
  19586. $maxw = $x - $this->lMargin;
  19587. } else {
  19588. $maxw = $this->w - $this->rMargin - $x;
  19589. }
  19590. $maxh = ($this->h - $this->tMargin - $this->bMargin);
  19591. $ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
  19592. $ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
  19593. if (!$distort) {
  19594. if (($maxw * $ratioHW) > $maxh) {
  19595. $maxw = $maxh * $ratioWH;
  19596. }
  19597. if (($maxh * $ratioWH) > $maxw) {
  19598. $maxh = $maxw * $ratioHW;
  19599. }
  19600. }
  19601. // set maximum dimesions
  19602. if ($w > $maxw) {
  19603. $w = $maxw;
  19604. }
  19605. if ($h > $maxh) {
  19606. $h = $maxh;
  19607. }
  19608. // set dimensions
  19609. if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
  19610. $w = ($cols + $hpad) * ($mw / $this->k);
  19611. $h = ($rows + $vpad) * ($mh / $this->k);
  19612. } elseif (($w === '') OR ($w <= 0)) {
  19613. $w = $h * $ratioWH;
  19614. } elseif (($h === '') OR ($h <= 0)) {
  19615. $h = $w * $ratioHW;
  19616. }
  19617. // barcode size (excluding padding)
  19618. $bw = ($w * $cols) / ($cols + $hpad);
  19619. $bh = ($h * $rows) / ($rows + $vpad);
  19620. // dimension of single barcode cell unit
  19621. $cw = $bw / $cols;
  19622. $ch = $bh / $rows;
  19623. if (!$distort) {
  19624. if (($cw / $ch) > ($mw / $mh)) {
  19625. // correct horizontal distortion
  19626. $cw = $ch * $mw / $mh;
  19627. $bw = $cw * $cols;
  19628. $style['hpadding'] = ($w - $bw) / (2 * $cw);
  19629. } else {
  19630. // correct vertical distortion
  19631. $ch = $cw * $mh / $mw;
  19632. $bh = $ch * $rows;
  19633. $style['vpadding'] = ($h - $bh) / (2 * $ch);
  19634. }
  19635. }
  19636. // fit the barcode on available space
  19637. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  19638. // set alignment
  19639. $this->img_rb_y = $y + $h;
  19640. // set alignment
  19641. if ($this->rtl) {
  19642. if ($style['position'] == 'L') {
  19643. $xpos = $this->lMargin;
  19644. } elseif ($style['position'] == 'C') {
  19645. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  19646. } elseif ($style['position'] == 'R') {
  19647. $xpos = $this->w - $this->rMargin - $w;
  19648. } else {
  19649. $xpos = $x - $w;
  19650. }
  19651. $this->img_rb_x = $xpos;
  19652. } else {
  19653. if ($style['position'] == 'L') {
  19654. $xpos = $this->lMargin;
  19655. } elseif ($style['position'] == 'C') {
  19656. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  19657. } elseif ($style['position'] == 'R') {
  19658. $xpos = $this->w - $this->rMargin - $w;
  19659. } else {
  19660. $xpos = $x;
  19661. }
  19662. $this->img_rb_x = $xpos + $w;
  19663. }
  19664. $xstart = $xpos + ($style['hpadding'] * $cw);
  19665. $ystart = $y + ($style['vpadding'] * $ch);
  19666. // barcode is always printed in LTR direction
  19667. $tempRTL = $this->rtl;
  19668. $this->rtl = false;
  19669. // print background color
  19670. if ($style['bgcolor']) {
  19671. $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  19672. } elseif ($style['border']) {
  19673. $this->Rect($xpos, $y, $w, $h, 'D');
  19674. }
  19675. // set foreground color
  19676. $this->SetDrawColorArray($style['fgcolor']);
  19677. // print barcode cells
  19678. // for each row
  19679. for ($r = 0; $r < $rows; ++$r) {
  19680. $xr = $xstart;
  19681. // for each column
  19682. for ($c = 0; $c < $cols; ++$c) {
  19683. if ($arrcode['bcode'][$r][$c] == 1) {
  19684. // draw a single barcode cell
  19685. $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
  19686. }
  19687. $xr += $cw;
  19688. }
  19689. $ystart += $ch;
  19690. }
  19691. // restore original direction
  19692. $this->rtl = $tempRTL;
  19693. // restore previous settings
  19694. $this->setGraphicVars($gvars);
  19695. // set pointer to align the next text/objects
  19696. switch($align) {
  19697. case 'T':{
  19698. $this->y = $y;
  19699. $this->x = $this->img_rb_x;
  19700. break;
  19701. }
  19702. case 'M':{
  19703. $this->y = $y + round($h/2);
  19704. $this->x = $this->img_rb_x;
  19705. break;
  19706. }
  19707. case 'B':{
  19708. $this->y = $this->img_rb_y;
  19709. $this->x = $this->img_rb_x;
  19710. break;
  19711. }
  19712. case 'N':{
  19713. $this->SetY($this->img_rb_y);
  19714. break;
  19715. }
  19716. default:{
  19717. break;
  19718. }
  19719. }
  19720. $this->endlinex = $this->img_rb_x;
  19721. }
  19722. /**
  19723. * Returns an array containing current margins:
  19724. * <ul>
  19725. <li>$ret['left'] = left margin</li>
  19726. <li>$ret['right'] = right margin</li>
  19727. <li>$ret['top'] = top margin</li>
  19728. <li>$ret['bottom'] = bottom margin</li>
  19729. <li>$ret['header'] = header margin</li>
  19730. <li>$ret['footer'] = footer margin</li>
  19731. <li>$ret['cell'] = cell padding array</li>
  19732. <li>$ret['padding_left'] = cell left padding</li>
  19733. <li>$ret['padding_top'] = cell top padding</li>
  19734. <li>$ret['padding_right'] = cell right padding</li>
  19735. <li>$ret['padding_bottom'] = cell bottom padding</li>
  19736. * </ul>
  19737. * @return array containing all margins measures
  19738. * @public
  19739. * @since 3.2.000 (2008-06-23)
  19740. */
  19741. public function getMargins() {
  19742. $ret = array(
  19743. 'left' => $this->lMargin,
  19744. 'right' => $this->rMargin,
  19745. 'top' => $this->tMargin,
  19746. 'bottom' => $this->bMargin,
  19747. 'header' => $this->header_margin,
  19748. 'footer' => $this->footer_margin,
  19749. 'cell' => $this->cell_padding,
  19750. 'padding_left' => $this->cell_padding['L'],
  19751. 'padding_top' => $this->cell_padding['T'],
  19752. 'padding_right' => $this->cell_padding['R'],
  19753. 'padding_bottom' => $this->cell_padding['B']
  19754. );
  19755. return $ret;
  19756. }
  19757. /**
  19758. * Returns an array containing original margins:
  19759. * <ul>
  19760. <li>$ret['left'] = left margin</li>
  19761. <li>$ret['right'] = right margin</li>
  19762. * </ul>
  19763. * @return array containing all margins measures
  19764. * @public
  19765. * @since 4.0.012 (2008-07-24)
  19766. */
  19767. public function getOriginalMargins() {
  19768. $ret = array(
  19769. 'left' => $this->original_lMargin,
  19770. 'right' => $this->original_rMargin
  19771. );
  19772. return $ret;
  19773. }
  19774. /**
  19775. * Returns the current font size.
  19776. * @return current font size
  19777. * @public
  19778. * @since 3.2.000 (2008-06-23)
  19779. */
  19780. public function getFontSize() {
  19781. return $this->FontSize;
  19782. }
  19783. /**
  19784. * Returns the current font size in points unit.
  19785. * @return current font size in points unit
  19786. * @public
  19787. * @since 3.2.000 (2008-06-23)
  19788. */
  19789. public function getFontSizePt() {
  19790. return $this->FontSizePt;
  19791. }
  19792. /**
  19793. * Returns the current font family name.
  19794. * @return string current font family name
  19795. * @public
  19796. * @since 4.3.008 (2008-12-05)
  19797. */
  19798. public function getFontFamily() {
  19799. return $this->FontFamily;
  19800. }
  19801. /**
  19802. * Returns the current font style.
  19803. * @return string current font style
  19804. * @public
  19805. * @since 4.3.008 (2008-12-05)
  19806. */
  19807. public function getFontStyle() {
  19808. return $this->FontStyle;
  19809. }
  19810. /**
  19811. * Cleanup HTML code (requires HTML Tidy library).
  19812. * @param $html (string) htmlcode to fix
  19813. * @param $default_css (string) CSS commands to add
  19814. * @param $tagvs (array) parameters for setHtmlVSpace method
  19815. * @param $tidy_options (array) options for tidy_parse_string function
  19816. * @return string XHTML code cleaned up
  19817. * @author Nicola Asuni
  19818. * @public
  19819. * @since 5.9.017 (2010-11-16)
  19820. * @see setHtmlVSpace()
  19821. */
  19822. public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
  19823. // configure parameters for HTML Tidy
  19824. if ($tidy_options === '') {
  19825. $tidy_options = array (
  19826. 'clean' => 1,
  19827. 'drop-empty-paras' => 0,
  19828. 'drop-proprietary-attributes' => 1,
  19829. 'fix-backslash' => 1,
  19830. 'hide-comments' => 1,
  19831. 'join-styles' => 1,
  19832. 'lower-literals' => 1,
  19833. 'merge-divs' => 1,
  19834. 'merge-spans' => 1,
  19835. 'output-xhtml' => 1,
  19836. 'word-2000' => 1,
  19837. 'wrap' => 0,
  19838. 'output-bom' => 0,
  19839. //'char-encoding' => 'utf8',
  19840. //'input-encoding' => 'utf8',
  19841. //'output-encoding' => 'utf8'
  19842. );
  19843. }
  19844. // clean up the HTML code
  19845. $tidy = tidy_parse_string($html, $tidy_options);
  19846. // fix the HTML
  19847. $tidy->cleanRepair();
  19848. // get the CSS part
  19849. $tidy_head = tidy_get_head($tidy);
  19850. $css = $tidy_head->value;
  19851. $css = preg_replace('/<style([^>]+)>/ims', '<style>', $css);
  19852. $css = preg_replace('/<\/style>(.*)<style>/ims', "\n", $css);
  19853. $css = str_replace('/*<![CDATA[*/', '', $css);
  19854. $css = str_replace('/*]]>*/', '', $css);
  19855. preg_match('/<style>(.*)<\/style>/ims', $css, $matches);
  19856. if (isset($matches[1])) {
  19857. $css = strtolower($matches[1]);
  19858. } else {
  19859. $css = '';
  19860. }
  19861. // include default css
  19862. $css = '<style>'.$default_css.$css.'</style>';
  19863. // get the body part
  19864. $tidy_body = tidy_get_body($tidy);
  19865. $html = $tidy_body->value;
  19866. // fix some self-closing tags
  19867. $html = str_replace('<br>', '<br />', $html);
  19868. // remove some empty tag blocks
  19869. $html = preg_replace('/<div([^\>]*)><\/div>/', '', $html);
  19870. $html = preg_replace('/<p([^\>]*)><\/p>/', '', $html);
  19871. if ($tagvs !== '') {
  19872. // set vertical space for some XHTML tags
  19873. $this->setHtmlVSpace($tagvs);
  19874. }
  19875. // return the cleaned XHTML code + CSS
  19876. return $css.$html;
  19877. }
  19878. /**
  19879. * Extracts the CSS properties from a CSS string.
  19880. * @param $cssdata (string) string containing CSS definitions.
  19881. * @return An array where the keys are the CSS selectors and the values are the CSS properties.
  19882. * @author Nicola Asuni
  19883. * @since 5.1.000 (2010-05-25)
  19884. * @protected
  19885. */
  19886. protected function extractCSSproperties($cssdata) {
  19887. if (empty($cssdata)) {
  19888. return array();
  19889. }
  19890. // remove comments
  19891. $cssdata = preg_replace('/\/\*[^\*]*\*\//', '', $cssdata);
  19892. // remove newlines and multiple spaces
  19893. $cssdata = preg_replace('/[\s]+/', ' ', $cssdata);
  19894. // remove some spaces
  19895. $cssdata = preg_replace('/[\s]*([;:\{\}]{1})[\s]*/', '\\1', $cssdata);
  19896. // remove empty blocks
  19897. $cssdata = preg_replace('/([^\}\{]+)\{\}/', '', $cssdata);
  19898. // replace media type parenthesis
  19899. $cssdata = preg_replace('/@media[\s]+([^\{]*)\{/i', '@media \\1§', $cssdata);
  19900. $cssdata = preg_replace('/\}\}/si', '}§', $cssdata);
  19901. // trim string
  19902. $cssdata = trim($cssdata);
  19903. // find media blocks (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  19904. $cssblocks = array();
  19905. $matches = array();
  19906. if (preg_match_all('/@media[\s]+([^\§]*)§([^§]*)§/i', $cssdata, $matches) > 0) {
  19907. foreach ($matches[1] as $key => $type) {
  19908. $cssblocks[$type] = $matches[2][$key];
  19909. }
  19910. // remove media blocks
  19911. $cssdata = preg_replace('/@media[\s]+([^\§]*)§([^§]*)§/i', '', $cssdata);
  19912. }
  19913. // keep 'all' and 'print' media, other media types are discarded
  19914. if (isset($cssblocks['all']) AND !empty($cssblocks['all'])) {
  19915. $cssdata .= $cssblocks['all'];
  19916. }
  19917. if (isset($cssblocks['print']) AND !empty($cssblocks['print'])) {
  19918. $cssdata .= $cssblocks['print'];
  19919. }
  19920. // reset css blocks array
  19921. $cssblocks = array();
  19922. $matches = array();
  19923. // explode css data string into array
  19924. if (substr($cssdata, -1) == '}') {
  19925. // remove last parethesis
  19926. $cssdata = substr($cssdata, 0, -1);
  19927. }
  19928. $matches = explode('}', $cssdata);
  19929. foreach ($matches as $key => $block) {
  19930. // index 0 contains the CSS selector, index 1 contains CSS properties
  19931. $cssblocks[$key] = explode('{', $block);
  19932. if (!isset($cssblocks[$key][1])) {
  19933. // remove empty definitions
  19934. unset($cssblocks[$key]);
  19935. }
  19936. }
  19937. // split groups of selectors (comma-separated list of selectors)
  19938. foreach ($cssblocks as $key => $block) {
  19939. if (strpos($block[0], ',') > 0) {
  19940. $selectors = explode(',', $block[0]);
  19941. foreach ($selectors as $sel) {
  19942. $cssblocks[] = array(0 => trim($sel), 1 => $block[1]);
  19943. }
  19944. unset($cssblocks[$key]);
  19945. }
  19946. }
  19947. // covert array to selector => properties
  19948. $cssdata = array();
  19949. foreach ($cssblocks as $block) {
  19950. $selector = $block[0];
  19951. // calculate selector's specificity
  19952. $matches = array();
  19953. $a = 0; // the declaration is not from is a 'style' attribute
  19954. $b = intval(preg_match_all('/[\#]/', $selector, $matches)); // number of ID attributes
  19955. $c = intval(preg_match_all('/[\[\.]/', $selector, $matches)); // number of other attributes
  19956. $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
  19957. $d = intval(preg_match_all('/[\>\+\~\s]{1}[a-zA-Z0-9]+/', ' '.$selector, $matches)); // number of element names
  19958. $d += intval(preg_match_all('/[\:][\:]/', $selector, $matches)); // number of pseudo-elements
  19959. $specificity = $a.$b.$c.$d;
  19960. // add specificity to the beginning of the selector
  19961. $cssdata[$specificity.' '.$selector] = $block[1];
  19962. }
  19963. // sort selectors alphabetically to account for specificity
  19964. ksort($cssdata, SORT_STRING);
  19965. // return array
  19966. return $cssdata;
  19967. }
  19968. /**
  19969. * Returns true if the CSS selector is valid for the selected HTML tag
  19970. * @param $dom (array) array of HTML tags and properties
  19971. * @param $key (int) key of the current HTML tag
  19972. * @param $selector (string) CSS selector string
  19973. * @return true if the selector is valid, false otherwise
  19974. * @protected
  19975. * @since 5.1.000 (2010-05-25)
  19976. */
  19977. protected function isValidCSSSelectorForTag($dom, $key, $selector) {
  19978. $valid = false; // value to be returned
  19979. $tag = $dom[$key]['value'];
  19980. $class = array();
  19981. if (isset($dom[$key]['attribute']['class']) AND !empty($dom[$key]['attribute']['class'])) {
  19982. $class = explode(' ', strtolower($dom[$key]['attribute']['class']));
  19983. }
  19984. $id = '';
  19985. if (isset($dom[$key]['attribute']['id']) AND !empty($dom[$key]['attribute']['id'])) {
  19986. $id = strtolower($dom[$key]['attribute']['id']);
  19987. }
  19988. $selector = preg_replace('/([\>\+\~\s]{1})([\.]{1})([^\>\+\~\s]*)/si', '\\1*.\\3', $selector);
  19989. $matches = array();
  19990. if (preg_match_all('/([\>\+\~\s]{1})([a-zA-Z0-9\*]+)([^\>\+\~\s]*)/si', $selector, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE) > 0) {
  19991. $parentop = array_pop($matches[1]);
  19992. $operator = $parentop[0];
  19993. $offset = $parentop[1];
  19994. $lasttag = array_pop($matches[2]);
  19995. $lasttag = strtolower(trim($lasttag[0]));
  19996. if (($lasttag == '*') OR ($lasttag == $tag)) {
  19997. // the last element on selector is our tag or 'any tag'
  19998. $attrib = array_pop($matches[3]);
  19999. $attrib = strtolower(trim($attrib[0]));
  20000. if (!empty($attrib)) {
  20001. // check if matches class, id, attribute, pseudo-class or pseudo-element
  20002. switch ($attrib{0}) {
  20003. case '.': { // class
  20004. if (in_array(substr($attrib, 1), $class)) {
  20005. $valid = true;
  20006. }
  20007. break;
  20008. }
  20009. case '#': { // ID
  20010. if (substr($attrib, 1) == $id) {
  20011. $valid = true;
  20012. }
  20013. break;
  20014. }
  20015. case '[': { // attribute
  20016. $attrmatch = array();
  20017. if (preg_match('/\[([a-zA-Z0-9]*)[\s]*([\~\^\$\*\|\=]*)[\s]*["]?([^"\]]*)["]?\]/i', $attrib, $attrmatch) > 0) {
  20018. $att = strtolower($attrmatch[1]);
  20019. $val = $attrmatch[3];
  20020. if (isset($dom[$key]['attribute'][$att])) {
  20021. switch ($attrmatch[2]) {
  20022. case '=': {
  20023. if ($dom[$key]['attribute'][$att] == $val) {
  20024. $valid = true;
  20025. }
  20026. break;
  20027. }
  20028. case '~=': {
  20029. if (in_array($val, explode(' ', $dom[$key]['attribute'][$att]))) {
  20030. $valid = true;
  20031. }
  20032. break;
  20033. }
  20034. case '^=': {
  20035. if ($val == substr($dom[$key]['attribute'][$att], 0, strlen($val))) {
  20036. $valid = true;
  20037. }
  20038. break;
  20039. }
  20040. case '$=': {
  20041. if ($val == substr($dom[$key]['attribute'][$att], -strlen($val))) {
  20042. $valid = true;
  20043. }
  20044. break;
  20045. }
  20046. case '*=': {
  20047. if (strpos($dom[$key]['attribute'][$att], $val) !== false) {
  20048. $valid = true;
  20049. }
  20050. break;
  20051. }
  20052. case '|=': {
  20053. if ($dom[$key]['attribute'][$att] == $val) {
  20054. $valid = true;
  20055. } elseif (preg_match('/'.$val.'[\-]{1}/i', $dom[$key]['attribute'][$att]) > 0) {
  20056. $valid = true;
  20057. }
  20058. break;
  20059. }
  20060. default: {
  20061. $valid = true;
  20062. }
  20063. }
  20064. }
  20065. }
  20066. break;
  20067. }
  20068. case ':': { // pseudo-class or pseudo-element
  20069. if ($attrib{1} == ':') { // pseudo-element
  20070. // pseudo-elements are not supported!
  20071. // (::first-line, ::first-letter, ::before, ::after)
  20072. } else { // pseudo-class
  20073. // pseudo-classes are not supported!
  20074. // (: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)
  20075. }
  20076. break;
  20077. }
  20078. } // end of switch
  20079. } else {
  20080. $valid = true;
  20081. }
  20082. if ($valid AND ($offset > 0)) {
  20083. $valid = false;
  20084. // check remaining selector part
  20085. $selector = substr($selector, 0, $offset);
  20086. switch ($operator) {
  20087. case ' ': { // descendant of an element
  20088. while ($dom[$key]['parent'] > 0) {
  20089. if ($this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector)) {
  20090. $valid = true;
  20091. break;
  20092. } else {
  20093. $key = $dom[$key]['parent'];
  20094. }
  20095. }
  20096. break;
  20097. }
  20098. case '>': { // child of an element
  20099. $valid = $this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector);
  20100. break;
  20101. }
  20102. case '+': { // immediately preceded by an element
  20103. for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
  20104. if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
  20105. $valid = $this->isValidCSSSelectorForTag($dom, $i, $selector);
  20106. break;
  20107. }
  20108. }
  20109. break;
  20110. }
  20111. case '~': { // preceded by an element
  20112. for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
  20113. if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
  20114. if ($this->isValidCSSSelectorForTag($dom, $i, $selector)) {
  20115. break;
  20116. }
  20117. }
  20118. }
  20119. break;
  20120. }
  20121. }
  20122. }
  20123. }
  20124. }
  20125. return $valid;
  20126. }
  20127. /**
  20128. * Returns the styles array that apply for the selected HTML tag.
  20129. * @param $dom (array) array of HTML tags and properties
  20130. * @param $key (int) key of the current HTML tag
  20131. * @param $css (array) array of CSS properties
  20132. * @return array containing CSS properties
  20133. * @protected
  20134. * @since 5.1.000 (2010-05-25)
  20135. */
  20136. protected function getCSSdataArray($dom, $key, $css) {
  20137. $cssarray = array(); // style to be returned
  20138. // get parent CSS selectors
  20139. $selectors = array();
  20140. if (isset($dom[($dom[$key]['parent'])]['csssel'])) {
  20141. $selectors = $dom[($dom[$key]['parent'])]['csssel'];
  20142. }
  20143. // get all styles that apply
  20144. foreach($css as $selector => $style) {
  20145. $pos = strpos($selector, ' ');
  20146. // get specificity
  20147. $specificity = substr($selector, 0, $pos);
  20148. // remove specificity
  20149. $selector = substr($selector, $pos);
  20150. // check if this selector apply to current tag
  20151. if ($this->isValidCSSSelectorForTag($dom, $key, $selector)) {
  20152. if (!in_array($selector, $selectors)) {
  20153. // add style if not already added on parent selector
  20154. $cssarray[] = array('k' => $selector, 's' => $specificity, 'c' => $style);
  20155. $selectors[] = $selector;
  20156. }
  20157. }
  20158. }
  20159. if (isset($dom[$key]['attribute']['style'])) {
  20160. // attach inline style (latest properties have high priority)
  20161. $cssarray[] = array('k' => '', 's' => '1000', 'c' => $dom[$key]['attribute']['style']);
  20162. }
  20163. // order the css array to account for specificity
  20164. $cssordered = array();
  20165. foreach ($cssarray as $key => $val) {
  20166. $skey = sprintf('%04d', $key);
  20167. $cssordered[$val['s'].'_'.$skey] = $val;
  20168. }
  20169. // sort selectors alphabetically to account for specificity
  20170. ksort($cssordered, SORT_STRING);
  20171. return array($selectors, $cssordered);
  20172. }
  20173. /**
  20174. * Compact CSS data array into single string.
  20175. * @param $css (array) array of CSS properties
  20176. * @return string containing merged CSS properties
  20177. * @protected
  20178. * @since 5.9.070 (2011-04-19)
  20179. */
  20180. protected function getTagStyleFromCSSarray($css) {
  20181. $tagstyle = ''; // value to be returned
  20182. foreach ($css as $style) {
  20183. // split single css commands
  20184. $csscmds = explode(';', $style['c']);
  20185. foreach ($csscmds as $cmd) {
  20186. if (!empty($cmd)) {
  20187. $pos = strpos($cmd, ':');
  20188. if ($pos !== false) {
  20189. $cmd = substr($cmd, 0, ($pos + 1));
  20190. if (strpos($tagstyle, $cmd) !== false) {
  20191. // remove duplicate commands (last commands have high priority)
  20192. $tagstyle = preg_replace('/'.$cmd.'[^;]+/i', '', $tagstyle);
  20193. }
  20194. }
  20195. }
  20196. }
  20197. $tagstyle .= ';'.$style['c'];
  20198. }
  20199. // remove multiple semicolons
  20200. $tagstyle = preg_replace('/[;]+/', ';', $tagstyle);
  20201. return $tagstyle;
  20202. }
  20203. /**
  20204. * Returns the border width from CSS property
  20205. * @param $width (string) border width
  20206. * @return int with in user units
  20207. * @protected
  20208. * @since 5.7.000 (2010-08-02)
  20209. */
  20210. protected function getCSSBorderWidth($width) {
  20211. if ($width == 'thin') {
  20212. $width = (2 / $this->k);
  20213. } elseif ($width == 'medium') {
  20214. $width = (4 / $this->k);
  20215. } elseif ($width == 'thick') {
  20216. $width = (6 / $this->k);
  20217. } else {
  20218. $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
  20219. }
  20220. return $width;
  20221. }
  20222. /**
  20223. * Returns the border dash style from CSS property
  20224. * @param $style (string) border style to convert
  20225. * @return int sash style (return -1 in case of none or hidden border)
  20226. * @protected
  20227. * @since 5.7.000 (2010-08-02)
  20228. */
  20229. protected function getCSSBorderDashStyle($style) {
  20230. switch (strtolower($style)) {
  20231. case 'none':
  20232. case 'hidden': {
  20233. $dash = -1;
  20234. break;
  20235. }
  20236. case 'dotted': {
  20237. $dash = 1;
  20238. break;
  20239. }
  20240. case 'dashed': {
  20241. $dash = 3;
  20242. break;
  20243. }
  20244. case 'double':
  20245. case 'groove':
  20246. case 'ridge':
  20247. case 'inset':
  20248. case 'outset':
  20249. case 'solid':
  20250. default: {
  20251. $dash = 0;
  20252. break;
  20253. }
  20254. }
  20255. return $dash;
  20256. }
  20257. /**
  20258. * Returns the border style array from CSS border properties
  20259. * @param $cssborder (string) border properties
  20260. * @return array containing border properties
  20261. * @protected
  20262. * @since 5.7.000 (2010-08-02)
  20263. */
  20264. protected function getCSSBorderStyle($cssborder) {
  20265. $bprop = preg_split('/[\s]+/', trim($cssborder));
  20266. $border = array(); // value to be returned
  20267. switch (count($bprop)) {
  20268. case 3: {
  20269. $width = $bprop[0];
  20270. $style = $bprop[1];
  20271. $color = $bprop[2];
  20272. break;
  20273. }
  20274. case 2: {
  20275. $width = 'medium';
  20276. $style = $bprop[0];
  20277. $color = $bprop[1];
  20278. break;
  20279. }
  20280. case 1: {
  20281. $width = 'medium';
  20282. $style = $bprop[0];
  20283. $color = 'black';
  20284. break;
  20285. }
  20286. default: {
  20287. $width = 'medium';
  20288. $style = 'solid';
  20289. $color = 'black';
  20290. break;
  20291. }
  20292. }
  20293. if ($style == 'none') {
  20294. return array();
  20295. }
  20296. $border['cap'] = 'square';
  20297. $border['join'] = 'miter';
  20298. $border['dash'] = $this->getCSSBorderDashStyle($style);
  20299. if ($border['dash'] < 0) {
  20300. return array();
  20301. }
  20302. $border['width'] = $this->getCSSBorderWidth($width);
  20303. $border['color'] = $this->convertHTMLColorToDec($color);
  20304. return $border;
  20305. }
  20306. /**
  20307. * Get the internal Cell padding from CSS attribute.
  20308. * @param $csspadding (string) padding properties
  20309. * @param $width (float) width of the containing element
  20310. * @return array of cell paddings
  20311. * @public
  20312. * @since 5.9.000 (2010-10-04)
  20313. */
  20314. public function getCSSPadding($csspadding, $width=0) {
  20315. $padding = preg_split('/[\s]+/', trim($csspadding));
  20316. $cell_padding = array(); // value to be returned
  20317. switch (count($padding)) {
  20318. case 4: {
  20319. $cell_padding['T'] = $padding[0];
  20320. $cell_padding['R'] = $padding[1];
  20321. $cell_padding['B'] = $padding[2];
  20322. $cell_padding['L'] = $padding[3];
  20323. break;
  20324. }
  20325. case 3: {
  20326. $cell_padding['T'] = $padding[0];
  20327. $cell_padding['R'] = $padding[1];
  20328. $cell_padding['B'] = $padding[2];
  20329. $cell_padding['L'] = $padding[1];
  20330. break;
  20331. }
  20332. case 2: {
  20333. $cell_padding['T'] = $padding[0];
  20334. $cell_padding['R'] = $padding[1];
  20335. $cell_padding['B'] = $padding[0];
  20336. $cell_padding['L'] = $padding[1];
  20337. break;
  20338. }
  20339. case 1: {
  20340. $cell_padding['T'] = $padding[0];
  20341. $cell_padding['R'] = $padding[0];
  20342. $cell_padding['B'] = $padding[0];
  20343. $cell_padding['L'] = $padding[0];
  20344. break;
  20345. }
  20346. default: {
  20347. return $this->cell_padding;
  20348. }
  20349. }
  20350. if ($width == 0) {
  20351. $width = $this->w - $this->lMargin - $this->rMargin;
  20352. }
  20353. $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
  20354. $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
  20355. $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
  20356. $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
  20357. return $cell_padding;
  20358. }
  20359. /**
  20360. * Get the internal Cell margin from CSS attribute.
  20361. * @param $cssmargin (string) margin properties
  20362. * @param $width (float) width of the containing element
  20363. * @return array of cell margins
  20364. * @public
  20365. * @since 5.9.000 (2010-10-04)
  20366. */
  20367. public function getCSSMargin($cssmargin, $width=0) {
  20368. $margin = preg_split('/[\s]+/', trim($cssmargin));
  20369. $cell_margin = array(); // value to be returned
  20370. switch (count($margin)) {
  20371. case 4: {
  20372. $cell_margin['T'] = $margin[0];
  20373. $cell_margin['R'] = $margin[1];
  20374. $cell_margin['B'] = $margin[2];
  20375. $cell_margin['L'] = $margin[3];
  20376. break;
  20377. }
  20378. case 3: {
  20379. $cell_margin['T'] = $margin[0];
  20380. $cell_margin['R'] = $margin[1];
  20381. $cell_margin['B'] = $margin[2];
  20382. $cell_margin['L'] = $margin[1];
  20383. break;
  20384. }
  20385. case 2: {
  20386. $cell_margin['T'] = $margin[0];
  20387. $cell_margin['R'] = $margin[1];
  20388. $cell_margin['B'] = $margin[0];
  20389. $cell_margin['L'] = $margin[1];
  20390. break;
  20391. }
  20392. case 1: {
  20393. $cell_margin['T'] = $margin[0];
  20394. $cell_margin['R'] = $margin[0];
  20395. $cell_margin['B'] = $margin[0];
  20396. $cell_margin['L'] = $margin[0];
  20397. break;
  20398. }
  20399. default: {
  20400. return $this->cell_margin;
  20401. }
  20402. }
  20403. if ($width == 0) {
  20404. $width = $this->w - $this->lMargin - $this->rMargin;
  20405. }
  20406. $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
  20407. $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
  20408. $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
  20409. $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
  20410. return $cell_margin;
  20411. }
  20412. /**
  20413. * Get the border-spacing from CSS attribute.
  20414. * @param $cssbspace (string) border-spacing CSS properties
  20415. * @param $width (float) width of the containing element
  20416. * @return array of border spacings
  20417. * @public
  20418. * @since 5.9.010 (2010-10-27)
  20419. */
  20420. public function getCSSBorderMargin($cssbspace, $width=0) {
  20421. $space = preg_split('/[\s]+/', trim($cssbspace));
  20422. $border_spacing = array(); // value to be returned
  20423. switch (count($space)) {
  20424. case 2: {
  20425. $border_spacing['H'] = $space[0];
  20426. $border_spacing['V'] = $space[1];
  20427. break;
  20428. }
  20429. case 1: {
  20430. $border_spacing['H'] = $space[0];
  20431. $border_spacing['V'] = $space[0];
  20432. break;
  20433. }
  20434. default: {
  20435. return array('H' => 0, 'V' => 0);
  20436. }
  20437. }
  20438. if ($width == 0) {
  20439. $width = $this->w - $this->lMargin - $this->rMargin;
  20440. }
  20441. $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
  20442. $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
  20443. return $border_spacing;
  20444. }
  20445. /**
  20446. * Returns the letter-spacing value from CSS value
  20447. * @param $spacing (string) letter-spacing value
  20448. * @param $parent (float) font spacing (tracking) value of the parent element
  20449. * @return float quantity to increases or decreases the space between characters in a text.
  20450. * @protected
  20451. * @since 5.9.000 (2010-10-02)
  20452. */
  20453. protected function getCSSFontSpacing($spacing, $parent=0) {
  20454. $val = 0; // value to be returned
  20455. $spacing = trim($spacing);
  20456. switch ($spacing) {
  20457. case 'normal': {
  20458. $val = 0;
  20459. break;
  20460. }
  20461. case 'inherit': {
  20462. if ($parent == 'normal') {
  20463. $val = 0;
  20464. } else {
  20465. $val = $parent;
  20466. }
  20467. break;
  20468. }
  20469. default: {
  20470. $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
  20471. }
  20472. }
  20473. return $val;
  20474. }
  20475. /**
  20476. * Returns the percentage of font stretching from CSS value
  20477. * @param $stretch (string) stretch mode
  20478. * @param $parent (float) stretch value of the parent element
  20479. * @return float font stretching percentage
  20480. * @protected
  20481. * @since 5.9.000 (2010-10-02)
  20482. */
  20483. protected function getCSSFontStretching($stretch, $parent=100) {
  20484. $val = 100; // value to be returned
  20485. $stretch = trim($stretch);
  20486. switch ($stretch) {
  20487. case 'ultra-condensed': {
  20488. $val = 40;
  20489. break;
  20490. }
  20491. case 'extra-condensed': {
  20492. $val = 55;
  20493. break;
  20494. }
  20495. case 'condensed': {
  20496. $val = 70;
  20497. break;
  20498. }
  20499. case 'semi-condensed': {
  20500. $val = 85;
  20501. break;
  20502. }
  20503. case 'normal': {
  20504. $val = 100;
  20505. break;
  20506. }
  20507. case 'semi-expanded': {
  20508. $val = 115;
  20509. break;
  20510. }
  20511. case 'expanded': {
  20512. $val = 130;
  20513. break;
  20514. }
  20515. case 'extra-expanded': {
  20516. $val = 145;
  20517. break;
  20518. }
  20519. case 'ultra-expanded': {
  20520. $val = 160;
  20521. break;
  20522. }
  20523. case 'wider': {
  20524. $val = $parent + 10;
  20525. break;
  20526. }
  20527. case 'narrower': {
  20528. $val = $parent - 10;
  20529. break;
  20530. }
  20531. case 'inherit': {
  20532. if ($parent == 'normal') {
  20533. $val = 100;
  20534. } else {
  20535. $val = $parent;
  20536. }
  20537. break;
  20538. }
  20539. default: {
  20540. $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
  20541. }
  20542. }
  20543. return $val;
  20544. }
  20545. /**
  20546. * Returns the HTML DOM array.
  20547. * @param $html (string) html code
  20548. * @return array
  20549. * @protected
  20550. * @since 3.2.000 (2008-06-20)
  20551. */
  20552. protected function getHtmlDomArray($html) {
  20553. // array of CSS styles ( selector => properties).
  20554. $css = array();
  20555. // get CSS array defined at previous call
  20556. $matches = array();
  20557. if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
  20558. if (isset($matches[1][0])) {
  20559. $css = array_merge($css, unserialize($this->unhtmlentities($matches[1][0])));
  20560. }
  20561. $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
  20562. }
  20563. // extract external CSS files
  20564. $matches = array();
  20565. if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
  20566. foreach ($matches[1] as $key => $link) {
  20567. $type = array();
  20568. if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
  20569. $type = array();
  20570. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
  20571. // get 'all' and 'print' media, other media types are discarded
  20572. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  20573. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  20574. $type = array();
  20575. if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
  20576. // read CSS data file
  20577. $cssdata = file_get_contents(trim($type[1]));
  20578. $css = array_merge($css, $this->extractCSSproperties($cssdata));
  20579. }
  20580. }
  20581. }
  20582. }
  20583. }
  20584. // extract style tags
  20585. $matches = array();
  20586. if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
  20587. foreach ($matches[1] as $key => $media) {
  20588. $type = array();
  20589. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
  20590. // get 'all' and 'print' media, other media types are discarded
  20591. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  20592. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  20593. $cssdata = $matches[2][$key];
  20594. $css = array_merge($css, $this->extractCSSproperties($cssdata));
  20595. }
  20596. }
  20597. }
  20598. // create a special tag to contain the CSS array (used for table content)
  20599. $csstagarray = '<cssarray>'.htmlentities(serialize($css)).'</cssarray>';
  20600. // remove head and style blocks
  20601. $html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
  20602. $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
  20603. // define block tags
  20604. $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
  20605. // define self-closing tags
  20606. $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
  20607. // remove all unsupported tags (the line below lists all supported tags)
  20608. $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>');
  20609. //replace some blank characters
  20610. $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
  20611. $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);
  20612. $html = preg_replace('@(\r\n|\r)@', "\n", $html);
  20613. $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
  20614. $html = strtr($html, $repTable);
  20615. $offset = 0;
  20616. while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
  20617. $html_a = substr($html, 0, $offset);
  20618. $html_b = substr($html, $offset, ($pos - $offset + 6));
  20619. while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
  20620. // preserve newlines on <pre> tag
  20621. $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
  20622. }
  20623. while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
  20624. // preserve spaces on <pre> tag
  20625. $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
  20626. }
  20627. $html = $html_a.$html_b.substr($html, $pos + 6);
  20628. $offset = strlen($html_a.$html_b);
  20629. }
  20630. $offset = 0;
  20631. while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
  20632. $html_a = substr($html, 0, $offset);
  20633. $html_b = substr($html, $offset, ($pos - $offset + 11));
  20634. while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
  20635. // preserve newlines on <textarea> tag
  20636. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
  20637. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
  20638. }
  20639. $html = $html_a.$html_b.substr($html, $pos + 11);
  20640. $offset = strlen($html_a.$html_b);
  20641. }
  20642. $html = preg_replace('/([\s]*)<option/si', '<option', $html);
  20643. $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
  20644. $offset = 0;
  20645. while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
  20646. $html_a = substr($html, 0, $offset);
  20647. $html_b = substr($html, $offset, ($pos - $offset + 9));
  20648. while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
  20649. $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
  20650. $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
  20651. }
  20652. $html = $html_a.$html_b.substr($html, $pos + 9);
  20653. $offset = strlen($html_a.$html_b);
  20654. }
  20655. if (preg_match("'</select'si", $html)) {
  20656. $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
  20657. $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
  20658. }
  20659. $html = str_replace("\n", ' ', $html);
  20660. // restore textarea newlines
  20661. $html = str_replace('<TBR>', "\n", $html);
  20662. // remove extra spaces from code
  20663. $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
  20664. $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
  20665. $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
  20666. $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
  20667. $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);
  20668. $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
  20669. $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
  20670. $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
  20671. $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
  20672. $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
  20673. $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
  20674. $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
  20675. $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
  20676. $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
  20677. $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
  20678. $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
  20679. $html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
  20680. $html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
  20681. $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
  20682. // trim string
  20683. $html = $this->stringTrim($html);
  20684. // fix first image tag alignment
  20685. $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
  20686. // pattern for generic tag
  20687. $tagpattern = '/(<[^>]+>)/';
  20688. // explodes the string
  20689. $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  20690. // count elements
  20691. $maxel = count($a);
  20692. $elkey = 0;
  20693. $key = 0;
  20694. // create an array of elements
  20695. $dom = array();
  20696. $dom[$key] = array();
  20697. // set inheritable properties fot the first void element
  20698. // 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
  20699. $dom[$key]['tag'] = false;
  20700. $dom[$key]['block'] = false;
  20701. $dom[$key]['value'] = '';
  20702. $dom[$key]['parent'] = 0;
  20703. $dom[$key]['hide'] = false;
  20704. $dom[$key]['fontname'] = $this->FontFamily;
  20705. $dom[$key]['fontstyle'] = $this->FontStyle;
  20706. $dom[$key]['fontsize'] = $this->FontSizePt;
  20707. $dom[$key]['font-stretch'] = $this->font_stretching;
  20708. $dom[$key]['letter-spacing'] = $this->font_spacing;
  20709. $dom[$key]['stroke'] = $this->textstrokewidth;
  20710. $dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
  20711. $dom[$key]['clip'] = ($this->textrendermode > 3);
  20712. $dom[$key]['line-height'] = $this->cell_height_ratio;
  20713. $dom[$key]['bgcolor'] = false;
  20714. $dom[$key]['fgcolor'] = $this->fgcolor; // color
  20715. $dom[$key]['strokecolor'] = $this->strokecolor;
  20716. $dom[$key]['align'] = '';
  20717. $dom[$key]['listtype'] = '';
  20718. $dom[$key]['text-indent'] = 0;
  20719. $dom[$key]['border'] = array();
  20720. $dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
  20721. $thead = false; // true when we are inside the THEAD tag
  20722. ++$key;
  20723. $level = array();
  20724. array_push($level, 0); // root
  20725. while ($elkey < $maxel) {
  20726. $dom[$key] = array();
  20727. $element = $a[$elkey];
  20728. $dom[$key]['elkey'] = $elkey;
  20729. if (preg_match($tagpattern, $element)) {
  20730. // html tag
  20731. $element = substr($element, 1, -1);
  20732. // get tag name
  20733. preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
  20734. $tagname = strtolower($tag[1]);
  20735. // check if we are inside a table header
  20736. if ($tagname == 'thead') {
  20737. if ($element{0} == '/') {
  20738. $thead = false;
  20739. } else {
  20740. $thead = true;
  20741. }
  20742. ++$elkey;
  20743. continue;
  20744. }
  20745. $dom[$key]['tag'] = true;
  20746. $dom[$key]['value'] = $tagname;
  20747. if (in_array($dom[$key]['value'], $blocktags)) {
  20748. $dom[$key]['block'] = true;
  20749. } else {
  20750. $dom[$key]['block'] = false;
  20751. }
  20752. if ($element{0} == '/') {
  20753. // *** closing html tag
  20754. $dom[$key]['opening'] = false;
  20755. $dom[$key]['parent'] = end($level);
  20756. array_pop($level);
  20757. $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
  20758. $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
  20759. $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
  20760. $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
  20761. $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
  20762. $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
  20763. $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
  20764. $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
  20765. $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
  20766. $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
  20767. $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
  20768. $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
  20769. $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
  20770. $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
  20771. $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
  20772. if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
  20773. $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
  20774. }
  20775. // set the number of columns in table tag
  20776. if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
  20777. $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
  20778. }
  20779. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  20780. $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
  20781. for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
  20782. $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
  20783. }
  20784. $key = $i;
  20785. // mark nested tables
  20786. $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
  20787. // remove thead sections from nested tables
  20788. $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
  20789. $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
  20790. }
  20791. // store header rows on a new table
  20792. if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
  20793. if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
  20794. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
  20795. }
  20796. for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
  20797. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
  20798. }
  20799. if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
  20800. $dom[($dom[$key]['parent'])]['attribute'] = array();
  20801. }
  20802. // header elements must be always contained in a single page
  20803. $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
  20804. }
  20805. if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
  20806. // remove the nobr attributes from the table header
  20807. $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
  20808. $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
  20809. }
  20810. } else {
  20811. // *** opening or self-closing html tag
  20812. $dom[$key]['opening'] = true;
  20813. $dom[$key]['parent'] = end($level);
  20814. if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
  20815. // self-closing tag
  20816. $dom[$key]['self'] = true;
  20817. } else {
  20818. // opening tag
  20819. array_push($level, $key);
  20820. $dom[$key]['self'] = false;
  20821. }
  20822. // copy some values from parent
  20823. $parentkey = 0;
  20824. if ($key > 0) {
  20825. $parentkey = $dom[$key]['parent'];
  20826. $dom[$key]['hide'] = $dom[$parentkey]['hide'];
  20827. $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
  20828. $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
  20829. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
  20830. $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
  20831. $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
  20832. $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
  20833. $dom[$key]['fill'] = $dom[$parentkey]['fill'];
  20834. $dom[$key]['clip'] = $dom[$parentkey]['clip'];
  20835. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  20836. $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
  20837. $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
  20838. $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
  20839. $dom[$key]['align'] = $dom[$parentkey]['align'];
  20840. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  20841. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  20842. $dom[$key]['border'] = array();
  20843. $dom[$key]['dir'] = $dom[$parentkey]['dir'];
  20844. }
  20845. // get attributes
  20846. preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
  20847. $dom[$key]['attribute'] = array(); // reset attribute array
  20848. while (list($id, $name) = each($attr_array[1])) {
  20849. $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
  20850. }
  20851. if (!empty($css)) {
  20852. // merge CSS style to current style
  20853. list($dom[$key]['csssel'], $dom[$key]['cssdata']) = $this->getCSSdataArray($dom, $key, $css);
  20854. $dom[$key]['attribute']['style'] = $this->getTagStyleFromCSSarray($dom[$key]['cssdata']);
  20855. }
  20856. // split style attributes
  20857. if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
  20858. // get style attributes
  20859. preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  20860. $dom[$key]['style'] = array(); // reset style attribute array
  20861. while (list($id, $name) = each($style_array[1])) {
  20862. // in case of duplicate attribute the last replace the previous
  20863. $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
  20864. }
  20865. // --- get some style attributes ---
  20866. // text direction
  20867. if (isset($dom[$key]['style']['direction'])) {
  20868. $dom[$key]['dir'] = $dom[$key]['style']['direction'];
  20869. }
  20870. // display
  20871. if (isset($dom[$key]['style']['display'])) {
  20872. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
  20873. }
  20874. // font family
  20875. if (isset($dom[$key]['style']['font-family'])) {
  20876. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
  20877. }
  20878. // list-style-type
  20879. if (isset($dom[$key]['style']['list-style-type'])) {
  20880. $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
  20881. if ($dom[$key]['listtype'] == 'inherit') {
  20882. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  20883. }
  20884. }
  20885. // text-indent
  20886. if (isset($dom[$key]['style']['text-indent'])) {
  20887. $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
  20888. if ($dom[$key]['text-indent'] == 'inherit') {
  20889. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  20890. }
  20891. }
  20892. // font size
  20893. if (isset($dom[$key]['style']['font-size'])) {
  20894. $fsize = trim($dom[$key]['style']['font-size']);
  20895. switch ($fsize) {
  20896. // absolute-size
  20897. case 'xx-small': {
  20898. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
  20899. break;
  20900. }
  20901. case 'x-small': {
  20902. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
  20903. break;
  20904. }
  20905. case 'small': {
  20906. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
  20907. break;
  20908. }
  20909. case 'medium': {
  20910. $dom[$key]['fontsize'] = $dom[0]['fontsize'];
  20911. break;
  20912. }
  20913. case 'large': {
  20914. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
  20915. break;
  20916. }
  20917. case 'x-large': {
  20918. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
  20919. break;
  20920. }
  20921. case 'xx-large': {
  20922. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
  20923. break;
  20924. }
  20925. // relative-size
  20926. case 'smaller': {
  20927. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
  20928. break;
  20929. }
  20930. case 'larger': {
  20931. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
  20932. break;
  20933. }
  20934. default: {
  20935. $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
  20936. }
  20937. }
  20938. }
  20939. // font-stretch
  20940. if (isset($dom[$key]['style']['font-stretch'])) {
  20941. $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
  20942. }
  20943. // letter-spacing
  20944. if (isset($dom[$key]['style']['letter-spacing'])) {
  20945. $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
  20946. }
  20947. // line-height
  20948. if (isset($dom[$key]['style']['line-height'])) {
  20949. $lineheight = trim($dom[$key]['style']['line-height']);
  20950. switch ($lineheight) {
  20951. // A normal line height. This is default
  20952. case 'normal': {
  20953. $dom[$key]['line-height'] = $dom[0]['line-height'];
  20954. break;
  20955. }
  20956. default: {
  20957. if (is_numeric($lineheight)) {
  20958. $lineheight = $lineheight * 100;
  20959. }
  20960. $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
  20961. }
  20962. }
  20963. }
  20964. // font style
  20965. if (isset($dom[$key]['style']['font-weight'])) {
  20966. if (strtolower($dom[$key]['style']['font-weight']{0}) == 'n') {
  20967. if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
  20968. $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
  20969. }
  20970. } elseif (strtolower($dom[$key]['style']['font-weight']{0}) == 'b') {
  20971. $dom[$key]['fontstyle'] .= 'B';
  20972. }
  20973. }
  20974. if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
  20975. $dom[$key]['fontstyle'] .= 'I';
  20976. }
  20977. // font color
  20978. if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
  20979. $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
  20980. } elseif ($dom[$key]['value'] == 'a') {
  20981. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  20982. }
  20983. // background color
  20984. if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
  20985. $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
  20986. }
  20987. // text-decoration
  20988. if (isset($dom[$key]['style']['text-decoration'])) {
  20989. $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
  20990. foreach ($decors as $dec) {
  20991. $dec = trim($dec);
  20992. if (!$this->empty_string($dec)) {
  20993. if ($dec{0} == 'u') {
  20994. // underline
  20995. $dom[$key]['fontstyle'] .= 'U';
  20996. } elseif ($dec{0} == 'l') {
  20997. // line-trough
  20998. $dom[$key]['fontstyle'] .= 'D';
  20999. } elseif ($dec{0} == 'o') {
  21000. // overline
  21001. $dom[$key]['fontstyle'] .= 'O';
  21002. }
  21003. }
  21004. }
  21005. } elseif ($dom[$key]['value'] == 'a') {
  21006. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  21007. }
  21008. // check for width attribute
  21009. if (isset($dom[$key]['style']['width'])) {
  21010. $dom[$key]['width'] = $dom[$key]['style']['width'];
  21011. }
  21012. // check for height attribute
  21013. if (isset($dom[$key]['style']['height'])) {
  21014. $dom[$key]['height'] = $dom[$key]['style']['height'];
  21015. }
  21016. // check for text alignment
  21017. if (isset($dom[$key]['style']['text-align'])) {
  21018. $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
  21019. }
  21020. // check for CSS border properties
  21021. if (isset($dom[$key]['style']['border'])) {
  21022. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
  21023. if (!empty($borderstyle)) {
  21024. $dom[$key]['border']['LTRB'] = $borderstyle;
  21025. }
  21026. }
  21027. if (isset($dom[$key]['style']['border-color'])) {
  21028. $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
  21029. if (isset($brd_colors[3])) {
  21030. $dom[$key]['border']['L']['color'] = $this->convertHTMLColorToDec($brd_colors[3]);
  21031. }
  21032. if (isset($brd_colors[1])) {
  21033. $dom[$key]['border']['R']['color'] = $this->convertHTMLColorToDec($brd_colors[1]);
  21034. }
  21035. if (isset($brd_colors[0])) {
  21036. $dom[$key]['border']['T']['color'] = $this->convertHTMLColorToDec($brd_colors[0]);
  21037. }
  21038. if (isset($brd_colors[2])) {
  21039. $dom[$key]['border']['B']['color'] = $this->convertHTMLColorToDec($brd_colors[2]);
  21040. }
  21041. }
  21042. if (isset($dom[$key]['style']['border-width'])) {
  21043. $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
  21044. if (isset($brd_widths[3])) {
  21045. $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
  21046. }
  21047. if (isset($brd_widths[1])) {
  21048. $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
  21049. }
  21050. if (isset($brd_widths[0])) {
  21051. $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
  21052. }
  21053. if (isset($brd_widths[2])) {
  21054. $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
  21055. }
  21056. }
  21057. if (isset($dom[$key]['style']['border-style'])) {
  21058. $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
  21059. if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
  21060. $dom[$key]['border']['L']['cap'] = 'square';
  21061. $dom[$key]['border']['L']['join'] = 'miter';
  21062. $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
  21063. if ($dom[$key]['border']['L']['dash'] < 0) {
  21064. $dom[$key]['border']['L'] = array();
  21065. }
  21066. }
  21067. if (isset($brd_styles[1])) {
  21068. $dom[$key]['border']['R']['cap'] = 'square';
  21069. $dom[$key]['border']['R']['join'] = 'miter';
  21070. $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
  21071. if ($dom[$key]['border']['R']['dash'] < 0) {
  21072. $dom[$key]['border']['R'] = array();
  21073. }
  21074. }
  21075. if (isset($brd_styles[0])) {
  21076. $dom[$key]['border']['T']['cap'] = 'square';
  21077. $dom[$key]['border']['T']['join'] = 'miter';
  21078. $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
  21079. if ($dom[$key]['border']['T']['dash'] < 0) {
  21080. $dom[$key]['border']['T'] = array();
  21081. }
  21082. }
  21083. if (isset($brd_styles[2])) {
  21084. $dom[$key]['border']['B']['cap'] = 'square';
  21085. $dom[$key]['border']['B']['join'] = 'miter';
  21086. $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
  21087. if ($dom[$key]['border']['B']['dash'] < 0) {
  21088. $dom[$key]['border']['B'] = array();
  21089. }
  21090. }
  21091. }
  21092. $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
  21093. foreach ($cellside as $bsk => $bsv) {
  21094. if (isset($dom[$key]['style']['border-'.$bsv])) {
  21095. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
  21096. if (!empty($borderstyle)) {
  21097. $dom[$key]['border'][$bsk] = $borderstyle;
  21098. }
  21099. }
  21100. if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
  21101. $dom[$key]['border'][$bsk]['color'] = $this->convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color']);
  21102. }
  21103. if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
  21104. $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
  21105. }
  21106. if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
  21107. $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
  21108. if ($dom[$key]['border'][$bsk]['dash'] < 0) {
  21109. $dom[$key]['border'][$bsk] = array();
  21110. }
  21111. }
  21112. }
  21113. // check for CSS padding properties
  21114. if (isset($dom[$key]['style']['padding'])) {
  21115. $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
  21116. } else {
  21117. $dom[$key]['padding'] = $this->cell_padding;
  21118. }
  21119. foreach ($cellside as $psk => $psv) {
  21120. if (isset($dom[$key]['style']['padding-'.$psv])) {
  21121. $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
  21122. }
  21123. }
  21124. // check for CSS margin properties
  21125. if (isset($dom[$key]['style']['margin'])) {
  21126. $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
  21127. } else {
  21128. $dom[$key]['margin'] = $this->cell_margin;
  21129. }
  21130. foreach ($cellside as $psk => $psv) {
  21131. if (isset($dom[$key]['style']['margin-'.$psv])) {
  21132. $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
  21133. }
  21134. }
  21135. // check for CSS border-spacing properties
  21136. if (isset($dom[$key]['style']['border-spacing'])) {
  21137. $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
  21138. }
  21139. // page-break-inside
  21140. if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
  21141. $dom[$key]['attribute']['nobr'] = 'true';
  21142. }
  21143. // page-break-before
  21144. if (isset($dom[$key]['style']['page-break-before'])) {
  21145. if ($dom[$key]['style']['page-break-before'] == 'always') {
  21146. $dom[$key]['attribute']['pagebreak'] = 'true';
  21147. } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
  21148. $dom[$key]['attribute']['pagebreak'] = 'left';
  21149. } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
  21150. $dom[$key]['attribute']['pagebreak'] = 'right';
  21151. }
  21152. }
  21153. // page-break-after
  21154. if (isset($dom[$key]['style']['page-break-after'])) {
  21155. if ($dom[$key]['style']['page-break-after'] == 'always') {
  21156. $dom[$key]['attribute']['pagebreakafter'] = 'true';
  21157. } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
  21158. $dom[$key]['attribute']['pagebreakafter'] = 'left';
  21159. } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
  21160. $dom[$key]['attribute']['pagebreakafter'] = 'right';
  21161. }
  21162. }
  21163. }
  21164. if (isset($dom[$key]['attribute']['display'])) {
  21165. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
  21166. }
  21167. if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
  21168. $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
  21169. if (!empty($borderstyle)) {
  21170. $dom[$key]['border']['LTRB'] = $borderstyle;
  21171. }
  21172. }
  21173. // check for font tag
  21174. if ($dom[$key]['value'] == 'font') {
  21175. // font family
  21176. if (isset($dom[$key]['attribute']['face'])) {
  21177. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
  21178. }
  21179. // font size
  21180. if (isset($dom[$key]['attribute']['size'])) {
  21181. if ($key > 0) {
  21182. if ($dom[$key]['attribute']['size']{0} == '+') {
  21183. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
  21184. } elseif ($dom[$key]['attribute']['size']{0} == '-') {
  21185. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
  21186. } else {
  21187. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  21188. }
  21189. } else {
  21190. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  21191. }
  21192. }
  21193. }
  21194. // force natural alignment for lists
  21195. if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
  21196. AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
  21197. if ($this->rtl) {
  21198. $dom[$key]['align'] = 'R';
  21199. } else {
  21200. $dom[$key]['align'] = 'L';
  21201. }
  21202. }
  21203. if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
  21204. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  21205. $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
  21206. }
  21207. }
  21208. if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
  21209. $dom[$key]['fontstyle'] .= 'B';
  21210. }
  21211. if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
  21212. $dom[$key]['fontstyle'] .= 'I';
  21213. }
  21214. if ($dom[$key]['value'] == 'u') {
  21215. $dom[$key]['fontstyle'] .= 'U';
  21216. }
  21217. if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
  21218. $dom[$key]['fontstyle'] .= 'D';
  21219. }
  21220. if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
  21221. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  21222. }
  21223. if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
  21224. $dom[$key]['fontname'] = $this->default_monospaced_font;
  21225. }
  21226. if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
  21227. // headings h1, h2, h3, h4, h5, h6
  21228. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  21229. $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
  21230. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
  21231. }
  21232. if (!isset($dom[$key]['style']['font-weight'])) {
  21233. $dom[$key]['fontstyle'] .= 'B';
  21234. }
  21235. }
  21236. if (($dom[$key]['value'] == 'table')) {
  21237. $dom[$key]['rows'] = 0; // number of rows
  21238. $dom[$key]['trids'] = array(); // IDs of TR elements
  21239. $dom[$key]['thead'] = ''; // table header rows
  21240. }
  21241. if (($dom[$key]['value'] == 'tr')) {
  21242. $dom[$key]['cols'] = 0;
  21243. if ($thead) {
  21244. $dom[$key]['thead'] = true;
  21245. // rows on thead block are printed as a separate table
  21246. } else {
  21247. $dom[$key]['thead'] = false;
  21248. // store the number of rows on table element
  21249. ++$dom[($dom[$key]['parent'])]['rows'];
  21250. // store the TR elements IDs on table element
  21251. array_push($dom[($dom[$key]['parent'])]['trids'], $key);
  21252. }
  21253. }
  21254. if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
  21255. if (isset($dom[$key]['attribute']['colspan'])) {
  21256. $colspan = intval($dom[$key]['attribute']['colspan']);
  21257. } else {
  21258. $colspan = 1;
  21259. }
  21260. $dom[$key]['attribute']['colspan'] = $colspan;
  21261. $dom[($dom[$key]['parent'])]['cols'] += $colspan;
  21262. }
  21263. // text direction
  21264. if (isset($dom[$key]['attribute']['dir'])) {
  21265. $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
  21266. }
  21267. // set foreground color attribute
  21268. if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
  21269. $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
  21270. } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
  21271. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  21272. }
  21273. // set background color attribute
  21274. if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
  21275. $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
  21276. }
  21277. // set stroke color attribute
  21278. if (isset($dom[$key]['attribute']['strokecolor']) AND (!$this->empty_string($dom[$key]['attribute']['strokecolor']))) {
  21279. $dom[$key]['strokecolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['strokecolor']);
  21280. }
  21281. // check for width attribute
  21282. if (isset($dom[$key]['attribute']['width'])) {
  21283. $dom[$key]['width'] = $dom[$key]['attribute']['width'];
  21284. }
  21285. // check for height attribute
  21286. if (isset($dom[$key]['attribute']['height'])) {
  21287. $dom[$key]['height'] = $dom[$key]['attribute']['height'];
  21288. }
  21289. // check for text alignment
  21290. if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
  21291. $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
  21292. }
  21293. // check for text rendering mode (the following attributes do not exist in HTML)
  21294. if (isset($dom[$key]['attribute']['stroke'])) {
  21295. // font stroke width
  21296. $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
  21297. }
  21298. if (isset($dom[$key]['attribute']['fill'])) {
  21299. // font fill
  21300. if ($dom[$key]['attribute']['fill'] == 'true') {
  21301. $dom[$key]['fill'] = true;
  21302. } else {
  21303. $dom[$key]['fill'] = false;
  21304. }
  21305. }
  21306. if (isset($dom[$key]['attribute']['clip'])) {
  21307. // clipping mode
  21308. if ($dom[$key]['attribute']['clip'] == 'true') {
  21309. $dom[$key]['clip'] = true;
  21310. } else {
  21311. $dom[$key]['clip'] = false;
  21312. }
  21313. }
  21314. } // end opening tag
  21315. } else {
  21316. // text
  21317. $dom[$key]['tag'] = false;
  21318. $dom[$key]['block'] = false;
  21319. //$element = str_replace('&nbsp;', $this->unichr(160), $element);
  21320. $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
  21321. $dom[$key]['parent'] = end($level);
  21322. $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
  21323. }
  21324. ++$elkey;
  21325. ++$key;
  21326. }
  21327. return $dom;
  21328. }
  21329. /**
  21330. * Returns the string used to find spaces
  21331. * @return string
  21332. * @protected
  21333. * @author Nicola Asuni
  21334. * @since 4.8.024 (2010-01-15)
  21335. */
  21336. protected function getSpaceString() {
  21337. $spacestr = chr(32);
  21338. if ($this->isUnicodeFont()) {
  21339. $spacestr = chr(0).chr(32);
  21340. }
  21341. return $spacestr;
  21342. }
  21343. /**
  21344. * Prints a cell (rectangular area) with optional borders, background color and html text string.
  21345. * 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 />
  21346. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  21347. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  21348. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  21349. * @param $x (float) upper-left corner X coordinate
  21350. * @param $y (float) upper-left corner Y coordinate
  21351. * @param $html (string) html text to print. Default value: empty string.
  21352. * @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)))
  21353. * @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>
  21354. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  21355. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  21356. * @param $reseth (boolean) if true reset the last cell height (default true).
  21357. * @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>
  21358. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  21359. * @see Multicell(), writeHTML()
  21360. * @public
  21361. */
  21362. public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
  21363. return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
  21364. }
  21365. /**
  21366. * Allows to preserve some HTML formatting (limited support).<br />
  21367. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  21368. * 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
  21369. * @param $html (string) text to display
  21370. * @param $ln (boolean) if true add a new line after text (default = true)
  21371. * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
  21372. * @param $reseth (boolean) if true reset the last cell height (default false).
  21373. * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
  21374. * @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>
  21375. * @public
  21376. */
  21377. public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
  21378. $gvars = $this->getGraphicVars();
  21379. // store current values
  21380. $prev_cell_margin = $this->cell_margin;
  21381. $prev_cell_padding = $this->cell_padding;
  21382. $prevPage = $this->page;
  21383. $prevlMargin = $this->lMargin;
  21384. $prevrMargin = $this->rMargin;
  21385. $curfontname = $this->FontFamily;
  21386. $curfontstyle = $this->FontStyle;
  21387. $curfontsize = $this->FontSizePt;
  21388. $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
  21389. $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
  21390. $curfontstretcing = $this->font_stretching;
  21391. $curfonttracking = $this->font_spacing;
  21392. $this->newline = true;
  21393. $newline = true;
  21394. $startlinepage = $this->page;
  21395. $minstartliney = $this->y;
  21396. $maxbottomliney = 0;
  21397. $startlinex = $this->x;
  21398. $startliney = $this->y;
  21399. $yshift = 0;
  21400. $loop = 0;
  21401. $curpos = 0;
  21402. $this_method_vars = array();
  21403. $undo = false;
  21404. $fontaligned = false;
  21405. $reverse_dir = false; // true when the text direction is reversed
  21406. $this->premode = false;
  21407. if ($this->inxobj) {
  21408. // we are inside an XObject template
  21409. $pask = count($this->xobjects[$this->xobjid]['annotations']);
  21410. } elseif (isset($this->PageAnnots[$this->page])) {
  21411. $pask = count($this->PageAnnots[$this->page]);
  21412. } else {
  21413. $pask = 0;
  21414. }
  21415. if ($this->inxobj) {
  21416. // we are inside an XObject template
  21417. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  21418. } elseif (!$this->InFooter) {
  21419. if (isset($this->footerlen[$this->page])) {
  21420. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  21421. } else {
  21422. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  21423. }
  21424. $startlinepos = $this->footerpos[$this->page];
  21425. } else {
  21426. // we are inside the footer
  21427. $startlinepos = $this->pagelen[$this->page];
  21428. }
  21429. $lalign = $align;
  21430. $plalign = $align;
  21431. if ($this->rtl) {
  21432. $w = $this->x - $this->lMargin;
  21433. } else {
  21434. $w = $this->w - $this->rMargin - $this->x;
  21435. }
  21436. $w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  21437. if ($cell) {
  21438. if ($this->rtl) {
  21439. $this->x -= $this->cell_padding['R'];
  21440. $this->lMargin += $this->cell_padding['R'];
  21441. } else {
  21442. $this->x += $this->cell_padding['L'];
  21443. $this->rMargin += $this->cell_padding['L'];
  21444. }
  21445. }
  21446. if ($this->customlistindent >= 0) {
  21447. $this->listindent = $this->customlistindent;
  21448. } else {
  21449. $this->listindent = $this->GetStringWidth('000000');
  21450. }
  21451. $this->listindentlevel = 0;
  21452. // save previous states
  21453. $prev_cell_height_ratio = $this->cell_height_ratio;
  21454. $prev_listnum = $this->listnum;
  21455. $prev_listordered = $this->listordered;
  21456. $prev_listcount = $this->listcount;
  21457. $prev_lispacer = $this->lispacer;
  21458. $this->listnum = 0;
  21459. $this->listordered = array();
  21460. $this->listcount = array();
  21461. $this->lispacer = '';
  21462. if (($this->empty_string($this->lasth)) OR ($reseth)) {
  21463. // reset row height
  21464. $this->resetLastH();
  21465. }
  21466. $dom = $this->getHtmlDomArray($html);
  21467. $maxel = count($dom);
  21468. $key = 0;
  21469. $hidden_node_key = -1;
  21470. while ($key < $maxel) {
  21471. if ($dom[$key]['tag']) {
  21472. if ($dom[$key]['opening']) {
  21473. if (($hidden_node_key <= 0) AND $dom[$key]['hide']) {
  21474. // store the node key
  21475. $hidden_node_key = $key;
  21476. }
  21477. } elseif (($hidden_node_key > 0) AND ($dom[$key]['parent'] == $hidden_node_key)) {
  21478. // we have reached the closing tag of the hidden node
  21479. $hidden_node_key = 0;
  21480. }
  21481. }
  21482. if ($hidden_node_key >= 0) {
  21483. // skip this node
  21484. ++$key;
  21485. if ($hidden_node_key == 0) {
  21486. // reset hidden mode
  21487. $hidden_node_key = -1;
  21488. }
  21489. continue;
  21490. }
  21491. if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
  21492. // check for pagebreak
  21493. if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
  21494. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  21495. $this->checkPageBreak($this->PageBreakTrigger + 1);
  21496. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  21497. }
  21498. if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  21499. OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  21500. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  21501. $this->checkPageBreak($this->PageBreakTrigger + 1);
  21502. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  21503. }
  21504. }
  21505. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
  21506. if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
  21507. $dom[$key]['attribute']['nobr'] = false;
  21508. } else {
  21509. // store current object
  21510. $this->startTransaction();
  21511. // save this method vars
  21512. $this_method_vars['html'] = $html;
  21513. $this_method_vars['ln'] = $ln;
  21514. $this_method_vars['fill'] = $fill;
  21515. $this_method_vars['reseth'] = $reseth;
  21516. $this_method_vars['cell'] = $cell;
  21517. $this_method_vars['align'] = $align;
  21518. $this_method_vars['gvars'] = $gvars;
  21519. $this_method_vars['prevPage'] = $prevPage;
  21520. $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
  21521. $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
  21522. $this_method_vars['prevlMargin'] = $prevlMargin;
  21523. $this_method_vars['prevrMargin'] = $prevrMargin;
  21524. $this_method_vars['curfontname'] = $curfontname;
  21525. $this_method_vars['curfontstyle'] = $curfontstyle;
  21526. $this_method_vars['curfontsize'] = $curfontsize;
  21527. $this_method_vars['curfontascent'] = $curfontascent;
  21528. $this_method_vars['curfontdescent'] = $curfontdescent;
  21529. $this_method_vars['curfontstretcing'] = $curfontstretcing;
  21530. $this_method_vars['curfonttracking'] = $curfonttracking;
  21531. $this_method_vars['minstartliney'] = $minstartliney;
  21532. $this_method_vars['maxbottomliney'] = $maxbottomliney;
  21533. $this_method_vars['yshift'] = $yshift;
  21534. $this_method_vars['startlinepage'] = $startlinepage;
  21535. $this_method_vars['startlinepos'] = $startlinepos;
  21536. $this_method_vars['startlinex'] = $startlinex;
  21537. $this_method_vars['startliney'] = $startliney;
  21538. $this_method_vars['newline'] = $newline;
  21539. $this_method_vars['loop'] = $loop;
  21540. $this_method_vars['curpos'] = $curpos;
  21541. $this_method_vars['pask'] = $pask;
  21542. $this_method_vars['lalign'] = $lalign;
  21543. $this_method_vars['plalign'] = $plalign;
  21544. $this_method_vars['w'] = $w;
  21545. $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
  21546. $this_method_vars['prev_listnum'] = $prev_listnum;
  21547. $this_method_vars['prev_listordered'] = $prev_listordered;
  21548. $this_method_vars['prev_listcount'] = $prev_listcount;
  21549. $this_method_vars['prev_lispacer'] = $prev_lispacer;
  21550. $this_method_vars['fontaligned'] = $fontaligned;
  21551. $this_method_vars['key'] = $key;
  21552. $this_method_vars['dom'] = $dom;
  21553. }
  21554. }
  21555. // print THEAD block
  21556. if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
  21557. if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !$this->empty_string($dom[$dom[$key]['parent']]['thead'])) {
  21558. $this->inthead = true;
  21559. // print table header (thead)
  21560. $this->writeHTML($this->thead, false, false, false, false, '');
  21561. // check if we are on a new page or on a new column
  21562. if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
  21563. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  21564. // restore previous object
  21565. $this->rollbackTransaction(true);
  21566. // restore previous values
  21567. foreach ($this_method_vars as $vkey => $vval) {
  21568. $$vkey = $vval;
  21569. }
  21570. // disable table header
  21571. $tmp_thead = $this->thead;
  21572. $this->thead = '';
  21573. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  21574. $pre_y = $this->y;
  21575. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  21576. // fix for multicolumn mode
  21577. $startliney = $this->y;
  21578. }
  21579. $this->start_transaction_page = $this->page;
  21580. $this->start_transaction_y = $this->y;
  21581. // restore table header
  21582. $this->thead = $tmp_thead;
  21583. // fix table border properties
  21584. if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
  21585. $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
  21586. } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
  21587. $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
  21588. } else {
  21589. $tmp_cellspacing = 0;
  21590. }
  21591. $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
  21592. $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
  21593. $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
  21594. $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
  21595. $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
  21596. $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
  21597. // print table header (thead)
  21598. $this->writeHTML($this->thead, false, false, false, false, '');
  21599. }
  21600. }
  21601. // move $key index forward to skip THEAD block
  21602. while ( ($key < $maxel) AND (!(
  21603. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
  21604. OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
  21605. ++$key;
  21606. }
  21607. }
  21608. if ($dom[$key]['tag'] OR ($key == 0)) {
  21609. if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
  21610. $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
  21611. }
  21612. // vertically align image in line
  21613. if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
  21614. // get image height
  21615. $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], $this->lasth, 'px');
  21616. $autolinebreak = false;
  21617. if (isset($dom[$key]['width']) AND ($dom[$key]['width'] > 0)) {
  21618. $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], 1, 'px', false);
  21619. if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
  21620. AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
  21621. OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
  21622. // add automatic line break
  21623. $autolinebreak = true;
  21624. $this->Ln('', $cell);
  21625. if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
  21626. // go back to evaluate this line break
  21627. --$key;
  21628. }
  21629. }
  21630. }
  21631. if (!$autolinebreak) {
  21632. if ($this->inPageBody()) {
  21633. $pre_y = $this->y;
  21634. // check for page break
  21635. if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
  21636. // fix for multicolumn mode
  21637. $startliney = $this->y;
  21638. }
  21639. }
  21640. if ($this->page > $startlinepage) {
  21641. // fix line splitted over two pages
  21642. if (isset($this->footerlen[$startlinepage])) {
  21643. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21644. }
  21645. // line to be moved one page forward
  21646. $pagebuff = $this->getPageBuffer($startlinepage);
  21647. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  21648. $tstart = substr($pagebuff, 0, $startlinepos);
  21649. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  21650. // remove line from previous page
  21651. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  21652. $pagebuff = $this->getPageBuffer($this->page);
  21653. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  21654. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  21655. // add line start to current page
  21656. $yshift = ($minstartliney - $this->y);
  21657. if ($fontaligned) {
  21658. $yshift += ($curfontsize / $this->k);
  21659. }
  21660. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  21661. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  21662. // shift the annotations and links
  21663. if (isset($this->PageAnnots[$this->page])) {
  21664. $next_pask = count($this->PageAnnots[$this->page]);
  21665. } else {
  21666. $next_pask = 0;
  21667. }
  21668. if (isset($this->PageAnnots[$startlinepage])) {
  21669. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  21670. if ($pak >= $pask) {
  21671. $this->PageAnnots[$this->page][] = $pac;
  21672. unset($this->PageAnnots[$startlinepage][$pak]);
  21673. $npak = count($this->PageAnnots[$this->page]) - 1;
  21674. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  21675. }
  21676. }
  21677. }
  21678. $pask = $next_pask;
  21679. $startlinepos = $this->cntmrk[$this->page];
  21680. $startlinepage = $this->page;
  21681. $startliney = $this->y;
  21682. $this->newline = false;
  21683. }
  21684. $this->y += ((($curfontsize * $this->cell_height_ratio / $this->k) + $curfontascent - $curfontdescent) / 2) - $imgh;
  21685. $minstartliney = min($this->y, $minstartliney);
  21686. $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio));
  21687. }
  21688. } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
  21689. // account for different font size
  21690. $pfontname = $curfontname;
  21691. $pfontstyle = $curfontstyle;
  21692. $pfontsize = $curfontsize;
  21693. $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
  21694. $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
  21695. $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
  21696. $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
  21697. $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
  21698. if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
  21699. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  21700. OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
  21701. if (($key < ($maxel - 1)) AND (
  21702. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
  21703. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  21704. OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize) AND ($fontsize >= 0) AND ($curfontsize >= 0) AND ($fontsize != $curfontsize))
  21705. )) {
  21706. if ($this->page > $startlinepage) {
  21707. // fix lines splitted over two pages
  21708. if (isset($this->footerlen[$startlinepage])) {
  21709. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21710. }
  21711. // line to be moved one page forward
  21712. $pagebuff = $this->getPageBuffer($startlinepage);
  21713. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  21714. $tstart = substr($pagebuff, 0, $startlinepos);
  21715. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  21716. // remove line start from previous page
  21717. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  21718. $pagebuff = $this->getPageBuffer($this->page);
  21719. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  21720. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  21721. // add line start to current page
  21722. $yshift = ($minstartliney - $this->y);
  21723. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  21724. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  21725. // shift the annotations and links
  21726. if (isset($this->PageAnnots[$this->page])) {
  21727. $next_pask = count($this->PageAnnots[$this->page]);
  21728. } else {
  21729. $next_pask = 0;
  21730. }
  21731. if (isset($this->PageAnnots[$startlinepage])) {
  21732. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  21733. if ($pak >= $pask) {
  21734. $this->PageAnnots[$this->page][] = $pac;
  21735. unset($this->PageAnnots[$startlinepage][$pak]);
  21736. $npak = count($this->PageAnnots[$this->page]) - 1;
  21737. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  21738. }
  21739. }
  21740. }
  21741. $pask = $next_pask;
  21742. $startlinepos = $this->cntmrk[$this->page];
  21743. $startlinepage = $this->page;
  21744. $startliney = $this->y;
  21745. }
  21746. if (!isset($dom[$key]['line-height'])) {
  21747. $dom[$key]['line-height'] = $this->cell_height_ratio;
  21748. }
  21749. if (!$dom[$key]['block']) {
  21750. 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']))) {
  21751. $this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
  21752. }
  21753. if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
  21754. $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
  21755. 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)))) {
  21756. $minstartliney = min($this->y, $line_align_data[1]);
  21757. $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $line_align_data[2]);
  21758. } else {
  21759. $minstartliney = min($this->y, $minstartliney);
  21760. $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney);
  21761. }
  21762. $line_align_data = $current_line_align_data;
  21763. }
  21764. }
  21765. $this->cell_height_ratio = $dom[$key]['line-height'];
  21766. $fontaligned = true;
  21767. }
  21768. $this->SetFont($fontname, $fontstyle, $fontsize);
  21769. // reset row height
  21770. $this->resetLastH();
  21771. $curfontname = $fontname;
  21772. $curfontstyle = $fontstyle;
  21773. $curfontsize = $fontsize;
  21774. $curfontascent = $fontascent;
  21775. $curfontdescent = $fontdescent;
  21776. }
  21777. }
  21778. // set text rendering mode
  21779. $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
  21780. $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
  21781. $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
  21782. $this->setTextRenderingMode($textstroke, $textfill, $textclip);
  21783. if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
  21784. $this->setFontStretching($dom[$key]['font-stretch']);
  21785. }
  21786. if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
  21787. $this->setFontSpacing($dom[$key]['letter-spacing']);
  21788. }
  21789. if (($plalign == 'J') AND $dom[$key]['block']) {
  21790. $plalign = '';
  21791. }
  21792. // get current position on page buffer
  21793. $curpos = $this->pagelen[$startlinepage];
  21794. if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
  21795. $this->SetFillColorArray($dom[$key]['bgcolor']);
  21796. $wfill = true;
  21797. } else {
  21798. $wfill = $fill | false;
  21799. }
  21800. if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
  21801. $this->SetTextColorArray($dom[$key]['fgcolor']);
  21802. }
  21803. if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
  21804. $this->SetDrawColorArray($dom[$key]['strokecolor']);
  21805. }
  21806. if (isset($dom[$key]['align'])) {
  21807. $lalign = $dom[$key]['align'];
  21808. }
  21809. if ($this->empty_string($lalign)) {
  21810. $lalign = $align;
  21811. }
  21812. }
  21813. // align lines
  21814. if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
  21815. $newline = true;
  21816. $fontaligned = false;
  21817. // we are at the beginning of a new line
  21818. if (isset($startlinex)) {
  21819. $yshift = ($minstartliney - $startliney);
  21820. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  21821. $yshift = 0;
  21822. }
  21823. $t_x = 0;
  21824. // the last line must be shifted to be aligned as requested
  21825. $linew = abs($this->endlinex - $startlinex);
  21826. if ($this->inxobj) {
  21827. // we are inside an XObject template
  21828. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  21829. if (isset($opentagpos)) {
  21830. $midpos = $opentagpos;
  21831. } else {
  21832. $midpos = 0;
  21833. }
  21834. if ($midpos > 0) {
  21835. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  21836. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  21837. } else {
  21838. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  21839. $pend = '';
  21840. }
  21841. } else {
  21842. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  21843. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  21844. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21845. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  21846. } elseif (isset($opentagpos)) {
  21847. $midpos = $opentagpos;
  21848. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  21849. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  21850. $midpos = $this->footerpos[$startlinepage];
  21851. } else {
  21852. $midpos = 0;
  21853. }
  21854. if ($midpos > 0) {
  21855. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  21856. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  21857. } else {
  21858. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  21859. $pend = '';
  21860. }
  21861. }
  21862. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  21863. // calculate shifting amount
  21864. $tw = $w;
  21865. if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
  21866. $tw += $this->cell_padding['R'];
  21867. }
  21868. if ($this->lMargin != $prevlMargin) {
  21869. $tw += ($prevlMargin - $this->lMargin);
  21870. }
  21871. if ($this->rMargin != $prevrMargin) {
  21872. $tw += ($prevrMargin - $this->rMargin);
  21873. }
  21874. $one_space_width = $this->GetStringWidth(chr(32));
  21875. $no = 0; // number of spaces on a line contained on a single block
  21876. if ($this->isRTLTextDir()) { // RTL
  21877. // remove left space if exist
  21878. $pos1 = $this->revstrpos($pmid, '[(');
  21879. if ($pos1 > 0) {
  21880. $pos1 = intval($pos1);
  21881. if ($this->isUnicodeFont()) {
  21882. $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32)));
  21883. $spacelen = 2;
  21884. } else {
  21885. $pos2 = intval($this->revstrpos($pmid, '[('.chr(32)));
  21886. $spacelen = 1;
  21887. }
  21888. if ($pos1 == $pos2) {
  21889. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  21890. if (substr($pmid, $pos1, 4) == '[()]') {
  21891. $linew -= $one_space_width;
  21892. } elseif ($pos1 == strpos($pmid, '[(')) {
  21893. $no = 1;
  21894. }
  21895. }
  21896. }
  21897. } else { // LTR
  21898. // remove right space if exist
  21899. $pos1 = $this->revstrpos($pmid, ')]');
  21900. if ($pos1 > 0) {
  21901. $pos1 = intval($pos1);
  21902. if ($this->isUnicodeFont()) {
  21903. $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  21904. $spacelen = 2;
  21905. } else {
  21906. $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1;
  21907. $spacelen = 1;
  21908. }
  21909. if ($pos1 == $pos2) {
  21910. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  21911. $linew -= $one_space_width;
  21912. }
  21913. }
  21914. }
  21915. $mdiff = ($tw - $linew);
  21916. if ($plalign == 'C') {
  21917. if ($this->rtl) {
  21918. $t_x = -($mdiff / 2);
  21919. } else {
  21920. $t_x = ($mdiff / 2);
  21921. }
  21922. } elseif ($plalign == 'R') {
  21923. // right alignment on LTR document
  21924. $t_x = $mdiff;
  21925. } elseif ($plalign == 'L') {
  21926. // left alignment on RTL document
  21927. $t_x = -$mdiff;
  21928. } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
  21929. // Justification
  21930. if ($this->isRTLTextDir()) {
  21931. // align text on the left
  21932. $t_x = -$mdiff;
  21933. }
  21934. $ns = 0; // number of spaces
  21935. $pmidtemp = $pmid;
  21936. // escape special characters
  21937. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  21938. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  21939. // search spaces
  21940. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
  21941. $spacestr = $this->getSpaceString();
  21942. $maxkk = count($lnstring[1]) - 1;
  21943. for ($kk=0; $kk <= $maxkk; ++$kk) {
  21944. // restore special characters
  21945. $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
  21946. $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
  21947. // store number of spaces on the strings
  21948. $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
  21949. // count total spaces on line
  21950. $ns += $lnstring[2][$kk];
  21951. $lnstring[3][$kk] = $ns;
  21952. }
  21953. if ($ns == 0) {
  21954. $ns = 1;
  21955. }
  21956. // calculate additional space to add to each existing space
  21957. $spacewidth = ($mdiff / ($ns - $no)) * $this->k;
  21958. $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
  21959. if ($this->font_spacing != 0) {
  21960. // fixed spacing mode
  21961. $osw = -1000 * $this->font_spacing / $this->FontSize;
  21962. $spacewidthu += $osw;
  21963. }
  21964. $nsmax = $ns;
  21965. $ns = 0;
  21966. reset($lnstring);
  21967. $offset = 0;
  21968. $strcount = 0;
  21969. $prev_epsposbeg = 0;
  21970. $textpos = 0;
  21971. if ($this->isRTLTextDir()) {
  21972. $textpos = $this->wPt;
  21973. }
  21974. global $spacew;
  21975. while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
  21976. // check if we are inside a string section '[( ... )]'
  21977. $stroffset = strpos($pmid, '[(', $offset);
  21978. if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
  21979. // set offset to the end of string section
  21980. $offset = strpos($pmid, ')]', $stroffset);
  21981. while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
  21982. $offset = strpos($pmid, ')]', ($offset + 1));
  21983. }
  21984. if ($offset === false) {
  21985. $this->Error('HTML Justification: malformed PDF code.');
  21986. }
  21987. continue;
  21988. }
  21989. if ($this->isRTLTextDir()) {
  21990. $spacew = ($spacewidth * ($nsmax - $ns));
  21991. } else {
  21992. $spacew = ($spacewidth * $ns);
  21993. }
  21994. $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
  21995. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
  21996. $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
  21997. if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
  21998. OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
  21999. // shift EPS images
  22000. $trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
  22001. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
  22002. $pmid_b = substr($pmid, 0, $epsposbeg);
  22003. $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
  22004. $pmid_e = substr($pmid, $epsposend);
  22005. $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
  22006. $offset = $epsposend;
  22007. continue;
  22008. }
  22009. $prev_epsposbeg = $epsposbeg;
  22010. $currentxpos = 0;
  22011. // shift blocks of code
  22012. switch ($strpiece[2][0]) {
  22013. case 'Td':
  22014. case 'cm':
  22015. case 'm':
  22016. case 'l': {
  22017. // get current X position
  22018. preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  22019. $currentxpos = $xmatches[1];
  22020. $textpos = $currentxpos;
  22021. if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
  22022. $ns = $lnstring[3][$strcount];
  22023. if ($this->isRTLTextDir()) {
  22024. $spacew = ($spacewidth * ($nsmax - $ns));
  22025. }
  22026. ++$strcount;
  22027. }
  22028. // justify block
  22029. $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
  22030. create_function('$matches', 'global $spacew;
  22031. $newx = sprintf("%F",(floatval($matches[1]) + $spacew));
  22032. return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
  22033. break;
  22034. }
  22035. case 're': {
  22036. // justify block
  22037. if (!$this->empty_string($this->lispacer)) {
  22038. $this->lispacer = '';
  22039. continue;
  22040. }
  22041. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
  22042. $currentxpos = $xmatches[1];
  22043. global $x_diff, $w_diff;
  22044. $x_diff = 0;
  22045. $w_diff = 0;
  22046. if ($this->isRTLTextDir()) { // RTL
  22047. if ($currentxpos < $textpos) {
  22048. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
  22049. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  22050. } else {
  22051. if ($strcount > 0) {
  22052. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
  22053. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  22054. }
  22055. }
  22056. } else { // LTR
  22057. if ($currentxpos > $textpos) {
  22058. if ($strcount > 0) {
  22059. $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
  22060. }
  22061. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  22062. } else {
  22063. if ($strcount > 1) {
  22064. $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
  22065. }
  22066. if ($strcount > 0) {
  22067. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  22068. }
  22069. }
  22070. }
  22071. $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x',
  22072. create_function('$matches', 'global $x_diff, $w_diff;
  22073. $newx = sprintf("%F",(floatval($matches[1]) + $x_diff));
  22074. $neww = sprintf("%F",(floatval($matches[3]) + $w_diff));
  22075. return "".$newx." ".$matches[2]." ".$neww." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
  22076. break;
  22077. }
  22078. case 'c': {
  22079. // get current X position
  22080. 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);
  22081. $currentxpos = $xmatches[1];
  22082. // justify block
  22083. $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',
  22084. create_function('$matches', 'global $spacew;
  22085. $newx1 = sprintf("%F",(floatval($matches[1]) + $spacew));
  22086. $newx2 = sprintf("%F",(floatval($matches[3]) + $spacew));
  22087. $newx3 = sprintf("%F",(floatval($matches[5]) + $spacew));
  22088. return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
  22089. break;
  22090. }
  22091. }
  22092. // shift the annotations and links
  22093. $cxpos = ($currentxpos / $this->k);
  22094. $lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
  22095. if ($this->inxobj) {
  22096. // we are inside an XObject template
  22097. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  22098. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  22099. if ($cxpos > $lmpos) {
  22100. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
  22101. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  22102. } else {
  22103. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  22104. }
  22105. break;
  22106. }
  22107. }
  22108. } elseif (isset($this->PageAnnots[$this->page])) {
  22109. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  22110. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  22111. if ($cxpos > $lmpos) {
  22112. $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
  22113. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  22114. } else {
  22115. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  22116. }
  22117. break;
  22118. }
  22119. }
  22120. }
  22121. } // end of while
  22122. // remove markers
  22123. $pmid = str_replace('x*#!#*x', '', $pmid);
  22124. if ($this->isUnicodeFont()) {
  22125. // multibyte characters
  22126. $spacew = $spacewidthu;
  22127. if ($this->font_stretching != 100) {
  22128. // word spacing is affected by stretching
  22129. $spacew /= ($this->font_stretching / 100);
  22130. }
  22131. $pmidtemp = $pmid;
  22132. // escape special characters
  22133. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  22134. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  22135. $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
  22136. create_function('$matches', 'global $spacew;
  22137. $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
  22138. $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
  22139. return "[(".str_replace(chr(0).chr(32), ") ".sprintf("%F", $spacew)." (", $matches[1]).")]";'), $pmidtemp);
  22140. if ($this->inxobj) {
  22141. // we are inside an XObject template
  22142. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
  22143. } else {
  22144. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
  22145. }
  22146. $endlinepos = strlen($pstart."\n".$pmid."\n");
  22147. } else {
  22148. // non-unicode (single-byte characters)
  22149. if ($this->font_stretching != 100) {
  22150. // word spacing (Tw) is affected by stretching
  22151. $spacewidth /= ($this->font_stretching / 100);
  22152. }
  22153. $rs = sprintf('%F Tw', $spacewidth);
  22154. $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
  22155. if ($this->inxobj) {
  22156. // we are inside an XObject template
  22157. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
  22158. } else {
  22159. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
  22160. }
  22161. $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
  22162. }
  22163. }
  22164. } // end of J
  22165. } // end if $startlinex
  22166. if (($t_x != 0) OR ($yshift < 0)) {
  22167. // shift the line
  22168. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  22169. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  22170. $endlinepos = strlen($pstart);
  22171. if ($this->inxobj) {
  22172. // we are inside an XObject template
  22173. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  22174. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  22175. if ($pak >= $pask) {
  22176. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  22177. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  22178. }
  22179. }
  22180. } else {
  22181. $this->setPageBuffer($startlinepage, $pstart.$pend);
  22182. // shift the annotations and links
  22183. if (isset($this->PageAnnots[$this->page])) {
  22184. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  22185. if ($pak >= $pask) {
  22186. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  22187. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  22188. }
  22189. }
  22190. }
  22191. }
  22192. $this->y -= $yshift;
  22193. }
  22194. }
  22195. $pbrk = $this->checkPageBreak($this->lasth);
  22196. $this->newline = false;
  22197. $startlinex = $this->x;
  22198. $startliney = $this->y;
  22199. if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
  22200. $startliney -= ((0.3 * $this->FontSizePt) / $this->k);
  22201. } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
  22202. $startliney -= (($this->FontSizePt / 0.7) / $this->k);
  22203. } else {
  22204. $minstartliney = $startliney;
  22205. $maxbottomliney = ($this->y + (($fontsize * $this->cell_height_ratio) / $this->k));
  22206. }
  22207. $startlinepage = $this->page;
  22208. if (isset($endlinepos) AND (!$pbrk)) {
  22209. $startlinepos = $endlinepos;
  22210. } else {
  22211. if ($this->inxobj) {
  22212. // we are inside an XObject template
  22213. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  22214. } elseif (!$this->InFooter) {
  22215. if (isset($this->footerlen[$this->page])) {
  22216. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  22217. } else {
  22218. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  22219. }
  22220. $startlinepos = $this->footerpos[$this->page];
  22221. } else {
  22222. $startlinepos = $this->pagelen[$this->page];
  22223. }
  22224. }
  22225. unset($endlinepos);
  22226. $plalign = $lalign;
  22227. if (isset($this->PageAnnots[$this->page])) {
  22228. $pask = count($this->PageAnnots[$this->page]);
  22229. } else {
  22230. $pask = 0;
  22231. }
  22232. if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
  22233. AND (isset($this->emptypagemrk[$this->page]))
  22234. AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
  22235. $this->SetFont($fontname, $fontstyle, $fontsize);
  22236. if ($wfill) {
  22237. $this->SetFillColorArray($this->bgcolor);
  22238. }
  22239. }
  22240. } // end newline
  22241. if (isset($opentagpos)) {
  22242. unset($opentagpos);
  22243. }
  22244. if ($dom[$key]['tag']) {
  22245. if ($dom[$key]['opening']) {
  22246. // get text indentation (if any)
  22247. if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
  22248. $this->textindent = $dom[$key]['text-indent'];
  22249. $this->newline = true;
  22250. }
  22251. // table
  22252. if ($dom[$key]['value'] == 'table') {
  22253. // available page width
  22254. if ($this->rtl) {
  22255. $wtmp = $this->x - $this->lMargin;
  22256. } else {
  22257. $wtmp = $this->w - $this->rMargin - $this->x;
  22258. }
  22259. // get cell spacing
  22260. if (isset($dom[$key]['attribute']['cellspacing'])) {
  22261. $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
  22262. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  22263. } elseif (isset($dom[$key]['border-spacing'])) {
  22264. $cellspacing = $dom[$key]['border-spacing'];
  22265. } else {
  22266. $cellspacing = array('H' => 0, 'V' => 0);
  22267. }
  22268. // table width
  22269. if (isset($dom[$key]['width'])) {
  22270. $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  22271. } else {
  22272. $table_width = $wtmp;
  22273. }
  22274. $table_width -= (2 * $cellspacing['H']);
  22275. if (!$this->inthead) {
  22276. $this->y += $cellspacing['V'];
  22277. }
  22278. if ($this->rtl) {
  22279. $cellspacingx = -$cellspacing['H'];
  22280. } else {
  22281. $cellspacingx = $cellspacing['H'];
  22282. }
  22283. // total table width without cellspaces
  22284. $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
  22285. // minimum column width
  22286. $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
  22287. // array of custom column widths
  22288. $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
  22289. }
  22290. // table row
  22291. if ($dom[$key]['value'] == 'tr') {
  22292. // reset column counter
  22293. $colid = 0;
  22294. }
  22295. // table cell
  22296. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  22297. $trid = $dom[$key]['parent'];
  22298. $table_el = $dom[$trid]['parent'];
  22299. if (!isset($dom[$table_el]['cols'])) {
  22300. $dom[$table_el]['cols'] = $dom[$trid]['cols'];
  22301. }
  22302. // store border info
  22303. $tdborder = 0;
  22304. if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
  22305. $tdborder = $dom[$key]['border'];
  22306. }
  22307. $colspan = $dom[$key]['attribute']['colspan'];
  22308. $old_cell_padding = $this->cell_padding;
  22309. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
  22310. $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
  22311. $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
  22312. } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
  22313. $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
  22314. } else {
  22315. $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
  22316. }
  22317. $this->cell_padding = $current_cell_padding;
  22318. if (isset($dom[$key]['height'])) {
  22319. // minimum cell height
  22320. $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
  22321. } else {
  22322. $cellh = 0;
  22323. }
  22324. if (isset($dom[$key]['content'])) {
  22325. $cell_content = stripslashes($dom[$key]['content']);
  22326. } else {
  22327. $cell_content = '&nbsp;';
  22328. }
  22329. $tagtype = $dom[$key]['value'];
  22330. $parentid = $key;
  22331. while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
  22332. // move $key index forward
  22333. ++$key;
  22334. }
  22335. if (!isset($dom[$trid]['startpage'])) {
  22336. $dom[$trid]['startpage'] = $this->page;
  22337. } else {
  22338. $this->setPage($dom[$trid]['startpage']);
  22339. }
  22340. if (!isset($dom[$trid]['startcolumn'])) {
  22341. $dom[$trid]['startcolumn'] = $this->current_column;
  22342. } elseif ($this->current_column != $dom[$trid]['startcolumn']) {
  22343. $tmpx = $this->x;
  22344. $this->selectColumn($dom[$trid]['startcolumn']);
  22345. $this->x = $tmpx;
  22346. }
  22347. if (!isset($dom[$trid]['starty'])) {
  22348. $dom[$trid]['starty'] = $this->y;
  22349. } else {
  22350. $this->y = $dom[$trid]['starty'];
  22351. }
  22352. if (!isset($dom[$trid]['startx'])) {
  22353. $dom[$trid]['startx'] = $this->x;
  22354. $this->x += $cellspacingx;
  22355. } else {
  22356. $this->x += ($cellspacingx / 2);
  22357. }
  22358. if (isset($dom[$parentid]['attribute']['rowspan'])) {
  22359. $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
  22360. } else {
  22361. $rowspan = 1;
  22362. }
  22363. // skip row-spanned cells started on the previous rows
  22364. if (isset($dom[$table_el]['rowspans'])) {
  22365. $rsk = 0;
  22366. $rskmax = count($dom[$table_el]['rowspans']);
  22367. while ($rsk < $rskmax) {
  22368. $trwsp = $dom[$table_el]['rowspans'][$rsk];
  22369. $rsstartx = $trwsp['startx'];
  22370. $rsendx = $trwsp['endx'];
  22371. // account for margin changes
  22372. if ($trwsp['startpage'] < $this->page) {
  22373. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
  22374. $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
  22375. $rsstartx -= $dl;
  22376. $rsendx -= $dl;
  22377. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
  22378. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
  22379. $rsstartx += $dl;
  22380. $rsendx += $dl;
  22381. }
  22382. }
  22383. if (($trwsp['rowspan'] > 0)
  22384. AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
  22385. AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
  22386. AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
  22387. // set the starting X position of the current cell
  22388. $this->x = $rsendx + $cellspacingx;
  22389. // increment column indicator
  22390. $colid += $trwsp['colspan'];
  22391. if (($trwsp['rowspan'] == 1)
  22392. AND (isset($dom[$trid]['endy']))
  22393. AND (isset($dom[$trid]['endpage']))
  22394. AND (isset($dom[$trid]['endcolumn']))
  22395. AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
  22396. AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  22397. // set ending Y position for row
  22398. $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  22399. $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
  22400. }
  22401. $rsk = 0;
  22402. } else {
  22403. ++$rsk;
  22404. }
  22405. }
  22406. }
  22407. if (isset($dom[$parentid]['width'])) {
  22408. // user specified width
  22409. $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
  22410. $tmpcw = ($cellw / $colspan);
  22411. for ($i = 0; $i < $colspan; ++$i) {
  22412. $table_colwidths[($colid + $i)] = $tmpcw;
  22413. }
  22414. } else {
  22415. // inherit column width
  22416. $cellw = 0;
  22417. for ($i = 0; $i < $colspan; ++$i) {
  22418. $cellw += $table_colwidths[($colid + $i)];
  22419. }
  22420. }
  22421. $cellw += (($colspan - 1) * $cellspacing['H']);
  22422. // increment column indicator
  22423. $colid += $colspan;
  22424. // add rowspan information to table element
  22425. if ($rowspan > 1) {
  22426. $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));
  22427. }
  22428. $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
  22429. if ($rowspan > 1) {
  22430. $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
  22431. }
  22432. // push background colors
  22433. if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
  22434. $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
  22435. }
  22436. // store border info
  22437. if (isset($tdborder) AND !empty($tdborder)) {
  22438. $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
  22439. }
  22440. $prevLastH = $this->lasth;
  22441. // store some info for multicolumn mode
  22442. if ($this->rtl) {
  22443. $this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
  22444. } else {
  22445. $this->colxshift['x'] = $this->x - $this->lMargin;
  22446. }
  22447. $this->colxshift['s'] = $cellspacing;
  22448. $this->colxshift['p'] = $current_cell_padding;
  22449. // ****** write the cell content ******
  22450. $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
  22451. // restore some values
  22452. $this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  22453. $this->lasth = $prevLastH;
  22454. $this->cell_padding = $old_cell_padding;
  22455. $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
  22456. // update the end of row position
  22457. if ($rowspan <= 1) {
  22458. if (isset($dom[$trid]['endy'])) {
  22459. if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
  22460. $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
  22461. } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
  22462. $dom[$trid]['endy'] = $this->y;
  22463. }
  22464. } else {
  22465. $dom[$trid]['endy'] = $this->y;
  22466. }
  22467. if (isset($dom[$trid]['endpage'])) {
  22468. $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
  22469. } else {
  22470. $dom[$trid]['endpage'] = $this->page;
  22471. }
  22472. if (isset($dom[$trid]['endcolumn'])) {
  22473. $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
  22474. } else {
  22475. $dom[$trid]['endcolumn'] = $this->current_column;
  22476. }
  22477. } else {
  22478. // account for row-spanned cells
  22479. $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
  22480. $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
  22481. $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
  22482. $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
  22483. }
  22484. if (isset($dom[$table_el]['rowspans'])) {
  22485. // update endy and endpage on rowspanned cells
  22486. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  22487. if ($trwsp['rowspan'] > 0) {
  22488. if (isset($dom[$trid]['endpage'])) {
  22489. if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  22490. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  22491. } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
  22492. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
  22493. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
  22494. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
  22495. } else {
  22496. $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
  22497. }
  22498. }
  22499. }
  22500. }
  22501. }
  22502. $this->x += ($cellspacingx / 2);
  22503. } else {
  22504. // opening tag (or self-closing tag)
  22505. if (!isset($opentagpos)) {
  22506. if ($this->inxobj) {
  22507. // we are inside an XObject template
  22508. $opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
  22509. } elseif (!$this->InFooter) {
  22510. if (isset($this->footerlen[$this->page])) {
  22511. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  22512. } else {
  22513. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  22514. }
  22515. $opentagpos = $this->footerpos[$this->page];
  22516. }
  22517. }
  22518. $dom = $this->openHTMLTagHandler($dom, $key, $cell);
  22519. }
  22520. } else { // closing tag
  22521. $prev_numpages = $this->numpages;
  22522. $old_bordermrk = $this->bordermrk[$this->page];
  22523. $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
  22524. if ($this->bordermrk[$this->page] > $old_bordermrk) {
  22525. $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
  22526. }
  22527. if ($prev_numpages > $this->numpages) {
  22528. $startlinepage = $this->page;
  22529. }
  22530. }
  22531. } elseif (strlen($dom[$key]['value']) > 0) {
  22532. // print list-item
  22533. if (!$this->empty_string($this->lispacer) AND ($this->lispacer != '^')) {
  22534. $this->SetFont($pfontname, $pfontstyle, $pfontsize);
  22535. $this->resetLastH();
  22536. $minstartliney = $this->y;
  22537. $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio));
  22538. $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
  22539. $this->SetFont($curfontname, $curfontstyle, $curfontsize);
  22540. $this->resetLastH();
  22541. if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
  22542. $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
  22543. $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
  22544. $this->y += ((($pfontsize - $curfontsize) * $this->cell_height_ratio / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
  22545. $minstartliney = min($this->y, $minstartliney);
  22546. $maxbottomliney = max(($this->y + (($pfontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney);
  22547. }
  22548. }
  22549. // text
  22550. $this->htmlvspace = 0;
  22551. if ((!$this->premode) AND $this->isRTLTextDir()) {
  22552. // reverse spaces order
  22553. $lsp = ''; // left spaces
  22554. $rsp = ''; // right spaces
  22555. if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  22556. $lsp = $matches[1];
  22557. }
  22558. if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  22559. $rsp = $matches[1];
  22560. }
  22561. $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
  22562. }
  22563. if ($newline) {
  22564. if (!$this->premode) {
  22565. $prelen = strlen($dom[$key]['value']);
  22566. if ($this->isRTLTextDir()) {
  22567. // right trim except non-breaking space
  22568. $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
  22569. } else {
  22570. // left trim except non-breaking space
  22571. $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
  22572. }
  22573. $postlen = strlen($dom[$key]['value']);
  22574. if (($postlen == 0) AND ($prelen > 0)) {
  22575. $dom[$key]['trimmed_space'] = true;
  22576. }
  22577. }
  22578. $newline = false;
  22579. $firstblock = true;
  22580. } else {
  22581. $firstblock = false;
  22582. // replace empty multiple spaces string with a single space
  22583. $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
  22584. }
  22585. $strrest = '';
  22586. if ($this->rtl) {
  22587. $this->x -= $this->textindent;
  22588. } else {
  22589. $this->x += $this->textindent;
  22590. }
  22591. if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
  22592. $strlinelen = $this->GetStringWidth($dom[$key]['value']);
  22593. if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
  22594. // HTML <a> Link
  22595. $hrefcolor = '';
  22596. if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
  22597. $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
  22598. }
  22599. $hrefstyle = -1;
  22600. if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
  22601. $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
  22602. }
  22603. $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
  22604. } else {
  22605. $wadj = 0; // space to leave for block continuity
  22606. if ($this->rtl) {
  22607. $cwa = ($this->x - $this->lMargin);
  22608. } else {
  22609. $cwa = ($this->w - $this->rMargin - $this->x);
  22610. }
  22611. if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
  22612. // check the next text blocks for continuity
  22613. $nkey = ($key + 1);
  22614. $write_block = true;
  22615. $same_textdir = true;
  22616. $tmp_fontname = $this->FontFamily;
  22617. $tmp_fontstyle = $this->FontStyle;
  22618. $tmp_fontsize = $this->FontSizePt;
  22619. while ($write_block AND isset($dom[$nkey])) {
  22620. if ($dom[$nkey]['tag']) {
  22621. if ($dom[$nkey]['block']) {
  22622. // end of block
  22623. $write_block = false;
  22624. }
  22625. $tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
  22626. $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
  22627. $tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
  22628. $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
  22629. } else {
  22630. $nextstr = preg_split('/'.$this->re_space['p'].'+/'.$this->re_space['m'], $dom[$nkey]['value']);
  22631. if (isset($nextstr[0]) AND $same_textdir) {
  22632. $wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
  22633. if (isset($nextstr[1])) {
  22634. $write_block = false;
  22635. }
  22636. }
  22637. }
  22638. ++$nkey;
  22639. }
  22640. }
  22641. if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
  22642. $wadj = 0;
  22643. $nextstr = preg_split('/'.$this->re_space['p'].'/'.$this->re_space['m'], $dom[$key]['value']);
  22644. $numblks = count($nextstr);
  22645. if ($numblks > 1) {
  22646. // try to split on blank spaces
  22647. $wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
  22648. } else {
  22649. // set the entire block on new line
  22650. $wadj = $this->GetStringWidth($nextstr[0]);
  22651. }
  22652. }
  22653. // check for reversed text direction
  22654. if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
  22655. // LTR text on RTL direction or RTL text on LTR direction
  22656. $reverse_dir = true;
  22657. $this->rtl = !$this->rtl;
  22658. $revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
  22659. if ($this->rtl) {
  22660. $this->x += $revshift;
  22661. } else {
  22662. $this->x -= $revshift;
  22663. }
  22664. $xws = $this->x;
  22665. }
  22666. // ****** write only until the end of the line and get the rest ******
  22667. $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
  22668. // restore default direction
  22669. if ($reverse_dir AND ($wadj == 0)) {
  22670. $this->x = $xws;
  22671. $this->rtl = !$this->rtl;
  22672. $reverse_dir = false;
  22673. }
  22674. }
  22675. }
  22676. $this->textindent = 0;
  22677. if (strlen($strrest) > 0) {
  22678. // store the remaining string on the previous $key position
  22679. $this->newline = true;
  22680. if ($strrest == $dom[$key]['value']) {
  22681. // used to avoid infinite loop
  22682. ++$loop;
  22683. } else {
  22684. $loop = 0;
  22685. }
  22686. $dom[$key]['value'] = $strrest;
  22687. if ($cell) {
  22688. if ($this->rtl) {
  22689. $this->x -= $this->cell_padding['R'];
  22690. } else {
  22691. $this->x += $this->cell_padding['L'];
  22692. }
  22693. }
  22694. if ($loop < 3) {
  22695. --$key;
  22696. }
  22697. } else {
  22698. $loop = 0;
  22699. // add the positive font spacing of the last character (if any)
  22700. if ($this->font_spacing > 0) {
  22701. if ($this->rtl) {
  22702. $this->x -= $this->font_spacing;
  22703. } else {
  22704. $this->x += $this->font_spacing;
  22705. }
  22706. }
  22707. }
  22708. }
  22709. ++$key;
  22710. 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')) {
  22711. // check if we are on a new page or on a new column
  22712. if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
  22713. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  22714. // restore previous object
  22715. $this->rollbackTransaction(true);
  22716. // restore previous values
  22717. foreach ($this_method_vars as $vkey => $vval) {
  22718. $$vkey = $vval;
  22719. }
  22720. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  22721. $pre_y = $this->y;
  22722. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  22723. $startliney = $this->y;
  22724. }
  22725. $undo = true; // avoid infinite loop
  22726. } else {
  22727. $undo = false;
  22728. }
  22729. }
  22730. } // end for each $key
  22731. // align the last line
  22732. if (isset($startlinex)) {
  22733. $yshift = ($minstartliney - $startliney);
  22734. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  22735. $yshift = 0;
  22736. }
  22737. $t_x = 0;
  22738. // the last line must be shifted to be aligned as requested
  22739. $linew = abs($this->endlinex - $startlinex);
  22740. if ($this->inxobj) {
  22741. // we are inside an XObject template
  22742. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  22743. if (isset($opentagpos)) {
  22744. $midpos = $opentagpos;
  22745. } else {
  22746. $midpos = 0;
  22747. }
  22748. if ($midpos > 0) {
  22749. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  22750. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  22751. } else {
  22752. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  22753. $pend = '';
  22754. }
  22755. } else {
  22756. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  22757. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  22758. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  22759. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  22760. } elseif (isset($opentagpos)) {
  22761. $midpos = $opentagpos;
  22762. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  22763. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  22764. $midpos = $this->footerpos[$startlinepage];
  22765. } else {
  22766. $midpos = 0;
  22767. }
  22768. if ($midpos > 0) {
  22769. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  22770. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  22771. } else {
  22772. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  22773. $pend = '';
  22774. }
  22775. }
  22776. if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  22777. // calculate shifting amount
  22778. $tw = $w;
  22779. if ($this->lMargin != $prevlMargin) {
  22780. $tw += ($prevlMargin - $this->lMargin);
  22781. }
  22782. if ($this->rMargin != $prevrMargin) {
  22783. $tw += ($prevrMargin - $this->rMargin);
  22784. }
  22785. $one_space_width = $this->GetStringWidth(chr(32));
  22786. $no = 0; // number of spaces on a line contained on a single block
  22787. if ($this->isRTLTextDir()) { // RTL
  22788. // remove left space if exist
  22789. $pos1 = $this->revstrpos($pmid, '[(');
  22790. if ($pos1 > 0) {
  22791. $pos1 = intval($pos1);
  22792. if ($this->isUnicodeFont()) {
  22793. $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32)));
  22794. $spacelen = 2;
  22795. } else {
  22796. $pos2 = intval($this->revstrpos($pmid, '[('.chr(32)));
  22797. $spacelen = 1;
  22798. }
  22799. if ($pos1 == $pos2) {
  22800. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  22801. if (substr($pmid, $pos1, 4) == '[()]') {
  22802. $linew -= $one_space_width;
  22803. } elseif ($pos1 == strpos($pmid, '[(')) {
  22804. $no = 1;
  22805. }
  22806. }
  22807. }
  22808. } else { // LTR
  22809. // remove right space if exist
  22810. $pos1 = $this->revstrpos($pmid, ')]');
  22811. if ($pos1 > 0) {
  22812. $pos1 = intval($pos1);
  22813. if ($this->isUnicodeFont()) {
  22814. $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  22815. $spacelen = 2;
  22816. } else {
  22817. $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1;
  22818. $spacelen = 1;
  22819. }
  22820. if ($pos1 == $pos2) {
  22821. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  22822. $linew -= $one_space_width;
  22823. }
  22824. }
  22825. }
  22826. $mdiff = ($tw - $linew);
  22827. if ($plalign == 'C') {
  22828. if ($this->rtl) {
  22829. $t_x = -($mdiff / 2);
  22830. } else {
  22831. $t_x = ($mdiff / 2);
  22832. }
  22833. } elseif ($plalign == 'R') {
  22834. // right alignment on LTR document
  22835. $t_x = $mdiff;
  22836. } elseif ($plalign == 'L') {
  22837. // left alignment on RTL document
  22838. $t_x = -$mdiff;
  22839. }
  22840. } // end if startlinex
  22841. if (($t_x != 0) OR ($yshift < 0)) {
  22842. // shift the line
  22843. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  22844. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  22845. $endlinepos = strlen($pstart);
  22846. if ($this->inxobj) {
  22847. // we are inside an XObject template
  22848. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  22849. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  22850. if ($pak >= $pask) {
  22851. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  22852. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  22853. }
  22854. }
  22855. } else {
  22856. $this->setPageBuffer($startlinepage, $pstart.$pend);
  22857. // shift the annotations and links
  22858. if (isset($this->PageAnnots[$this->page])) {
  22859. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  22860. if ($pak >= $pask) {
  22861. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  22862. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  22863. }
  22864. }
  22865. }
  22866. }
  22867. $this->y -= $yshift;
  22868. $yshift = 0;
  22869. }
  22870. }
  22871. // restore previous values
  22872. $this->setGraphicVars($gvars);
  22873. if ($this->num_columns > 1) {
  22874. $this->selectColumn();
  22875. } elseif ($this->page > $prevPage) {
  22876. $this->lMargin = $this->pagedim[$this->page]['olm'];
  22877. $this->rMargin = $this->pagedim[$this->page]['orm'];
  22878. }
  22879. // restore previous list state
  22880. $this->cell_height_ratio = $prev_cell_height_ratio;
  22881. $this->listnum = $prev_listnum;
  22882. $this->listordered = $prev_listordered;
  22883. $this->listcount = $prev_listcount;
  22884. $this->lispacer = $prev_lispacer;
  22885. if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
  22886. $this->Ln($this->lasth);
  22887. if ($this->y < $maxbottomliney) {
  22888. $this->y = $maxbottomliney;
  22889. }
  22890. }
  22891. unset($dom);
  22892. }
  22893. /**
  22894. * Process opening tags.
  22895. * @param $dom (array) html dom array
  22896. * @param $key (int) current element id
  22897. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  22898. * @return $dom array
  22899. * @protected
  22900. */
  22901. protected function openHTMLTagHandler($dom, $key, $cell) {
  22902. $tag = $dom[$key];
  22903. $parent = $dom[($dom[$key]['parent'])];
  22904. $firsttag = ($key == 1);
  22905. // check for text direction attribute
  22906. if (isset($tag['dir'])) {
  22907. $this->setTempRTL($tag['dir']);
  22908. } else {
  22909. $this->tmprtl = false;
  22910. }
  22911. if ($tag['block']) {
  22912. $hbz = 0; // distance from y to line bottom
  22913. $hb = 0; // vertical space between block tags
  22914. // calculate vertical space for block tags
  22915. if (isset($this->tagvspaces[$tag['value']][0]['h']) AND ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
  22916. $cur_h = $this->tagvspaces[$tag['value']][0]['h'];
  22917. } elseif (isset($tag['fontsize'])) {
  22918. $cur_h = ($tag['fontsize'] / $this->k) * $this->cell_height_ratio;
  22919. } else {
  22920. $cur_h = $this->FontSize * $this->cell_height_ratio;
  22921. }
  22922. if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
  22923. $n = $this->tagvspaces[$tag['value']][0]['n'];
  22924. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  22925. $n = 0.6;
  22926. } else {
  22927. $n = 1;
  22928. }
  22929. if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br')))) {
  22930. $hb = 0;
  22931. } else {
  22932. $hb = ($n * $cur_h);
  22933. }
  22934. if (($this->htmlvspace <= 0) AND ($n > 0)) {
  22935. if (isset($parent['fontsize'])) {
  22936. $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  22937. } else {
  22938. $hbz = $this->FontSize * $this->cell_height_ratio;
  22939. }
  22940. }
  22941. }
  22942. // Opening tag
  22943. switch($tag['value']) {
  22944. case 'table': {
  22945. $cp = 0;
  22946. $cs = 0;
  22947. $dom[$key]['rowspans'] = array();
  22948. if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
  22949. // set table header
  22950. if (!$this->empty_string($dom[$key]['thead'])) {
  22951. // set table header
  22952. $this->thead = $dom[$key]['thead'];
  22953. if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
  22954. $this->theadMargins = array();
  22955. $this->theadMargins['cell_padding'] = $this->cell_padding;
  22956. $this->theadMargins['lmargin'] = $this->lMargin;
  22957. $this->theadMargins['rmargin'] = $this->rMargin;
  22958. $this->theadMargins['page'] = $this->page;
  22959. $this->theadMargins['cell'] = $cell;
  22960. }
  22961. }
  22962. }
  22963. // store current margins and page
  22964. $dom[$key]['old_cell_padding'] = $this->cell_padding;
  22965. if (isset($tag['attribute']['cellpadding'])) {
  22966. $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
  22967. $this->SetCellPadding($pad);
  22968. } elseif (isset($tag['padding'])) {
  22969. $this->cell_padding = $tag['padding'];
  22970. }
  22971. if (isset($tag['attribute']['cellspacing'])) {
  22972. $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  22973. } elseif (isset($tag['border-spacing'])) {
  22974. $cs = $tag['border-spacing']['V'];
  22975. }
  22976. $prev_y = $this->y;
  22977. if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
  22978. $this->inthead = true;
  22979. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  22980. $this->checkPageBreak($this->PageBreakTrigger + 1);
  22981. }
  22982. break;
  22983. }
  22984. case 'tr': {
  22985. // array of columns positions
  22986. $dom[$key]['cellpos'] = array();
  22987. break;
  22988. }
  22989. case 'hr': {
  22990. if ((isset($tag['height'])) AND ($tag['height'] != '')) {
  22991. $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
  22992. } else {
  22993. $hrHeight = $this->GetLineWidth();
  22994. }
  22995. $this->addHTMLVertSpace($hbz, ($hrHeight / 2), $cell, $firsttag);
  22996. $x = $this->GetX();
  22997. $y = $this->GetY();
  22998. $wtmp = $this->w - $this->lMargin - $this->rMargin;
  22999. if ($cell) {
  23000. $wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  23001. }
  23002. if ((isset($tag['width'])) AND ($tag['width'] != '')) {
  23003. $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
  23004. } else {
  23005. $hrWidth = $wtmp;
  23006. }
  23007. $prevlinewidth = $this->GetLineWidth();
  23008. $this->SetLineWidth($hrHeight);
  23009. $this->Line($x, $y, $x + $hrWidth, $y);
  23010. $this->SetLineWidth($prevlinewidth);
  23011. $this->addHTMLVertSpace(($hrHeight / 2), 0, $cell, !isset($dom[($key + 1)]));
  23012. break;
  23013. }
  23014. case 'a': {
  23015. if (array_key_exists('href', $tag['attribute'])) {
  23016. $this->HREF['url'] = $tag['attribute']['href'];
  23017. }
  23018. break;
  23019. }
  23020. case 'img': {
  23021. if (isset($tag['attribute']['src'])) {
  23022. if ($tag['attribute']['src']{0} === '@') {
  23023. // data stream
  23024. $tag['attribute']['src'] = '@'.base64_decode(substr($tag['attribute']['src'], 1));
  23025. $type = '';
  23026. } else {
  23027. // check for images without protocol
  23028. if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
  23029. $tag['attribute']['src'] = 'http:'.$tag['attribute']['src'];
  23030. }
  23031. /* PrestaShop
  23032. // replace relative path with real server path
  23033. if (($tag['attribute']['src'][0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  23034. $findroot = strpos($tag['attribute']['src'], $_SERVER['DOCUMENT_ROOT']);
  23035. if (($findroot === false) OR ($findroot > 1)) {
  23036. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  23037. $tag['attribute']['src'] = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$tag['attribute']['src'];
  23038. } else {
  23039. $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
  23040. }
  23041. }
  23042. }*/
  23043. $tag['attribute']['src'] = htmlspecialchars_decode(urldecode($tag['attribute']['src']));
  23044. $type = $this->getImageFileType($tag['attribute']['src']);
  23045. $testscrtype = @parse_url($tag['attribute']['src']);
  23046. if (!isset($testscrtype['query']) OR empty($testscrtype['query'])) {
  23047. // convert URL to server path
  23048. $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
  23049. }
  23050. }
  23051. if (!isset($tag['width'])) {
  23052. $tag['width'] = 0;
  23053. }
  23054. if (!isset($tag['height'])) {
  23055. $tag['height'] = 0;
  23056. }
  23057. //if (!isset($tag['attribute']['align'])) {
  23058. // the only alignment supported is "bottom"
  23059. // further development is required for other modes.
  23060. $tag['attribute']['align'] = 'bottom';
  23061. //}
  23062. switch($tag['attribute']['align']) {
  23063. case 'top': {
  23064. $align = 'T';
  23065. break;
  23066. }
  23067. case 'middle': {
  23068. $align = 'M';
  23069. break;
  23070. }
  23071. case 'bottom': {
  23072. $align = 'B';
  23073. break;
  23074. }
  23075. default: {
  23076. $align = 'B';
  23077. break;
  23078. }
  23079. }
  23080. $prevy = $this->y;
  23081. $xpos = $this->x;
  23082. $imglink = '';
  23083. if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
  23084. $imglink = $this->HREF['url'];
  23085. if ($imglink{0} == '#') {
  23086. // convert url to internal link
  23087. $lnkdata = explode(',', $imglink);
  23088. if (isset($lnkdata[0])) {
  23089. $page = intval(substr($lnkdata[0], 1));
  23090. if (empty($page) OR ($page <= 0)) {
  23091. $page = $this->page;
  23092. }
  23093. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  23094. $lnky = floatval($lnkdata[1]);
  23095. } else {
  23096. $lnky = 0;
  23097. }
  23098. $imglink = $this->AddLink();
  23099. $this->SetLink($imglink, $lnky, $page);
  23100. }
  23101. }
  23102. }
  23103. $border = 0;
  23104. if (isset($tag['border']) AND !empty($tag['border'])) {
  23105. // currently only support 1 (frame) or a combination of 'LTRB'
  23106. $border = $tag['border'];
  23107. }
  23108. $iw = '';
  23109. if (isset($tag['width'])) {
  23110. $iw = $this->getHTMLUnitToUnits($tag['width'], 1, 'px', false);
  23111. }
  23112. $ih = '';
  23113. if (isset($tag['height'])) {
  23114. $ih = $this->getHTMLUnitToUnits($tag['height'], 1, 'px', false);
  23115. }
  23116. if (($type == 'eps') OR ($type == 'ai')) {
  23117. $this->ImageEps($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
  23118. } elseif ($type == 'svg') {
  23119. $this->ImageSVG($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
  23120. } else {
  23121. $this->Image($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
  23122. }
  23123. switch($align) {
  23124. case 'T': {
  23125. $this->y = $prevy;
  23126. break;
  23127. }
  23128. case 'M': {
  23129. $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
  23130. break;
  23131. }
  23132. case 'B': {
  23133. $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
  23134. break;
  23135. }
  23136. }
  23137. }
  23138. break;
  23139. }
  23140. case 'dl': {
  23141. ++$this->listnum;
  23142. if ($this->listnum == 1) {
  23143. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23144. } else {
  23145. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  23146. }
  23147. break;
  23148. }
  23149. case 'dt': {
  23150. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23151. break;
  23152. }
  23153. case 'dd': {
  23154. if ($this->rtl) {
  23155. $this->rMargin += $this->listindent;
  23156. } else {
  23157. $this->lMargin += $this->listindent;
  23158. }
  23159. ++$this->listindentlevel;
  23160. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23161. break;
  23162. }
  23163. case 'ul':
  23164. case 'ol': {
  23165. ++$this->listnum;
  23166. if ($tag['value'] == 'ol') {
  23167. $this->listordered[$this->listnum] = true;
  23168. } else {
  23169. $this->listordered[$this->listnum] = false;
  23170. }
  23171. if (isset($tag['attribute']['start'])) {
  23172. $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
  23173. } else {
  23174. $this->listcount[$this->listnum] = 0;
  23175. }
  23176. if ($this->rtl) {
  23177. $this->rMargin += $this->listindent;
  23178. $this->x -= $this->listindent;
  23179. } else {
  23180. $this->lMargin += $this->listindent;
  23181. $this->x += $this->listindent;
  23182. }
  23183. ++$this->listindentlevel;
  23184. if ($this->listnum == 1) {
  23185. if ($key > 1) {
  23186. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23187. }
  23188. } else {
  23189. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  23190. }
  23191. break;
  23192. }
  23193. case 'li': {
  23194. if ($key > 2) {
  23195. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23196. }
  23197. if ($this->listordered[$this->listnum]) {
  23198. // ordered item
  23199. if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
  23200. $this->lispacer = $parent['attribute']['type'];
  23201. } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
  23202. $this->lispacer = $parent['listtype'];
  23203. } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
  23204. $this->lispacer = $this->lisymbol;
  23205. } else {
  23206. $this->lispacer = '#';
  23207. }
  23208. ++$this->listcount[$this->listnum];
  23209. if (isset($tag['attribute']['value'])) {
  23210. $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
  23211. }
  23212. } else {
  23213. // unordered item
  23214. if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
  23215. $this->lispacer = $parent['attribute']['type'];
  23216. } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
  23217. $this->lispacer = $parent['listtype'];
  23218. } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
  23219. $this->lispacer = $this->lisymbol;
  23220. } else {
  23221. $this->lispacer = '!';
  23222. }
  23223. }
  23224. break;
  23225. }
  23226. case 'blockquote': {
  23227. if ($this->rtl) {
  23228. $this->rMargin += $this->listindent;
  23229. } else {
  23230. $this->lMargin += $this->listindent;
  23231. }
  23232. ++$this->listindentlevel;
  23233. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23234. break;
  23235. }
  23236. case 'br': {
  23237. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23238. break;
  23239. }
  23240. case 'div': {
  23241. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23242. break;
  23243. }
  23244. case 'p': {
  23245. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23246. break;
  23247. }
  23248. case 'pre': {
  23249. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23250. $this->premode = true;
  23251. break;
  23252. }
  23253. case 'sup': {
  23254. $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
  23255. break;
  23256. }
  23257. case 'sub': {
  23258. $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
  23259. break;
  23260. }
  23261. case 'h1':
  23262. case 'h2':
  23263. case 'h3':
  23264. case 'h4':
  23265. case 'h5':
  23266. case 'h6': {
  23267. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  23268. break;
  23269. }
  23270. // Form fields (since 4.8.000 - 2009-09-07)
  23271. case 'form': {
  23272. if (isset($tag['attribute']['action'])) {
  23273. $this->form_action = $tag['attribute']['action'];
  23274. } else {
  23275. $this->form_action = K_PATH_URL.$_SERVER['SCRIPT_NAME'];
  23276. }
  23277. if (isset($tag['attribute']['enctype'])) {
  23278. $this->form_enctype = $tag['attribute']['enctype'];
  23279. } else {
  23280. $this->form_enctype = 'application/x-www-form-urlencoded';
  23281. }
  23282. if (isset($tag['attribute']['method'])) {
  23283. $this->form_mode = $tag['attribute']['method'];
  23284. } else {
  23285. $this->form_mode = 'post';
  23286. }
  23287. break;
  23288. }
  23289. case 'input': {
  23290. if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
  23291. $name = $tag['attribute']['name'];
  23292. } else {
  23293. break;
  23294. }
  23295. $prop = array();
  23296. $opt = array();
  23297. if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) {
  23298. $prop['readonly'] = true;
  23299. }
  23300. if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) {
  23301. $value = $tag['attribute']['value'];
  23302. }
  23303. if (isset($tag['attribute']['maxlength']) AND !$this->empty_string($tag['attribute']['maxlength'])) {
  23304. $opt['maxlen'] = intval($tag['attribute']['maxlength']);
  23305. }
  23306. $h = $this->FontSize * $this->cell_height_ratio;
  23307. if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) {
  23308. $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
  23309. } else {
  23310. $w = $h;
  23311. }
  23312. if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
  23313. $checked = true;
  23314. } else {
  23315. $checked = false;
  23316. }
  23317. if (isset($tag['align'])) {
  23318. switch ($tag['align']) {
  23319. case 'C': {
  23320. $opt['q'] = 1;
  23321. break;
  23322. }
  23323. case 'R': {
  23324. $opt['q'] = 2;
  23325. break;
  23326. }
  23327. case 'L':
  23328. default: {
  23329. break;
  23330. }
  23331. }
  23332. }
  23333. switch ($tag['attribute']['type']) {
  23334. case 'text': {
  23335. if (isset($value)) {
  23336. $opt['v'] = $value;
  23337. }
  23338. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  23339. break;
  23340. }
  23341. case 'password': {
  23342. if (isset($value)) {
  23343. $opt['v'] = $value;
  23344. }
  23345. $prop['password'] = 'true';
  23346. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  23347. break;
  23348. }
  23349. case 'checkbox': {
  23350. if (!isset($value)) {
  23351. break;
  23352. }
  23353. $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
  23354. break;
  23355. }
  23356. case 'radio': {
  23357. if (!isset($value)) {
  23358. break;
  23359. }
  23360. $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
  23361. break;
  23362. }
  23363. case 'submit': {
  23364. if (!isset($value)) {
  23365. $value = 'submit';
  23366. }
  23367. $w = $this->GetStringWidth($value) * 1.5;
  23368. $h *= 1.6;
  23369. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  23370. $action = array();
  23371. $action['S'] = 'SubmitForm';
  23372. $action['F'] = $this->form_action;
  23373. if ($this->form_enctype != 'FDF') {
  23374. $action['Flags'] = array('ExportFormat');
  23375. }
  23376. if ($this->form_mode == 'get') {
  23377. $action['Flags'] = array('GetMethod');
  23378. }
  23379. $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
  23380. break;
  23381. }
  23382. case 'reset': {
  23383. if (!isset($value)) {
  23384. $value = 'reset';
  23385. }
  23386. $w = $this->GetStringWidth($value) * 1.5;
  23387. $h *= 1.6;
  23388. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  23389. $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
  23390. break;
  23391. }
  23392. case 'file': {
  23393. $prop['fileSelect'] = 'true';
  23394. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  23395. if (!isset($value)) {
  23396. $value = '*';
  23397. }
  23398. $w = $this->GetStringWidth($value) * 2;
  23399. $h *= 1.2;
  23400. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  23401. $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
  23402. $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  23403. break;
  23404. }
  23405. case 'hidden': {
  23406. if (isset($value)) {
  23407. $opt['v'] = $value;
  23408. }
  23409. $opt['f'] = array('invisible', 'hidden');
  23410. $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
  23411. break;
  23412. }
  23413. case 'image': {
  23414. // THIS TYPE MUST BE FIXED
  23415. if (isset($tag['attribute']['src']) AND !$this->empty_string($tag['attribute']['src'])) {
  23416. $img = $tag['attribute']['src'];
  23417. } else {
  23418. break;
  23419. }
  23420. $value = 'img';
  23421. //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
  23422. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  23423. $jsaction = $tag['attribute']['onclick'];
  23424. } else {
  23425. $jsaction = '';
  23426. }
  23427. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  23428. break;
  23429. }
  23430. case 'button': {
  23431. if (!isset($value)) {
  23432. $value = ' ';
  23433. }
  23434. $w = $this->GetStringWidth($value) * 1.5;
  23435. $h *= 1.6;
  23436. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  23437. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  23438. $jsaction = $tag['attribute']['onclick'];
  23439. } else {
  23440. $jsaction = '';
  23441. }
  23442. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  23443. break;
  23444. }
  23445. }
  23446. break;
  23447. }
  23448. case 'textarea': {
  23449. $prop = array();
  23450. $opt = array();
  23451. if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) {
  23452. $prop['readonly'] = true;
  23453. }
  23454. if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
  23455. $name = $tag['attribute']['name'];
  23456. } else {
  23457. break;
  23458. }
  23459. if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) {
  23460. $opt['v'] = $tag['attribute']['value'];
  23461. }
  23462. if (isset($tag['attribute']['cols']) AND !$this->empty_string($tag['attribute']['cols'])) {
  23463. $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
  23464. } else {
  23465. $w = 40;
  23466. }
  23467. if (isset($tag['attribute']['rows']) AND !$this->empty_string($tag['attribute']['rows'])) {
  23468. $h = intval($tag['attribute']['rows']) * $this->FontSize * $this->cell_height_ratio;
  23469. } else {
  23470. $h = 10;
  23471. }
  23472. $prop['multiline'] = 'true';
  23473. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  23474. break;
  23475. }
  23476. case 'select': {
  23477. $h = $this->FontSize * $this->cell_height_ratio;
  23478. if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) {
  23479. $h *= ($tag['attribute']['size'] + 1);
  23480. }
  23481. $prop = array();
  23482. $opt = array();
  23483. if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
  23484. $name = $tag['attribute']['name'];
  23485. } else {
  23486. break;
  23487. }
  23488. $w = 0;
  23489. if (isset($tag['attribute']['opt']) AND !$this->empty_string($tag['attribute']['opt'])) {
  23490. $options = explode('#!NwL!#', $tag['attribute']['opt']);
  23491. $values = array();
  23492. foreach ($options as $val) {
  23493. if (strpos($val, '#!TaB!#') !== false) {
  23494. $opts = explode('#!TaB!#', $val);
  23495. $values[] = $opts;
  23496. $w = max($w, $this->GetStringWidth($opts[1]));
  23497. } else {
  23498. $values[] = $val;
  23499. $w = max($w, $this->GetStringWidth($val));
  23500. }
  23501. }
  23502. } else {
  23503. break;
  23504. }
  23505. $w *= 2;
  23506. if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
  23507. $prop['multipleSelection'] = 'true';
  23508. $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  23509. } else {
  23510. $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  23511. }
  23512. break;
  23513. }
  23514. case 'tcpdf': {
  23515. if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
  23516. // Special tag used to call TCPDF methods
  23517. if (isset($tag['attribute']['method'])) {
  23518. $tcpdf_method = $tag['attribute']['method'];
  23519. if (method_exists($this, $tcpdf_method)) {
  23520. if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
  23521. $params = unserialize(urldecode($tag['attribute']['params']));
  23522. call_user_func_array(array($this, $tcpdf_method), $params);
  23523. } else {
  23524. $this->$tcpdf_method();
  23525. }
  23526. $this->newline = true;
  23527. }
  23528. }
  23529. }
  23530. break;
  23531. }
  23532. default: {
  23533. break;
  23534. }
  23535. }
  23536. // define tags that support borders and background colors
  23537. $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
  23538. if (in_array($tag['value'], $bordertags)) {
  23539. // set border
  23540. $dom[$key]['borderposition'] = $this->getBorderStartPosition();
  23541. }
  23542. if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
  23543. $pba = $dom[$key]['attribute']['pagebreakafter'];
  23544. // check for pagebreak
  23545. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  23546. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  23547. $this->checkPageBreak($this->PageBreakTrigger + 1);
  23548. }
  23549. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  23550. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  23551. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  23552. $this->checkPageBreak($this->PageBreakTrigger + 1);
  23553. }
  23554. }
  23555. return $dom;
  23556. }
  23557. /**
  23558. * Process closing tags.
  23559. * @param $dom (array) html dom array
  23560. * @param $key (int) current element id
  23561. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  23562. * @param $maxbottomliney (int) maximum y value of current line
  23563. * @return $dom array
  23564. * @protected
  23565. */
  23566. protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
  23567. $tag = $dom[$key];
  23568. $parent = $dom[($dom[$key]['parent'])];
  23569. $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
  23570. $in_table_head = false;
  23571. // maximum x position (used to draw borders)
  23572. if ($this->rtl) {
  23573. $xmax = $this->w;
  23574. } else {
  23575. $xmax = 0;
  23576. }
  23577. if ($tag['block']) {
  23578. $hbz = 0; // distance from y to line bottom
  23579. $hb = 0; // vertical space between block tags
  23580. // calculate vertical space for block tags
  23581. if (isset($this->tagvspaces[$tag['value']][1]['h']) AND ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  23582. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  23583. } elseif (isset($parent['fontsize'])) {
  23584. $pre_h = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  23585. } else {
  23586. $pre_h = $this->FontSize * $this->cell_height_ratio;
  23587. }
  23588. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  23589. $n = $this->tagvspaces[$tag['value']][1]['n'];
  23590. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  23591. $n = 0.6;
  23592. } else {
  23593. $n = 1;
  23594. }
  23595. if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
  23596. $hb = 0;
  23597. } else {
  23598. $hb = ($n * $pre_h);
  23599. }
  23600. if ($maxbottomliney > $this->PageBreakTrigger) {
  23601. $hbz = ($this->FontSize * $this->cell_height_ratio);
  23602. } elseif ($this->y < $maxbottomliney) {
  23603. $hbz = ($maxbottomliney - $this->y);
  23604. }
  23605. }
  23606. // Closing tag
  23607. switch($tag['value']) {
  23608. case 'tr': {
  23609. $table_el = $dom[($dom[$key]['parent'])]['parent'];
  23610. if (!isset($parent['endy'])) {
  23611. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  23612. $parent['endy'] = $this->y;
  23613. }
  23614. if (!isset($parent['endpage'])) {
  23615. $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
  23616. $parent['endpage'] = $this->page;
  23617. }
  23618. if (!isset($parent['endcolumn'])) {
  23619. $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
  23620. $parent['endcolumn'] = $this->current_column;
  23621. }
  23622. // update row-spanned cells
  23623. if (isset($dom[$table_el]['rowspans'])) {
  23624. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  23625. $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
  23626. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  23627. if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
  23628. $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
  23629. } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
  23630. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  23631. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  23632. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  23633. }
  23634. }
  23635. }
  23636. // report new endy and endpage to the rowspanned cells
  23637. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  23638. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  23639. $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
  23640. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  23641. $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
  23642. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  23643. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
  23644. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  23645. }
  23646. }
  23647. // update remaining rowspanned cells
  23648. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  23649. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  23650. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
  23651. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
  23652. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
  23653. }
  23654. }
  23655. }
  23656. $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
  23657. if ($this->num_columns > 1) {
  23658. $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
  23659. }
  23660. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  23661. if (isset($dom[$table_el]['attribute']['cellspacing'])) {
  23662. $this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
  23663. } elseif (isset($dom[$table_el]['border-spacing'])) {
  23664. $this->y += $dom[$table_el]['border-spacing']['V'];
  23665. }
  23666. $this->Ln(0, $cell);
  23667. if ($this->current_column == $parent['startcolumn']) {
  23668. $this->x = $parent['startx'];
  23669. }
  23670. // account for booklet mode
  23671. if ($this->page > $parent['startpage']) {
  23672. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
  23673. $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
  23674. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
  23675. $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
  23676. }
  23677. }
  23678. break;
  23679. }
  23680. case 'tablehead':
  23681. // closing tag used for the thead part
  23682. $in_table_head = true;
  23683. $this->inthead = false;
  23684. case 'table': {
  23685. $table_el = $parent;
  23686. // set default border
  23687. if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
  23688. // set default border
  23689. $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
  23690. } else {
  23691. $border = 0;
  23692. }
  23693. $default_border = $border;
  23694. // fix bottom line alignment of last line before page break
  23695. foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
  23696. // update row-spanned cells
  23697. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  23698. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  23699. if ($trwsp['trid'] == $trkey) {
  23700. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
  23701. }
  23702. if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
  23703. $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
  23704. }
  23705. }
  23706. }
  23707. if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
  23708. $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
  23709. $dom[$prevtrkey]['endy'] = $pgendy;
  23710. // update row-spanned cells
  23711. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  23712. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  23713. if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] > 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
  23714. $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
  23715. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
  23716. }
  23717. }
  23718. }
  23719. }
  23720. $prevtrkey = $trkey;
  23721. $table_el = $dom[($dom[$key]['parent'])];
  23722. }
  23723. // for each row
  23724. if (count($table_el['trids']) > 0) {
  23725. unset($xmax);
  23726. }
  23727. foreach ($table_el['trids'] as $j => $trkey) {
  23728. $parent = $dom[$trkey];
  23729. if (!isset($xmax)) {
  23730. $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
  23731. }
  23732. // for each cell on the row
  23733. foreach ($parent['cellpos'] as $k => $cellpos) {
  23734. if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
  23735. $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
  23736. $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
  23737. $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
  23738. $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
  23739. $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
  23740. $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
  23741. $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
  23742. } else {
  23743. $endy = $parent['endy'];
  23744. $startpage = $parent['startpage'];
  23745. $endpage = $parent['endpage'];
  23746. $startcolumn = $parent['startcolumn'];
  23747. $endcolumn = $parent['endcolumn'];
  23748. }
  23749. if ($this->num_columns == 0) {
  23750. $this->num_columns = 1;
  23751. }
  23752. if (isset($cellpos['border'])) {
  23753. $border = $cellpos['border'];
  23754. }
  23755. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  23756. $this->SetFillColorArray($cellpos['bgcolor']);
  23757. $fill = true;
  23758. } else {
  23759. $fill = false;
  23760. }
  23761. $x = $cellpos['startx'];
  23762. $y = $parent['starty'];
  23763. $starty = $y;
  23764. $w = abs($cellpos['endx'] - $cellpos['startx']);
  23765. // get border modes
  23766. $border_start = $this->getBorderMode($border, $position='start');
  23767. $border_end = $this->getBorderMode($border, $position='end');
  23768. $border_middle = $this->getBorderMode($border, $position='middle');
  23769. // design borders around HTML cells.
  23770. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  23771. $ccode = '';
  23772. $this->setPage($page);
  23773. if ($this->num_columns < 2) {
  23774. // single-column mode
  23775. $this->x = $x;
  23776. $this->y = $this->tMargin;
  23777. }
  23778. // account for margin changes
  23779. if ($page > $startpage) {
  23780. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  23781. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  23782. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  23783. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  23784. }
  23785. }
  23786. if ($startpage == $endpage) { // single page
  23787. $deltacol = 0;
  23788. $deltath = 0;
  23789. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  23790. $this->selectColumn($column);
  23791. if ($startcolumn == $endcolumn) { // single column
  23792. $cborder = $border;
  23793. $h = $endy - $parent['starty'];
  23794. $this->y = $y;
  23795. $this->x = $x;
  23796. } elseif ($column == $startcolumn) { // first column
  23797. $cborder = $border_start;
  23798. $this->y = $starty;
  23799. $this->x = $x;
  23800. $h = $this->h - $this->y - $this->bMargin;
  23801. if ($this->rtl) {
  23802. $deltacol = $this->x + $this->rMargin - $this->w;
  23803. } else {
  23804. $deltacol = $this->x - $this->lMargin;
  23805. }
  23806. } elseif ($column == $endcolumn) { // end column
  23807. $cborder = $border_end;
  23808. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23809. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23810. }
  23811. $this->x += $deltacol;
  23812. $h = $endy - $this->y;
  23813. } else { // middle column
  23814. $cborder = $border_middle;
  23815. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23816. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23817. }
  23818. $this->x += $deltacol;
  23819. $h = $this->h - $this->y - $this->bMargin;
  23820. }
  23821. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23822. } // end for each column
  23823. } elseif ($page == $startpage) { // first page
  23824. $deltacol = 0;
  23825. $deltath = 0;
  23826. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  23827. $this->selectColumn($column);
  23828. if ($column == $startcolumn) { // first column
  23829. $cborder = $border_start;
  23830. $this->y = $starty;
  23831. $this->x = $x;
  23832. $h = $this->h - $this->y - $this->bMargin;
  23833. if ($this->rtl) {
  23834. $deltacol = $this->x + $this->rMargin - $this->w;
  23835. } else {
  23836. $deltacol = $this->x - $this->lMargin;
  23837. }
  23838. } else { // middle column
  23839. $cborder = $border_middle;
  23840. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23841. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23842. }
  23843. $this->x += $deltacol;
  23844. $h = $this->h - $this->y - $this->bMargin;
  23845. }
  23846. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23847. } // end for each column
  23848. } elseif ($page == $endpage) { // last page
  23849. $deltacol = 0;
  23850. $deltath = 0;
  23851. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  23852. $this->selectColumn($column);
  23853. if ($column == $endcolumn) { // end column
  23854. $cborder = $border_end;
  23855. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23856. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23857. }
  23858. $this->x += $deltacol;
  23859. $h = $endy - $this->y;
  23860. } else { // middle column
  23861. $cborder = $border_middle;
  23862. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23863. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23864. }
  23865. $this->x += $deltacol;
  23866. $h = $this->h - $this->y - $this->bMargin;
  23867. }
  23868. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23869. } // end for each column
  23870. } else { // middle page
  23871. $deltacol = 0;
  23872. $deltath = 0;
  23873. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  23874. $this->selectColumn($column);
  23875. $cborder = $border_middle;
  23876. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  23877. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  23878. }
  23879. $this->x += $deltacol;
  23880. $h = $this->h - $this->y - $this->bMargin;
  23881. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  23882. } // end for each column
  23883. }
  23884. if ($cborder OR $fill) {
  23885. $offsetlen = strlen($ccode);
  23886. // draw border and fill
  23887. if ($this->inxobj) {
  23888. // we are inside an XObject template
  23889. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  23890. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  23891. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  23892. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  23893. } else {
  23894. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  23895. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  23896. }
  23897. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  23898. $pstart = substr($pagebuff, 0, $pagemark);
  23899. $pend = substr($pagebuff, $pagemark);
  23900. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  23901. } else {
  23902. // draw border and fill
  23903. if (end($this->transfmrk[$this->page]) !== false) {
  23904. $pagemarkkey = key($this->transfmrk[$this->page]);
  23905. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  23906. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  23907. } elseif ($this->InFooter) {
  23908. $pagemark = $this->footerpos[$this->page];
  23909. $this->footerpos[$this->page] += $offsetlen;
  23910. } else {
  23911. $pagemark = $this->intmrk[$this->page];
  23912. $this->intmrk[$this->page] += $offsetlen;
  23913. }
  23914. $pagebuff = $this->getPageBuffer($this->page);
  23915. $pstart = substr($pagebuff, 0, $pagemark);
  23916. $pend = substr($pagebuff, $pagemark);
  23917. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  23918. }
  23919. }
  23920. } // end for each page
  23921. // restore default border
  23922. $border = $default_border;
  23923. } // end for each cell on the row
  23924. if (isset($table_el['attribute']['cellspacing'])) {
  23925. $this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
  23926. } elseif (isset($table_el['border-spacing'])) {
  23927. $this->y += $table_el['border-spacing']['V'];
  23928. }
  23929. $this->Ln(0, $cell);
  23930. $this->x = $parent['startx'];
  23931. if ($endpage > $startpage) {
  23932. if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
  23933. $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
  23934. } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
  23935. $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
  23936. }
  23937. }
  23938. }
  23939. if (!$in_table_head) { // we are not inside a thead section
  23940. $this->cell_padding = $table_el['old_cell_padding'];
  23941. // reset row height
  23942. $this->resetLastH();
  23943. if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
  23944. $plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
  23945. if (($plendiff > 0) AND ($plendiff < 60)) {
  23946. $pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
  23947. if (substr($pagediff, 0, 5) == 'BT /F') {
  23948. // the difference is only a font setting
  23949. $plendiff = 0;
  23950. }
  23951. }
  23952. if ($plendiff == 0) {
  23953. // remove last blank page
  23954. $this->deletePage($this->numpages);
  23955. }
  23956. }
  23957. if (isset($this->theadMargins['top'])) {
  23958. // restore top margin
  23959. $this->tMargin = $this->theadMargins['top'];
  23960. }
  23961. if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
  23962. // reset main table header
  23963. $this->thead = '';
  23964. $this->theadMargins = array();
  23965. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  23966. }
  23967. }
  23968. $parent = $table_el;
  23969. break;
  23970. }
  23971. case 'a': {
  23972. $this->HREF = '';
  23973. break;
  23974. }
  23975. case 'sup': {
  23976. $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
  23977. break;
  23978. }
  23979. case 'sub': {
  23980. $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
  23981. break;
  23982. }
  23983. case 'div': {
  23984. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23985. break;
  23986. }
  23987. case 'blockquote': {
  23988. if ($this->rtl) {
  23989. $this->rMargin -= $this->listindent;
  23990. } else {
  23991. $this->lMargin -= $this->listindent;
  23992. }
  23993. --$this->listindentlevel;
  23994. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23995. break;
  23996. }
  23997. case 'p': {
  23998. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  23999. break;
  24000. }
  24001. case 'pre': {
  24002. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  24003. $this->premode = false;
  24004. break;
  24005. }
  24006. case 'dl': {
  24007. --$this->listnum;
  24008. if ($this->listnum <= 0) {
  24009. $this->listnum = 0;
  24010. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  24011. } else {
  24012. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  24013. }
  24014. $this->resetLastH();
  24015. break;
  24016. }
  24017. case 'dt': {
  24018. $this->lispacer = '';
  24019. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  24020. break;
  24021. }
  24022. case 'dd': {
  24023. $this->lispacer = '';
  24024. if ($this->rtl) {
  24025. $this->rMargin -= $this->listindent;
  24026. } else {
  24027. $this->lMargin -= $this->listindent;
  24028. }
  24029. --$this->listindentlevel;
  24030. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  24031. break;
  24032. }
  24033. case 'ul':
  24034. case 'ol': {
  24035. --$this->listnum;
  24036. $this->lispacer = '';
  24037. if ($this->rtl) {
  24038. $this->rMargin -= $this->listindent;
  24039. } else {
  24040. $this->lMargin -= $this->listindent;
  24041. }
  24042. --$this->listindentlevel;
  24043. if ($this->listnum <= 0) {
  24044. $this->listnum = 0;
  24045. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  24046. } else {
  24047. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  24048. }
  24049. $this->resetLastH();
  24050. break;
  24051. }
  24052. case 'li': {
  24053. $this->lispacer = '';
  24054. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  24055. break;
  24056. }
  24057. case 'h1':
  24058. case 'h2':
  24059. case 'h3':
  24060. case 'h4':
  24061. case 'h5':
  24062. case 'h6': {
  24063. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  24064. break;
  24065. }
  24066. // Form fields (since 4.8.000 - 2009-09-07)
  24067. case 'form': {
  24068. $this->form_action = '';
  24069. $this->form_enctype = 'application/x-www-form-urlencoded';
  24070. break;
  24071. }
  24072. default : {
  24073. break;
  24074. }
  24075. }
  24076. // draw border and background (if any)
  24077. $this->drawHTMLTagBorder($parent, $xmax);
  24078. if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
  24079. $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
  24080. // check for pagebreak
  24081. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  24082. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  24083. $this->checkPageBreak($this->PageBreakTrigger + 1);
  24084. }
  24085. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  24086. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  24087. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  24088. $this->checkPageBreak($this->PageBreakTrigger + 1);
  24089. }
  24090. }
  24091. $this->tmprtl = false;
  24092. return $dom;
  24093. }
  24094. /**
  24095. * Add vertical spaces if needed.
  24096. * @param $hbz (string) Distance between current y and line bottom.
  24097. * @param $hb (string) The height of the break.
  24098. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  24099. * @param $firsttag (boolean) set to true when the tag is the first.
  24100. * @param $lasttag (boolean) set to true when the tag is the last.
  24101. * @protected
  24102. */
  24103. protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
  24104. if ($firsttag) {
  24105. $this->Ln(0, $cell);
  24106. $this->htmlvspace = 0;
  24107. return;
  24108. }
  24109. if ($lasttag) {
  24110. $this->Ln($hbz, $cell);
  24111. $this->htmlvspace = 0;
  24112. return;
  24113. }
  24114. if ($hb < $this->htmlvspace) {
  24115. $hd = 0;
  24116. } else {
  24117. $hd = $hb - $this->htmlvspace;
  24118. $this->htmlvspace = $hb;
  24119. }
  24120. $this->Ln(($hbz + $hd), $cell);
  24121. }
  24122. /**
  24123. * Return the starting coordinates to draw an html border
  24124. * @return array containing top-left border coordinates
  24125. * @protected
  24126. * @since 5.7.000 (2010-08-03)
  24127. */
  24128. protected function getBorderStartPosition() {
  24129. if ($this->rtl) {
  24130. $xmax = $this->lMargin;
  24131. } else {
  24132. $xmax = $this->w - $this->rMargin;
  24133. }
  24134. return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
  24135. }
  24136. /**
  24137. * Draw an HTML block border and fill
  24138. * @param $tag (array) array of tag properties.
  24139. * @param $xmax (int) end X coordinate for border.
  24140. * @protected
  24141. * @since 5.7.000 (2010-08-03)
  24142. */
  24143. protected function drawHTMLTagBorder($tag, $xmax) {
  24144. if (!isset($tag['borderposition'])) {
  24145. // nothing to draw
  24146. return;
  24147. }
  24148. $prev_x = $this->x;
  24149. $prev_y = $this->y;
  24150. $prev_lasth = $this->lasth;
  24151. $border = 0;
  24152. $fill = false;
  24153. $this->lasth = 0;
  24154. if (isset($tag['border']) AND !empty($tag['border'])) {
  24155. // get border style
  24156. $border = $tag['border'];
  24157. if (!$this->empty_string($this->thead) AND (!$this->inthead)) {
  24158. // border for table header
  24159. $border = $this->getBorderMode($border, $position='middle');
  24160. }
  24161. }
  24162. if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
  24163. // get background color
  24164. $old_bgcolor = $this->bgcolor;
  24165. $this->SetFillColorArray($tag['bgcolor']);
  24166. $fill = true;
  24167. }
  24168. if (!$border AND !$fill) {
  24169. // nothing to draw
  24170. return;
  24171. }
  24172. if (isset($tag['attribute']['cellspacing'])) {
  24173. $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  24174. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  24175. } elseif (isset($tag['border-spacing'])) {
  24176. $cellspacing = $tag['border-spacing'];
  24177. } else {
  24178. $cellspacing = array('H' => 0, 'V' => 0);
  24179. }
  24180. if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
  24181. // draw the border externally respect the sqare edge.
  24182. $border['mode'] = 'ext';
  24183. }
  24184. if ($this->rtl) {
  24185. if ($xmax >= $tag['borderposition']['x']) {
  24186. $xmax = $tag['borderposition']['xmax'];
  24187. }
  24188. $w = ($tag['borderposition']['x'] - $xmax);
  24189. } else {
  24190. if ($xmax <= $tag['borderposition']['x']) {
  24191. $xmax = $tag['borderposition']['xmax'];
  24192. }
  24193. $w = ($xmax - $tag['borderposition']['x']);
  24194. }
  24195. if ($w <= 0) {
  24196. return;
  24197. }
  24198. $w += $cellspacing['H'];
  24199. $startpage = $tag['borderposition']['page'];
  24200. $startcolumn = $tag['borderposition']['column'];
  24201. $x = $tag['borderposition']['x'];
  24202. $y = $tag['borderposition']['y'];
  24203. $endpage = $this->page;
  24204. $starty = $tag['borderposition']['y'] - $cellspacing['V'];
  24205. $currentY = $this->y;
  24206. $this->x = $x;
  24207. // get latest column
  24208. $endcolumn = $this->current_column;
  24209. if ($this->num_columns == 0) {
  24210. $this->num_columns = 1;
  24211. }
  24212. // get border modes
  24213. $border_start = $this->getBorderMode($border, $position='start');
  24214. $border_end = $this->getBorderMode($border, $position='end');
  24215. $border_middle = $this->getBorderMode($border, $position='middle');
  24216. // temporary disable page regions
  24217. $temp_page_regions = $this->page_regions;
  24218. $this->page_regions = array();
  24219. // design borders around HTML cells.
  24220. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  24221. $ccode = '';
  24222. $this->setPage($page);
  24223. if ($this->num_columns < 2) {
  24224. // single-column mode
  24225. $this->x = $x;
  24226. $this->y = $this->tMargin;
  24227. }
  24228. // account for margin changes
  24229. if ($page > $startpage) {
  24230. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  24231. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  24232. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  24233. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  24234. }
  24235. }
  24236. if ($startpage == $endpage) {
  24237. // single page
  24238. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  24239. $this->selectColumn($column);
  24240. if ($startcolumn == $endcolumn) { // single column
  24241. $cborder = $border;
  24242. $h = ($currentY - $y) + $cellspacing['V'];
  24243. $this->y = $starty;
  24244. } elseif ($column == $startcolumn) { // first column
  24245. $cborder = $border_start;
  24246. $this->y = $starty;
  24247. $h = $this->h - $this->y - $this->bMargin;
  24248. } elseif ($column == $endcolumn) { // end column
  24249. $cborder = $border_end;
  24250. $h = $currentY - $this->y;
  24251. } else { // middle column
  24252. $cborder = $border_middle;
  24253. $h = $this->h - $this->y - $this->bMargin;
  24254. }
  24255. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  24256. } // end for each column
  24257. } elseif ($page == $startpage) { // first page
  24258. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  24259. $this->selectColumn($column);
  24260. if ($column == $startcolumn) { // first column
  24261. $cborder = $border_start;
  24262. $this->y = $starty;
  24263. $h = $this->h - $this->y - $this->bMargin;
  24264. } else { // middle column
  24265. $cborder = $border_middle;
  24266. $h = $this->h - $this->y - $this->bMargin;
  24267. }
  24268. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  24269. } // end for each column
  24270. } elseif ($page == $endpage) { // last page
  24271. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  24272. $this->selectColumn($column);
  24273. if ($column == $endcolumn) {
  24274. // end column
  24275. $cborder = $border_end;
  24276. $h = $currentY - $this->y;
  24277. } else {
  24278. // middle column
  24279. $cborder = $border_middle;
  24280. $h = $this->h - $this->y - $this->bMargin;
  24281. }
  24282. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  24283. } // end for each column
  24284. } else { // middle page
  24285. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  24286. $this->selectColumn($column);
  24287. $cborder = $border_middle;
  24288. $h = $this->h - $this->y - $this->bMargin;
  24289. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  24290. } // end for each column
  24291. }
  24292. if ($cborder OR $fill) {
  24293. $offsetlen = strlen($ccode);
  24294. // draw border and fill
  24295. if ($this->inxobj) {
  24296. // we are inside an XObject template
  24297. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  24298. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  24299. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  24300. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  24301. } else {
  24302. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  24303. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  24304. }
  24305. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  24306. $pstart = substr($pagebuff, 0, $pagemark);
  24307. $pend = substr($pagebuff, $pagemark);
  24308. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  24309. } else {
  24310. if (end($this->transfmrk[$this->page]) !== false) {
  24311. $pagemarkkey = key($this->transfmrk[$this->page]);
  24312. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  24313. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  24314. } elseif ($this->InFooter) {
  24315. $pagemark = $this->footerpos[$this->page];
  24316. $this->footerpos[$this->page] += $offsetlen;
  24317. } else {
  24318. $pagemark = $this->intmrk[$this->page];
  24319. $this->intmrk[$this->page] += $offsetlen;
  24320. }
  24321. $pagebuff = $this->getPageBuffer($this->page);
  24322. $pstart = substr($pagebuff, 0, $this->bordermrk[$this->page]);
  24323. $pend = substr($pagebuff, $this->bordermrk[$this->page]);
  24324. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  24325. $this->bordermrk[$this->page] += $offsetlen;
  24326. $this->cntmrk[$this->page] += $offsetlen;
  24327. }
  24328. }
  24329. } // end for each page
  24330. // restore page regions
  24331. $this->page_regions = $temp_page_regions;
  24332. if (isset($old_bgcolor)) {
  24333. // restore background color
  24334. $this->SetFillColorArray($old_bgcolor);
  24335. }
  24336. // restore pointer position
  24337. $this->x = $prev_x;
  24338. $this->y = $prev_y;
  24339. $this->lasth = $prev_lasth;
  24340. }
  24341. /**
  24342. * Set the default bullet to be used as LI bullet symbol
  24343. * @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')
  24344. * @public
  24345. * @since 4.0.028 (2008-09-26)
  24346. */
  24347. public function setLIsymbol($symbol='!') {
  24348. // check for custom image symbol
  24349. if (substr($symbol, 0, 4) == 'img|') {
  24350. $this->lisymbol = $symbol;
  24351. return;
  24352. }
  24353. $symbol = strtolower($symbol);
  24354. switch ($symbol) {
  24355. case '!' :
  24356. case '#' :
  24357. case 'disc' :
  24358. case 'circle' :
  24359. case 'square' :
  24360. case '1':
  24361. case 'decimal':
  24362. case 'decimal-leading-zero':
  24363. case 'i':
  24364. case 'lower-roman':
  24365. case 'I':
  24366. case 'upper-roman':
  24367. case 'a':
  24368. case 'lower-alpha':
  24369. case 'lower-latin':
  24370. case 'A':
  24371. case 'upper-alpha':
  24372. case 'upper-latin':
  24373. case 'lower-greek': {
  24374. $this->lisymbol = $symbol;
  24375. break;
  24376. }
  24377. default : {
  24378. $this->lisymbol = '';
  24379. }
  24380. }
  24381. }
  24382. /**
  24383. * Set the booklet mode for double-sided pages.
  24384. * @param $booklet (boolean) true set the booklet mode on, false otherwise.
  24385. * @param $inner (float) Inner page margin.
  24386. * @param $outer (float) Outer page margin.
  24387. * @public
  24388. * @since 4.2.000 (2008-10-29)
  24389. */
  24390. public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
  24391. $this->booklet = $booklet;
  24392. if ($inner >= 0) {
  24393. $this->lMargin = $inner;
  24394. }
  24395. if ($outer >= 0) {
  24396. $this->rMargin = $outer;
  24397. }
  24398. }
  24399. /**
  24400. * Swap the left and right margins.
  24401. * @param $reverse (boolean) if true swap left and right margins.
  24402. * @protected
  24403. * @since 4.2.000 (2008-10-29)
  24404. */
  24405. protected function swapMargins($reverse=true) {
  24406. if ($reverse) {
  24407. // swap left and right margins
  24408. $mtemp = $this->original_lMargin;
  24409. $this->original_lMargin = $this->original_rMargin;
  24410. $this->original_rMargin = $mtemp;
  24411. $deltam = $this->original_lMargin - $this->original_rMargin;
  24412. $this->lMargin += $deltam;
  24413. $this->rMargin -= $deltam;
  24414. }
  24415. }
  24416. /**
  24417. * Set the vertical spaces for HTML tags.
  24418. * The array must have the following structure (example):
  24419. * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
  24420. * The first array level contains the tag names,
  24421. * the second level contains 0 for opening tags or 1 for closing tags,
  24422. * the third level contains the vertical space unit (h) and the number spaces to add (n).
  24423. * If the h parameter is not specified, default values are used.
  24424. * @param $tagvs (array) array of tags and relative vertical spaces.
  24425. * @public
  24426. * @since 4.2.001 (2008-10-30)
  24427. */
  24428. public function setHtmlVSpace($tagvs) {
  24429. $this->tagvspaces = $tagvs;
  24430. }
  24431. /**
  24432. * Set custom width for list indentation.
  24433. * @param $width (float) width of the indentation. Use negative value to disable it.
  24434. * @public
  24435. * @since 4.2.007 (2008-11-12)
  24436. */
  24437. public function setListIndentWidth($width) {
  24438. return $this->customlistindent = floatval($width);
  24439. }
  24440. /**
  24441. * Set the top/bottom cell sides to be open or closed when the cell cross the page.
  24442. * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
  24443. * @public
  24444. * @since 4.2.010 (2008-11-14)
  24445. */
  24446. public function setOpenCell($isopen) {
  24447. $this->opencell = $isopen;
  24448. }
  24449. /**
  24450. * Set the color and font style for HTML links.
  24451. * @param $color (array) RGB array of colors
  24452. * @param $fontstyle (string) additional font styles to add
  24453. * @public
  24454. * @since 4.4.003 (2008-12-09)
  24455. */
  24456. public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
  24457. $this->htmlLinkColorArray = $color;
  24458. $this->htmlLinkFontStyle = $fontstyle;
  24459. }
  24460. /**
  24461. * Convert HTML string containing value and unit of measure to user's units or points.
  24462. * @param $htmlval (string) string containing values and unit
  24463. * @param $refsize (string) reference value in points
  24464. * @param $defaultunit (string) default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  24465. * @param $points (boolean) if true returns points, otherwise returns value in user's units
  24466. * @return float value in user's unit or point if $points=true
  24467. * @public
  24468. * @since 4.4.004 (2008-12-10)
  24469. */
  24470. public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
  24471. $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
  24472. $retval = 0;
  24473. $value = 0;
  24474. $unit = 'px';
  24475. $k = $this->k;
  24476. if ($points) {
  24477. $k = 1;
  24478. }
  24479. if (in_array($defaultunit, $supportedunits)) {
  24480. $unit = $defaultunit;
  24481. }
  24482. if (is_numeric($htmlval)) {
  24483. $value = floatval($htmlval);
  24484. } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
  24485. $value = floatval($mnum[1]);
  24486. if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
  24487. if (in_array($munit[1], $supportedunits)) {
  24488. $unit = $munit[1];
  24489. }
  24490. }
  24491. }
  24492. switch ($unit) {
  24493. // percentage
  24494. case '%': {
  24495. $retval = (($value * $refsize) / 100);
  24496. break;
  24497. }
  24498. // relative-size
  24499. case 'em': {
  24500. $retval = ($value * $refsize);
  24501. break;
  24502. }
  24503. // height of lower case 'x' (about half the font-size)
  24504. case 'ex': {
  24505. $retval = $value * ($refsize / 2);
  24506. break;
  24507. }
  24508. // absolute-size
  24509. case 'in': {
  24510. $retval = ($value * $this->dpi) / $k;
  24511. break;
  24512. }
  24513. // centimeters
  24514. case 'cm': {
  24515. $retval = ($value / 2.54 * $this->dpi) / $k;
  24516. break;
  24517. }
  24518. // millimeters
  24519. case 'mm': {
  24520. $retval = ($value / 25.4 * $this->dpi) / $k;
  24521. break;
  24522. }
  24523. // one pica is 12 points
  24524. case 'pc': {
  24525. $retval = ($value * 12) / $k;
  24526. break;
  24527. }
  24528. // points
  24529. case 'pt': {
  24530. $retval = $value / $k;
  24531. break;
  24532. }
  24533. // pixels
  24534. case 'px': {
  24535. $retval = $this->pixelsToUnits($value);
  24536. break;
  24537. }
  24538. }
  24539. return $retval;
  24540. }
  24541. /**
  24542. * Returns the Roman representation of an integer number
  24543. * @param $number (int) number to convert
  24544. * @return string roman representation of the specified number
  24545. * @since 4.4.004 (2008-12-10)
  24546. * @public
  24547. */
  24548. public function intToRoman($number) {
  24549. $roman = '';
  24550. while ($number >= 1000) {
  24551. $roman .= 'M';
  24552. $number -= 1000;
  24553. }
  24554. while ($number >= 900) {
  24555. $roman .= 'CM';
  24556. $number -= 900;
  24557. }
  24558. while ($number >= 500) {
  24559. $roman .= 'D';
  24560. $number -= 500;
  24561. }
  24562. while ($number >= 400) {
  24563. $roman .= 'CD';
  24564. $number -= 400;
  24565. }
  24566. while ($number >= 100) {
  24567. $roman .= 'C';
  24568. $number -= 100;
  24569. }
  24570. while ($number >= 90) {
  24571. $roman .= 'XC';
  24572. $number -= 90;
  24573. }
  24574. while ($number >= 50) {
  24575. $roman .= 'L';
  24576. $number -= 50;
  24577. }
  24578. while ($number >= 40) {
  24579. $roman .= 'XL';
  24580. $number -= 40;
  24581. }
  24582. while ($number >= 10) {
  24583. $roman .= 'X';
  24584. $number -= 10;
  24585. }
  24586. while ($number >= 9) {
  24587. $roman .= 'IX';
  24588. $number -= 9;
  24589. }
  24590. while ($number >= 5) {
  24591. $roman .= 'V';
  24592. $number -= 5;
  24593. }
  24594. while ($number >= 4) {
  24595. $roman .= 'IV';
  24596. $number -= 4;
  24597. }
  24598. while ($number >= 1) {
  24599. $roman .= 'I';
  24600. --$number;
  24601. }
  24602. return $roman;
  24603. }
  24604. /**
  24605. * Output an HTML list bullet or ordered item symbol
  24606. * @param $listdepth (int) list nesting level
  24607. * @param $listtype (string) type of list
  24608. * @param $size (float) current font size
  24609. * @protected
  24610. * @since 4.4.004 (2008-12-10)
  24611. */
  24612. protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
  24613. $size /= $this->k;
  24614. $fill = '';
  24615. $bgcolor = $this->bgcolor;
  24616. $color = $this->fgcolor;
  24617. $strokecolor = $this->strokecolor;
  24618. $width = 0;
  24619. $textitem = '';
  24620. $tmpx = $this->x;
  24621. $lspace = $this->GetStringWidth(' ');
  24622. if ($listtype == '^') {
  24623. // special symbol used for avoid justification of rect bullet
  24624. $this->lispacer = '';
  24625. return;
  24626. } elseif ($listtype == '!') {
  24627. // set default list type for unordered list
  24628. $deftypes = array('disc', 'circle', 'square');
  24629. $listtype = $deftypes[($listdepth - 1) % 3];
  24630. } elseif ($listtype == '#') {
  24631. // set default list type for ordered list
  24632. $listtype = 'decimal';
  24633. } elseif (substr($listtype, 0, 4) == 'img|') {
  24634. // custom image type ('img|type|width|height|image.ext')
  24635. $img = explode('|', $listtype);
  24636. $listtype = 'img';
  24637. }
  24638. switch ($listtype) {
  24639. // unordered types
  24640. case 'none': {
  24641. break;
  24642. }
  24643. case 'disc': {
  24644. $r = $size / 6;
  24645. $lspace += (2 * $r);
  24646. if ($this->rtl) {
  24647. $this->x += $lspace;
  24648. } else {
  24649. $this->x -= $lspace;
  24650. }
  24651. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
  24652. break;
  24653. }
  24654. case 'circle': {
  24655. $r = $size / 6;
  24656. $lspace += (2 * $r);
  24657. if ($this->rtl) {
  24658. $this->x += $lspace;
  24659. } else {
  24660. $this->x -= $lspace;
  24661. }
  24662. $prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
  24663. $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
  24664. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
  24665. $this->_out($prev_line_style); // restore line settings
  24666. break;
  24667. }
  24668. case 'square': {
  24669. $l = $size / 3;
  24670. $lspace += $l;
  24671. if ($this->rtl) {;
  24672. $this->x += $lspace;
  24673. } else {
  24674. $this->x -= $lspace;
  24675. }
  24676. $this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
  24677. break;
  24678. }
  24679. case 'img': {
  24680. // 1=>type, 2=>width, 3=>height, 4=>image.ext
  24681. $lspace += $img[2];
  24682. if ($this->rtl) {;
  24683. $this->x += $lspace;
  24684. } else {
  24685. $this->x -= $lspace;
  24686. }
  24687. $imgtype = strtolower($img[1]);
  24688. $prev_y = $this->y;
  24689. switch ($imgtype) {
  24690. case 'svg': {
  24691. $this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
  24692. break;
  24693. }
  24694. case 'ai':
  24695. case 'eps': {
  24696. $this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
  24697. break;
  24698. }
  24699. default: {
  24700. $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);
  24701. break;
  24702. }
  24703. }
  24704. $this->y = $prev_y;
  24705. break;
  24706. }
  24707. // ordered types
  24708. // $this->listcount[$this->listnum];
  24709. // $textitem
  24710. case '1':
  24711. case 'decimal': {
  24712. $textitem = $this->listcount[$this->listnum];
  24713. break;
  24714. }
  24715. case 'decimal-leading-zero': {
  24716. $textitem = sprintf('%02d', $this->listcount[$this->listnum]);
  24717. break;
  24718. }
  24719. case 'i':
  24720. case 'lower-roman': {
  24721. $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
  24722. break;
  24723. }
  24724. case 'I':
  24725. case 'upper-roman': {
  24726. $textitem = $this->intToRoman($this->listcount[$this->listnum]);
  24727. break;
  24728. }
  24729. case 'a':
  24730. case 'lower-alpha':
  24731. case 'lower-latin': {
  24732. $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
  24733. break;
  24734. }
  24735. case 'A':
  24736. case 'upper-alpha':
  24737. case 'upper-latin': {
  24738. $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
  24739. break;
  24740. }
  24741. case 'lower-greek': {
  24742. $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
  24743. break;
  24744. }
  24745. /*
  24746. // Types to be implemented (special handling)
  24747. case 'hebrew': {
  24748. break;
  24749. }
  24750. case 'armenian': {
  24751. break;
  24752. }
  24753. case 'georgian': {
  24754. break;
  24755. }
  24756. case 'cjk-ideographic': {
  24757. break;
  24758. }
  24759. case 'hiragana': {
  24760. break;
  24761. }
  24762. case 'katakana': {
  24763. break;
  24764. }
  24765. case 'hiragana-iroha': {
  24766. break;
  24767. }
  24768. case 'katakana-iroha': {
  24769. break;
  24770. }
  24771. */
  24772. default: {
  24773. $textitem = $this->listcount[$this->listnum];
  24774. }
  24775. }
  24776. if (!$this->empty_string($textitem)) {
  24777. // Check whether we need a new page or new column
  24778. $prev_y = $this->y;
  24779. $h = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
  24780. if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
  24781. $tmpx = $this->x;
  24782. }
  24783. // print ordered item
  24784. if ($this->rtl) {
  24785. $textitem = '.'.$textitem;
  24786. } else {
  24787. $textitem = $textitem.'.';
  24788. }
  24789. $lspace += $this->GetStringWidth($textitem);
  24790. if ($this->rtl) {
  24791. $this->x += $lspace;
  24792. } else {
  24793. $this->x -= $lspace;
  24794. }
  24795. $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
  24796. }
  24797. $this->x = $tmpx;
  24798. $this->lispacer = '^';
  24799. // restore colors
  24800. $this->SetFillColorArray($bgcolor);
  24801. $this->SetDrawColorArray($strokecolor);
  24802. $this->SettextColorArray($color);
  24803. }
  24804. /**
  24805. * Returns current graphic variables as array.
  24806. * @return array of graphic variables
  24807. * @protected
  24808. * @since 4.2.010 (2008-11-14)
  24809. */
  24810. protected function getGraphicVars() {
  24811. $grapvars = array(
  24812. 'FontFamily' => $this->FontFamily,
  24813. 'FontStyle' => $this->FontStyle,
  24814. 'FontSizePt' => $this->FontSizePt,
  24815. 'rMargin' => $this->rMargin,
  24816. 'lMargin' => $this->lMargin,
  24817. 'cell_padding' => $this->cell_padding,
  24818. 'cell_margin' => $this->cell_margin,
  24819. 'LineWidth' => $this->LineWidth,
  24820. 'linestyleWidth' => $this->linestyleWidth,
  24821. 'linestyleCap' => $this->linestyleCap,
  24822. 'linestyleJoin' => $this->linestyleJoin,
  24823. 'linestyleDash' => $this->linestyleDash,
  24824. 'textrendermode' => $this->textrendermode,
  24825. 'textstrokewidth' => $this->textstrokewidth,
  24826. 'DrawColor' => $this->DrawColor,
  24827. 'FillColor' => $this->FillColor,
  24828. 'TextColor' => $this->TextColor,
  24829. 'ColorFlag' => $this->ColorFlag,
  24830. 'bgcolor' => $this->bgcolor,
  24831. 'fgcolor' => $this->fgcolor,
  24832. 'htmlvspace' => $this->htmlvspace,
  24833. 'listindent' => $this->listindent,
  24834. 'listindentlevel' => $this->listindentlevel,
  24835. 'listnum' => $this->listnum,
  24836. 'listordered' => $this->listordered,
  24837. 'listcount' => $this->listcount,
  24838. 'lispacer' => $this->lispacer,
  24839. 'cell_height_ratio' => $this->cell_height_ratio,
  24840. 'font_stretching' => $this->font_stretching,
  24841. 'font_spacing' => $this->font_spacing,
  24842. 'alpha' => $this->alpha,
  24843. // extended
  24844. 'lasth' => $this->lasth,
  24845. 'tMargin' => $this->tMargin,
  24846. 'bMargin' => $this->bMargin,
  24847. 'AutoPageBreak' => $this->AutoPageBreak,
  24848. 'PageBreakTrigger' => $this->PageBreakTrigger,
  24849. 'x' => $this->x,
  24850. 'y' => $this->y,
  24851. 'w' => $this->w,
  24852. 'h' => $this->h,
  24853. 'wPt' => $this->wPt,
  24854. 'hPt' => $this->hPt,
  24855. 'fwPt' => $this->fwPt,
  24856. 'fhPt' => $this->fhPt,
  24857. 'page' => $this->page,
  24858. 'current_column' => $this->current_column,
  24859. 'num_columns' => $this->num_columns
  24860. );
  24861. return $grapvars;
  24862. }
  24863. /**
  24864. * Set graphic variables.
  24865. * @param $gvars (array) array of graphic variablesto restore
  24866. * @param $extended (boolean) if true restore extended graphic variables
  24867. * @protected
  24868. * @since 4.2.010 (2008-11-14)
  24869. */
  24870. protected function setGraphicVars($gvars, $extended=false) {
  24871. $this->FontFamily = $gvars['FontFamily'];
  24872. $this->FontStyle = $gvars['FontStyle'];
  24873. $this->FontSizePt = $gvars['FontSizePt'];
  24874. $this->rMargin = $gvars['rMargin'];
  24875. $this->lMargin = $gvars['lMargin'];
  24876. $this->cell_padding = $gvars['cell_padding'];
  24877. $this->cell_margin = $gvars['cell_margin'];
  24878. $this->LineWidth = $gvars['LineWidth'];
  24879. $this->linestyleWidth = $gvars['linestyleWidth'];
  24880. $this->linestyleCap = $gvars['linestyleCap'];
  24881. $this->linestyleJoin = $gvars['linestyleJoin'];
  24882. $this->linestyleDash = $gvars['linestyleDash'];
  24883. $this->textrendermode = $gvars['textrendermode'];
  24884. $this->textstrokewidth = $gvars['textstrokewidth'];
  24885. $this->DrawColor = $gvars['DrawColor'];
  24886. $this->FillColor = $gvars['FillColor'];
  24887. $this->TextColor = $gvars['TextColor'];
  24888. $this->ColorFlag = $gvars['ColorFlag'];
  24889. $this->bgcolor = $gvars['bgcolor'];
  24890. $this->fgcolor = $gvars['fgcolor'];
  24891. $this->htmlvspace = $gvars['htmlvspace'];
  24892. $this->listindent = $gvars['listindent'];
  24893. $this->listindentlevel = $gvars['listindentlevel'];
  24894. $this->listnum = $gvars['listnum'];
  24895. $this->listordered = $gvars['listordered'];
  24896. $this->listcount = $gvars['listcount'];
  24897. $this->lispacer = $gvars['lispacer'];
  24898. $this->cell_height_ratio = $gvars['cell_height_ratio'];
  24899. $this->font_stretching = $gvars['font_stretching'];
  24900. $this->font_spacing = $gvars['font_spacing'];
  24901. $this->alpha = $gvars['alpha'];
  24902. if ($extended) {
  24903. // restore extended values
  24904. $this->lasth = $gvars['lasth'];
  24905. $this->tMargin = $gvars['tMargin'];
  24906. $this->bMargin = $gvars['bMargin'];
  24907. $this->AutoPageBreak = $gvars['AutoPageBreak'];
  24908. $this->PageBreakTrigger = $gvars['PageBreakTrigger'];
  24909. $this->x = $gvars['x'];
  24910. $this->y = $gvars['y'];
  24911. $this->w = $gvars['w'];
  24912. $this->h = $gvars['h'];
  24913. $this->wPt = $gvars['wPt'];
  24914. $this->hPt = $gvars['hPt'];
  24915. $this->fwPt = $gvars['fwPt'];
  24916. $this->fhPt = $gvars['fhPt'];
  24917. $this->page = $gvars['page'];
  24918. $this->current_column = $gvars['current_column'];
  24919. $this->num_columns = $gvars['num_columns'];
  24920. }
  24921. $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
  24922. if (!$this->empty_string($this->FontFamily)) {
  24923. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  24924. }
  24925. }
  24926. /**
  24927. * Returns a temporary filename for caching object on filesystem.
  24928. * @param $name (string) prefix to add to filename
  24929. * @return string filename.
  24930. * @since 4.5.000 (2008-12-31)
  24931. * @protected
  24932. */
  24933. protected function getObjFilename($name) {
  24934. return tempnam(K_PATH_CACHE, $name.'_');
  24935. }
  24936. /**
  24937. * Writes data to a temporary file on filesystem.
  24938. * @param $filename (string) file name
  24939. * @param $data (mixed) data to write on file
  24940. * @param $append (boolean) if true append data, false replace.
  24941. * @since 4.5.000 (2008-12-31)
  24942. * @protected
  24943. */
  24944. protected function writeDiskCache($filename, $data, $append=false) {
  24945. if ($append) {
  24946. $fmode = 'ab+';
  24947. } else {
  24948. $fmode = 'wb+';
  24949. }
  24950. $f = @fopen($filename, $fmode);
  24951. if (!$f) {
  24952. $this->Error('Unable to write cache file: '.$filename);
  24953. } else {
  24954. fwrite($f, $data);
  24955. fclose($f);
  24956. }
  24957. // update file length (needed for transactions)
  24958. if (!isset($this->cache_file_length['_'.$filename])) {
  24959. $this->cache_file_length['_'.$filename] = strlen($data);
  24960. } else {
  24961. $this->cache_file_length['_'.$filename] += strlen($data);
  24962. }
  24963. }
  24964. /**
  24965. * Read data from a temporary file on filesystem.
  24966. * @param $filename (string) file name
  24967. * @return mixed retrieved data
  24968. * @since 4.5.000 (2008-12-31)
  24969. * @protected
  24970. */
  24971. protected function readDiskCache($filename) {
  24972. return file_get_contents($filename);
  24973. }
  24974. /**
  24975. * Set buffer content (always append data).
  24976. * @param $data (string) data
  24977. * @protected
  24978. * @since 4.5.000 (2009-01-02)
  24979. */
  24980. protected function setBuffer($data) {
  24981. $this->bufferlen += strlen($data);
  24982. if ($this->diskcache) {
  24983. if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
  24984. $this->buffer = $this->getObjFilename('buffer');
  24985. }
  24986. $this->writeDiskCache($this->buffer, $data, true);
  24987. } else {
  24988. $this->buffer .= $data;
  24989. }
  24990. }
  24991. /**
  24992. * Replace the buffer content
  24993. * @param $data (string) data
  24994. * @protected
  24995. * @since 5.5.000 (2010-06-22)
  24996. */
  24997. protected function replaceBuffer($data) {
  24998. $this->bufferlen = strlen($data);
  24999. if ($this->diskcache) {
  25000. if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
  25001. $this->buffer = $this->getObjFilename('buffer');
  25002. }
  25003. $this->writeDiskCache($this->buffer, $data, false);
  25004. } else {
  25005. $this->buffer = $data;
  25006. }
  25007. }
  25008. /**
  25009. * Get buffer content.
  25010. * @return string buffer content
  25011. * @protected
  25012. * @since 4.5.000 (2009-01-02)
  25013. */
  25014. protected function getBuffer() {
  25015. if ($this->diskcache) {
  25016. return $this->readDiskCache($this->buffer);
  25017. } else {
  25018. return $this->buffer;
  25019. }
  25020. }
  25021. /**
  25022. * Set page buffer content.
  25023. * @param $page (int) page number
  25024. * @param $data (string) page data
  25025. * @param $append (boolean) if true append data, false replace.
  25026. * @protected
  25027. * @since 4.5.000 (2008-12-31)
  25028. */
  25029. protected function setPageBuffer($page, $data, $append=false) {
  25030. if ($this->diskcache) {
  25031. if (!isset($this->pages[$page])) {
  25032. $this->pages[$page] = $this->getObjFilename('page'.$page);
  25033. }
  25034. $this->writeDiskCache($this->pages[$page], $data, $append);
  25035. } else {
  25036. if ($append) {
  25037. $this->pages[$page] .= $data;
  25038. } else {
  25039. $this->pages[$page] = $data;
  25040. }
  25041. }
  25042. if ($append AND isset($this->pagelen[$page])) {
  25043. $this->pagelen[$page] += strlen($data);
  25044. } else {
  25045. $this->pagelen[$page] = strlen($data);
  25046. }
  25047. }
  25048. /**
  25049. * Get page buffer content.
  25050. * @param $page (int) page number
  25051. * @return string page buffer content or false in case of error
  25052. * @protected
  25053. * @since 4.5.000 (2008-12-31)
  25054. */
  25055. protected function getPageBuffer($page) {
  25056. if ($this->diskcache) {
  25057. return $this->readDiskCache($this->pages[$page]);
  25058. } elseif (isset($this->pages[$page])) {
  25059. return $this->pages[$page];
  25060. }
  25061. return false;
  25062. }
  25063. /**
  25064. * Set image buffer content.
  25065. * @param $image (string) image key
  25066. * @param $data (array) image data
  25067. * @protected
  25068. * @since 4.5.000 (2008-12-31)
  25069. */
  25070. protected function setImageBuffer($image, $data) {
  25071. if ($this->diskcache) {
  25072. if (!isset($this->images[$image])) {
  25073. $this->images[$image] = $this->getObjFilename('image'.$image);
  25074. }
  25075. $this->writeDiskCache($this->images[$image], serialize($data));
  25076. } else {
  25077. $this->images[$image] = $data;
  25078. }
  25079. if (!in_array($image, $this->imagekeys)) {
  25080. $this->imagekeys[] = $image;
  25081. ++$this->numimages;
  25082. }
  25083. }
  25084. /**
  25085. * Set image buffer content for a specified sub-key.
  25086. * @param $image (string) image key
  25087. * @param $key (string) image sub-key
  25088. * @param $data (array) image data
  25089. * @protected
  25090. * @since 4.5.000 (2008-12-31)
  25091. */
  25092. protected function setImageSubBuffer($image, $key, $data) {
  25093. if (!isset($this->images[$image])) {
  25094. $this->setImageBuffer($image, array());
  25095. }
  25096. if ($this->diskcache) {
  25097. $tmpimg = $this->getImageBuffer($image);
  25098. $tmpimg[$key] = $data;
  25099. $this->writeDiskCache($this->images[$image], serialize($tmpimg));
  25100. } else {
  25101. $this->images[$image][$key] = $data;
  25102. }
  25103. }
  25104. /**
  25105. * Get image buffer content.
  25106. * @param $image (string) image key
  25107. * @return string image buffer content or false in case of error
  25108. * @protected
  25109. * @since 4.5.000 (2008-12-31)
  25110. */
  25111. protected function getImageBuffer($image) {
  25112. if ($this->diskcache AND isset($this->images[$image])) {
  25113. return unserialize($this->readDiskCache($this->images[$image]));
  25114. } elseif (isset($this->images[$image])) {
  25115. return $this->images[$image];
  25116. }
  25117. return false;
  25118. }
  25119. /**
  25120. * Set font buffer content.
  25121. * @param $font (string) font key
  25122. * @param $data (array) font data
  25123. * @protected
  25124. * @since 4.5.000 (2009-01-02)
  25125. */
  25126. protected function setFontBuffer($font, $data) {
  25127. if ($this->diskcache) {
  25128. if (!isset($this->fonts[$font])) {
  25129. $this->fonts[$font] = $this->getObjFilename('font');
  25130. }
  25131. $this->writeDiskCache($this->fonts[$font], serialize($data));
  25132. } else {
  25133. $this->fonts[$font] = $data;
  25134. }
  25135. if (!in_array($font, $this->fontkeys)) {
  25136. $this->fontkeys[] = $font;
  25137. // store object ID for current font
  25138. ++$this->n;
  25139. $this->font_obj_ids[$font] = $this->n;
  25140. $this->setFontSubBuffer($font, 'n', $this->n);
  25141. }
  25142. }
  25143. /**
  25144. * Set font buffer content.
  25145. * @param $font (string) font key
  25146. * @param $key (string) font sub-key
  25147. * @param $data (array) font data
  25148. * @protected
  25149. * @since 4.5.000 (2009-01-02)
  25150. */
  25151. protected function setFontSubBuffer($font, $key, $data) {
  25152. if (!isset($this->fonts[$font])) {
  25153. $this->setFontBuffer($font, array());
  25154. }
  25155. if ($this->diskcache) {
  25156. $tmpfont = $this->getFontBuffer($font);
  25157. $tmpfont[$key] = $data;
  25158. $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
  25159. } else {
  25160. $this->fonts[$font][$key] = $data;
  25161. }
  25162. }
  25163. /**
  25164. * Get font buffer content.
  25165. * @param $font (string) font key
  25166. * @return string font buffer content or false in case of error
  25167. * @protected
  25168. * @since 4.5.000 (2009-01-02)
  25169. */
  25170. protected function getFontBuffer($font) {
  25171. if ($this->diskcache AND isset($this->fonts[$font])) {
  25172. return unserialize($this->readDiskCache($this->fonts[$font]));
  25173. } elseif (isset($this->fonts[$font])) {
  25174. return $this->fonts[$font];
  25175. }
  25176. return false;
  25177. }
  25178. /**
  25179. * Move a page to a previous position.
  25180. * @param $frompage (int) number of the source page
  25181. * @param $topage (int) number of the destination page (must be less than $frompage)
  25182. * @return true in case of success, false in case of error.
  25183. * @public
  25184. * @since 4.5.000 (2009-01-02)
  25185. */
  25186. public function movePage($frompage, $topage) {
  25187. if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
  25188. return false;
  25189. }
  25190. if ($frompage == $this->page) {
  25191. // close the page before moving it
  25192. $this->endPage();
  25193. }
  25194. // move all page-related states
  25195. $tmppage = $this->getPageBuffer($frompage);
  25196. $tmppagedim = $this->pagedim[$frompage];
  25197. $tmppagelen = $this->pagelen[$frompage];
  25198. $tmpintmrk = $this->intmrk[$frompage];
  25199. $tmpbordermrk = $this->bordermrk[$frompage];
  25200. $tmpcntmrk = $this->cntmrk[$frompage];
  25201. $tmppageobjects = $this->pageobjects[$frompage];
  25202. if (isset($this->footerpos[$frompage])) {
  25203. $tmpfooterpos = $this->footerpos[$frompage];
  25204. }
  25205. if (isset($this->footerlen[$frompage])) {
  25206. $tmpfooterlen = $this->footerlen[$frompage];
  25207. }
  25208. if (isset($this->transfmrk[$frompage])) {
  25209. $tmptransfmrk = $this->transfmrk[$frompage];
  25210. }
  25211. if (isset($this->PageAnnots[$frompage])) {
  25212. $tmpannots = $this->PageAnnots[$frompage];
  25213. }
  25214. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  25215. for ($i = $frompage; $i > $topage; --$i) {
  25216. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
  25217. --$this->pagegroups[$this->newpagegroup[$i]];
  25218. break;
  25219. }
  25220. }
  25221. for ($i = $topage; $i > 0; --$i) {
  25222. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
  25223. ++$this->pagegroups[$this->newpagegroup[$i]];
  25224. break;
  25225. }
  25226. }
  25227. }
  25228. for ($i = $frompage; $i > $topage; --$i) {
  25229. $j = $i - 1;
  25230. // shift pages down
  25231. $this->setPageBuffer($i, $this->getPageBuffer($j));
  25232. $this->pagedim[$i] = $this->pagedim[$j];
  25233. $this->pagelen[$i] = $this->pagelen[$j];
  25234. $this->intmrk[$i] = $this->intmrk[$j];
  25235. $this->bordermrk[$i] = $this->bordermrk[$j];
  25236. $this->cntmrk[$i] = $this->cntmrk[$j];
  25237. $this->pageobjects[$i] = $this->pageobjects[$j];
  25238. if (isset($this->footerpos[$j])) {
  25239. $this->footerpos[$i] = $this->footerpos[$j];
  25240. } elseif (isset($this->footerpos[$i])) {
  25241. unset($this->footerpos[$i]);
  25242. }
  25243. if (isset($this->footerlen[$j])) {
  25244. $this->footerlen[$i] = $this->footerlen[$j];
  25245. } elseif (isset($this->footerlen[$i])) {
  25246. unset($this->footerlen[$i]);
  25247. }
  25248. if (isset($this->transfmrk[$j])) {
  25249. $this->transfmrk[$i] = $this->transfmrk[$j];
  25250. } elseif (isset($this->transfmrk[$i])) {
  25251. unset($this->transfmrk[$i]);
  25252. }
  25253. if (isset($this->PageAnnots[$j])) {
  25254. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  25255. } elseif (isset($this->PageAnnots[$i])) {
  25256. unset($this->PageAnnots[$i]);
  25257. }
  25258. if (isset($this->newpagegroup[$j])) {
  25259. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  25260. unset($this->newpagegroup[$j]);
  25261. }
  25262. if ($this->currpagegroup == $j) {
  25263. $this->currpagegroup = $i;
  25264. }
  25265. }
  25266. $this->setPageBuffer($topage, $tmppage);
  25267. $this->pagedim[$topage] = $tmppagedim;
  25268. $this->pagelen[$topage] = $tmppagelen;
  25269. $this->intmrk[$topage] = $tmpintmrk;
  25270. $this->bordermrk[$topage] = $tmpbordermrk;
  25271. $this->cntmrk[$topage] = $tmpcntmrk;
  25272. $this->pageobjects[$topage] = $tmppageobjects;
  25273. if (isset($tmpfooterpos)) {
  25274. $this->footerpos[$topage] = $tmpfooterpos;
  25275. } elseif (isset($this->footerpos[$topage])) {
  25276. unset($this->footerpos[$topage]);
  25277. }
  25278. if (isset($tmpfooterlen)) {
  25279. $this->footerlen[$topage] = $tmpfooterlen;
  25280. } elseif (isset($this->footerlen[$topage])) {
  25281. unset($this->footerlen[$topage]);
  25282. }
  25283. if (isset($tmptransfmrk)) {
  25284. $this->transfmrk[$topage] = $tmptransfmrk;
  25285. } elseif (isset($this->transfmrk[$topage])) {
  25286. unset($this->transfmrk[$topage]);
  25287. }
  25288. if (isset($tmpannots)) {
  25289. $this->PageAnnots[$topage] = $tmpannots;
  25290. } elseif (isset($this->PageAnnots[$topage])) {
  25291. unset($this->PageAnnots[$topage]);
  25292. }
  25293. // adjust outlines
  25294. $tmpoutlines = $this->outlines;
  25295. foreach ($tmpoutlines as $key => $outline) {
  25296. if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
  25297. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  25298. } elseif ($outline['p'] == $frompage) {
  25299. $this->outlines[$key]['p'] = $topage;
  25300. }
  25301. }
  25302. // adjust dests
  25303. $tmpdests = $this->dests;
  25304. foreach ($tmpdests as $key => $dest) {
  25305. if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
  25306. $this->dests[$key]['p'] = ($dest['p'] + 1);
  25307. } elseif ($dest['p'] == $frompage) {
  25308. $this->dests[$key]['p'] = $topage;
  25309. }
  25310. }
  25311. // adjust links
  25312. $tmplinks = $this->links;
  25313. foreach ($tmplinks as $key => $link) {
  25314. if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
  25315. $this->links[$key][0] = ($link[0] + 1);
  25316. } elseif ($link[0] == $frompage) {
  25317. $this->links[$key][0] = $topage;
  25318. }
  25319. }
  25320. // adjust javascript
  25321. $tmpjavascript = $this->javascript;
  25322. global $jfrompage, $jtopage;
  25323. $jfrompage = $frompage;
  25324. $jtopage = $topage;
  25325. $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
  25326. create_function('$matches', 'global $jfrompage, $jtopage;
  25327. $pagenum = intval($matches[3]) + 1;
  25328. if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
  25329. $newpage = ($pagenum + 1);
  25330. } elseif ($pagenum == $jfrompage) {
  25331. $newpage = $jtopage;
  25332. } else {
  25333. $newpage = $pagenum;
  25334. }
  25335. --$newpage;
  25336. return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
  25337. // return to last page
  25338. $this->lastPage(true);
  25339. return true;
  25340. }
  25341. /**
  25342. * Remove the specified page.
  25343. * @param $page (int) page to remove
  25344. * @return true in case of success, false in case of error.
  25345. * @public
  25346. * @since 4.6.004 (2009-04-23)
  25347. */
  25348. public function deletePage($page) {
  25349. if (($page < 1) OR ($page > $this->numpages)) {
  25350. return false;
  25351. }
  25352. // delete current page
  25353. unset($this->pages[$page]);
  25354. unset($this->pagedim[$page]);
  25355. unset($this->pagelen[$page]);
  25356. unset($this->intmrk[$page]);
  25357. unset($this->bordermrk[$page]);
  25358. unset($this->cntmrk[$page]);
  25359. foreach ($this->pageobjects[$page] as $oid) {
  25360. if (isset($this->offsets[$oid])){
  25361. unset($this->offsets[$oid]);
  25362. }
  25363. }
  25364. unset($this->pageobjects[$page]);
  25365. if (isset($this->footerpos[$page])) {
  25366. unset($this->footerpos[$page]);
  25367. }
  25368. if (isset($this->footerlen[$page])) {
  25369. unset($this->footerlen[$page]);
  25370. }
  25371. if (isset($this->transfmrk[$page])) {
  25372. unset($this->transfmrk[$page]);
  25373. }
  25374. if (isset($this->PageAnnots[$page])) {
  25375. unset($this->PageAnnots[$page]);
  25376. }
  25377. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  25378. for ($i = $page; $i > 0; --$i) {
  25379. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
  25380. --$this->pagegroups[$this->newpagegroup[$i]];
  25381. break;
  25382. }
  25383. }
  25384. }
  25385. if (isset($this->pageopen[$page])) {
  25386. unset($this->pageopen[$page]);
  25387. }
  25388. if ($page < $this->numpages) {
  25389. // update remaining pages
  25390. for ($i = $page; $i < $this->numpages; ++$i) {
  25391. $j = $i + 1;
  25392. // shift pages
  25393. $this->setPageBuffer($i, $this->getPageBuffer($j));
  25394. $this->pagedim[$i] = $this->pagedim[$j];
  25395. $this->pagelen[$i] = $this->pagelen[$j];
  25396. $this->intmrk[$i] = $this->intmrk[$j];
  25397. $this->bordermrk[$i] = $this->bordermrk[$j];
  25398. $this->cntmrk[$i] = $this->cntmrk[$j];
  25399. $this->pageobjects[$i] = $this->pageobjects[$j];
  25400. if (isset($this->footerpos[$j])) {
  25401. $this->footerpos[$i] = $this->footerpos[$j];
  25402. } elseif (isset($this->footerpos[$i])) {
  25403. unset($this->footerpos[$i]);
  25404. }
  25405. if (isset($this->footerlen[$j])) {
  25406. $this->footerlen[$i] = $this->footerlen[$j];
  25407. } elseif (isset($this->footerlen[$i])) {
  25408. unset($this->footerlen[$i]);
  25409. }
  25410. if (isset($this->transfmrk[$j])) {
  25411. $this->transfmrk[$i] = $this->transfmrk[$j];
  25412. } elseif (isset($this->transfmrk[$i])) {
  25413. unset($this->transfmrk[$i]);
  25414. }
  25415. if (isset($this->PageAnnots[$j])) {
  25416. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  25417. } elseif (isset($this->PageAnnots[$i])) {
  25418. unset($this->PageAnnots[$i]);
  25419. }
  25420. if (isset($this->newpagegroup[$j])) {
  25421. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  25422. unset($this->newpagegroup[$j]);
  25423. }
  25424. if ($this->currpagegroup == $j) {
  25425. $this->currpagegroup = $i;
  25426. }
  25427. if (isset($this->pageopen[$j])) {
  25428. $this->pageopen[$i] = $this->pageopen[$j];
  25429. } elseif (isset($this->pageopen[$i])) {
  25430. unset($this->pageopen[$i]);
  25431. }
  25432. }
  25433. // remove last page
  25434. unset($this->pages[$this->numpages]);
  25435. unset($this->pagedim[$this->numpages]);
  25436. unset($this->pagelen[$this->numpages]);
  25437. unset($this->intmrk[$this->numpages]);
  25438. unset($this->bordermrk[$this->numpages]);
  25439. unset($this->cntmrk[$this->numpages]);
  25440. foreach ($this->pageobjects[$this->numpages] as $oid) {
  25441. if (isset($this->offsets[$oid])){
  25442. unset($this->offsets[$oid]);
  25443. }
  25444. }
  25445. unset($this->pageobjects[$this->numpages]);
  25446. if (isset($this->footerpos[$this->numpages])) {
  25447. unset($this->footerpos[$this->numpages]);
  25448. }
  25449. if (isset($this->footerlen[$this->numpages])) {
  25450. unset($this->footerlen[$this->numpages]);
  25451. }
  25452. if (isset($this->transfmrk[$this->numpages])) {
  25453. unset($this->transfmrk[$this->numpages]);
  25454. }
  25455. if (isset($this->PageAnnots[$this->numpages])) {
  25456. unset($this->PageAnnots[$this->numpages]);
  25457. }
  25458. if (isset($this->newpagegroup[$this->numpages])) {
  25459. unset($this->newpagegroup[$this->numpages]);
  25460. }
  25461. if ($this->currpagegroup == $this->numpages) {
  25462. $this->currpagegroup = ($this->numpages - 1);
  25463. }
  25464. if (isset($this->pagegroups[$this->numpages])) {
  25465. unset($this->pagegroups[$this->numpages]);
  25466. }
  25467. if (isset($this->pageopen[$this->numpages])) {
  25468. unset($this->pageopen[$this->numpages]);
  25469. }
  25470. }
  25471. --$this->numpages;
  25472. $this->page = $this->numpages;
  25473. // adjust outlines
  25474. $tmpoutlines = $this->outlines;
  25475. foreach ($tmpoutlines as $key => $outline) {
  25476. if ($outline['p'] > $page) {
  25477. $this->outlines[$key]['p'] = $outline['p'] - 1;
  25478. } elseif ($outline['p'] == $page) {
  25479. unset($this->outlines[$key]);
  25480. }
  25481. }
  25482. // adjust dests
  25483. $tmpdests = $this->dests;
  25484. foreach ($tmpdests as $key => $dest) {
  25485. if ($dest['p'] > $page) {
  25486. $this->dests[$key]['p'] = $dest['p'] - 1;
  25487. } elseif ($dest['p'] == $page) {
  25488. unset($this->dests[$key]);
  25489. }
  25490. }
  25491. // adjust links
  25492. $tmplinks = $this->links;
  25493. foreach ($tmplinks as $key => $link) {
  25494. if ($link[0] > $page) {
  25495. $this->links[$key][0] = $link[0] - 1;
  25496. } elseif ($link[0] == $page) {
  25497. unset($this->links[$key]);
  25498. }
  25499. }
  25500. // adjust javascript
  25501. $tmpjavascript = $this->javascript;
  25502. global $jpage;
  25503. $jpage = $page;
  25504. $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
  25505. create_function('$matches', 'global $jpage;
  25506. $pagenum = intval($matches[3]) + 1;
  25507. if ($pagenum >= $jpage) {
  25508. $newpage = ($pagenum - 1);
  25509. } elseif ($pagenum == $jpage) {
  25510. $newpage = 1;
  25511. } else {
  25512. $newpage = $pagenum;
  25513. }
  25514. --$newpage;
  25515. return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
  25516. // return to last page
  25517. $this->lastPage(true);
  25518. return true;
  25519. }
  25520. /**
  25521. * Clone the specified page to a new page.
  25522. * @param $page (int) number of page to copy (0 = current page)
  25523. * @return true in case of success, false in case of error.
  25524. * @public
  25525. * @since 4.9.015 (2010-04-20)
  25526. */
  25527. public function copyPage($page=0) {
  25528. if ($page == 0) {
  25529. // default value
  25530. $page = $this->page;
  25531. }
  25532. if (($page < 1) OR ($page > $this->numpages)) {
  25533. return false;
  25534. }
  25535. // close the last page
  25536. $this->endPage();
  25537. // copy all page-related states
  25538. ++$this->numpages;
  25539. $this->page = $this->numpages;
  25540. $this->setPageBuffer($this->page, $this->getPageBuffer($page));
  25541. $this->pagedim[$this->page] = $this->pagedim[$page];
  25542. $this->pagelen[$this->page] = $this->pagelen[$page];
  25543. $this->intmrk[$this->page] = $this->intmrk[$page];
  25544. $this->bordermrk[$this->page] = $this->bordermrk[$page];
  25545. $this->cntmrk[$this->page] = $this->cntmrk[$page];
  25546. $this->pageobjects[$this->page] = $this->pageobjects[$page];
  25547. $this->pageopen[$this->page] = false;
  25548. if (isset($this->footerpos[$page])) {
  25549. $this->footerpos[$this->page] = $this->footerpos[$page];
  25550. }
  25551. if (isset($this->footerlen[$page])) {
  25552. $this->footerlen[$this->page] = $this->footerlen[$page];
  25553. }
  25554. if (isset($this->transfmrk[$page])) {
  25555. $this->transfmrk[$this->page] = $this->transfmrk[$page];
  25556. }
  25557. if (isset($this->PageAnnots[$page])) {
  25558. $this->PageAnnots[$this->page] = $this->PageAnnots[$page];
  25559. }
  25560. if (isset($this->newpagegroup[$page])) {
  25561. // start a new group
  25562. $this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
  25563. $this->currpagegroup = $this->newpagegroup[$this->page];
  25564. $this->pagegroups[$this->currpagegroup] = 1;
  25565. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  25566. ++$this->pagegroups[$this->currpagegroup];
  25567. }
  25568. // copy outlines
  25569. $tmpoutlines = $this->outlines;
  25570. foreach ($tmpoutlines as $key => $outline) {
  25571. if ($outline['p'] == $page) {
  25572. $this->outlines[] = array('t' => $outline['t'], 'l' => $outline['l'], 'x' => $outline['x'], 'y' => $outline['y'], 'p' => $this->page, 's' => $outline['s'], 'c' => $outline['c']);
  25573. }
  25574. }
  25575. // copy links
  25576. $tmplinks = $this->links;
  25577. foreach ($tmplinks as $key => $link) {
  25578. if ($link[0] == $page) {
  25579. $this->links[] = array($this->page, $link[1]);
  25580. }
  25581. }
  25582. // return to last page
  25583. $this->lastPage(true);
  25584. return true;
  25585. }
  25586. /**
  25587. * Output a Table of Content Index (TOC).
  25588. * This method must be called after all Bookmarks were set.
  25589. * Before calling this method you have to open the page using the addTOCPage() method.
  25590. * After calling this method you have to call endTOCPage() to close the TOC page.
  25591. * You can override this method to achieve different styles.
  25592. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  25593. * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
  25594. * @param $filler (string) string used to fill the space between text and page number.
  25595. * @param $toc_name (string) name to use for TOC bookmark.
  25596. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  25597. * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
  25598. * @public
  25599. * @author Nicola Asuni
  25600. * @since 4.5.000 (2009-01-02)
  25601. * @see addTOCPage(), endTOCPage(), addHTMLTOC()
  25602. */
  25603. public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
  25604. $fontsize = $this->FontSizePt;
  25605. $fontfamily = $this->FontFamily;
  25606. $fontstyle = $this->FontStyle;
  25607. $w = $this->w - $this->lMargin - $this->rMargin;
  25608. $spacer = $this->GetStringWidth(chr(32)) * 4;
  25609. $lmargin = $this->lMargin;
  25610. $rmargin = $this->rMargin;
  25611. $x_start = $this->GetX();
  25612. $page_first = $this->page;
  25613. $current_page = $this->page;
  25614. $page_fill_start = false;
  25615. $page_fill_end = false;
  25616. $current_column = $this->current_column;
  25617. if ($this->empty_string($numbersfont)) {
  25618. $numbersfont = $this->default_monospaced_font;
  25619. }
  25620. if ($this->empty_string($filler)) {
  25621. $filler = ' ';
  25622. }
  25623. if ($this->empty_string($page)) {
  25624. $gap = ' ';
  25625. } else {
  25626. $gap = '';
  25627. if ($page < 1) {
  25628. $page = 1;
  25629. }
  25630. }
  25631. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  25632. $numwidth = $this->GetStringWidth('00000');
  25633. $maxpage = 0; //used for pages on attached documents
  25634. foreach ($this->outlines as $key => $outline) {
  25635. // check for extra pages (used for attachments)
  25636. if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
  25637. $outline['p'] += ($this->page - $page_first);
  25638. }
  25639. if ($this->rtl) {
  25640. $aligntext = 'R';
  25641. $alignnum = 'L';
  25642. } else {
  25643. $aligntext = 'L';
  25644. $alignnum = 'R';
  25645. }
  25646. if ($outline['l'] == 0) {
  25647. $this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
  25648. } else {
  25649. $this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
  25650. }
  25651. $this->SetTextColorArray($outline['c']);
  25652. // check for page break
  25653. $this->checkPageBreak((2 * $this->FontSize * $this->cell_height_ratio));
  25654. // set margins and X position
  25655. if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
  25656. $this->lMargin = $lmargin;
  25657. $this->rMargin = $rmargin;
  25658. } else {
  25659. if ($this->current_column != $current_column) {
  25660. if ($this->rtl) {
  25661. $x_start = $this->w - $this->columns[$this->current_column]['x'];
  25662. } else {
  25663. $x_start = $this->columns[$this->current_column]['x'];
  25664. }
  25665. }
  25666. $lmargin = $this->lMargin;
  25667. $rmargin = $this->rMargin;
  25668. $current_page = $this->page;
  25669. $current_column = $this->current_column;
  25670. }
  25671. $this->SetX($x_start);
  25672. $indent = ($spacer * $outline['l']);
  25673. if ($this->rtl) {
  25674. $this->x -= $indent;
  25675. $this->rMargin = $this->w - $this->x;
  25676. } else {
  25677. $this->x += $indent;
  25678. $this->lMargin = $this->x;
  25679. }
  25680. $link = $this->AddLink();
  25681. $this->SetLink($link, $outline['y'], $outline['p']);
  25682. // write the text
  25683. if ($this->rtl) {
  25684. $txt = ' '.$outline['t'];
  25685. } else {
  25686. $txt = $outline['t'].' ';
  25687. }
  25688. $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
  25689. if ($this->rtl) {
  25690. $tw = $this->x - $this->lMargin;
  25691. } else {
  25692. $tw = $this->w - $this->rMargin - $this->x;
  25693. }
  25694. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  25695. if ($this->empty_string($page)) {
  25696. $pagenum = $outline['p'];
  25697. } else {
  25698. // placemark to be replaced with the correct number
  25699. $pagenum = '{#'.($outline['p']).'}';
  25700. if ($this->isUnicodeFont()) {
  25701. $pagenum = '{'.$pagenum.'}';
  25702. }
  25703. $maxpage = max($maxpage, $outline['p']);
  25704. }
  25705. $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
  25706. $numfills = floor($fw / $this->GetStringWidth($filler));
  25707. if ($numfills > 0) {
  25708. $rowfill = str_repeat($filler, $numfills);
  25709. } else {
  25710. $rowfill = '';
  25711. }
  25712. if ($this->rtl) {
  25713. $pagenum = $pagenum.$gap.$rowfill;
  25714. } else {
  25715. $pagenum = $rowfill.$gap.$pagenum;
  25716. }
  25717. // write the number
  25718. $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
  25719. }
  25720. $page_last = $this->getPage();
  25721. $numpages = ($page_last - $page_first + 1);
  25722. // account for booklet mode
  25723. if ($this->booklet) {
  25724. // check if a blank page is required before TOC
  25725. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  25726. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  25727. if ($page_fill_start) {
  25728. // add a page at the end (to be moved before TOC)
  25729. $this->addPage();
  25730. ++$page_last;
  25731. ++$numpages;
  25732. }
  25733. if ($page_fill_end) {
  25734. // add a page at the end
  25735. $this->addPage();
  25736. ++$page_last;
  25737. ++$numpages;
  25738. }
  25739. }
  25740. $maxpage = max($maxpage, $page_last);
  25741. if (!$this->empty_string($page)) {
  25742. for ($p = $page_first; $p <= $page_last; ++$p) {
  25743. // get page data
  25744. $temppage = $this->getPageBuffer($p);
  25745. for ($n = 1; $n <= $maxpage; ++$n) {
  25746. // update page numbers
  25747. $a = '{#'.$n.'}';
  25748. // get page number aliases
  25749. $pnalias = $this->getInternalPageNumberAliases($a);
  25750. // calculate replacement number
  25751. if (($n >= $page) AND ($n <= $this->numpages)) {
  25752. $np = $n + $numpages;
  25753. } else {
  25754. $np = $n;
  25755. }
  25756. $na = $this->formatTOCPageNumber(($this->starting_page_number + $np - 1));
  25757. $nu = $this->UTF8ToUTF16BE($na, false);
  25758. // replace aliases with numbers
  25759. foreach ($pnalias['u'] as $u) {
  25760. $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
  25761. if ($this->rtl) {
  25762. $nr = $nu.$this->UTF8ToUTF16BE(' '.$sfill);
  25763. } else {
  25764. $nr = $this->UTF8ToUTF16BE($sfill.' ').$nu;
  25765. }
  25766. $temppage = str_replace($u, $nr, $temppage);
  25767. }
  25768. foreach ($pnalias['a'] as $a) {
  25769. $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
  25770. if ($this->rtl) {
  25771. $nr = $na.' '.$sfill;
  25772. } else {
  25773. $nr = $sfill.' '.$na;
  25774. }
  25775. $temppage = str_replace($a, $nr, $temppage);
  25776. }
  25777. }
  25778. // save changes
  25779. $this->setPageBuffer($p, $temppage);
  25780. }
  25781. // move pages
  25782. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  25783. if ($page_fill_start) {
  25784. $this->movePage($page_last, $page_first);
  25785. }
  25786. for ($i = 0; $i < $numpages; ++$i) {
  25787. $this->movePage($page_last, $page);
  25788. }
  25789. }
  25790. }
  25791. /**
  25792. * Output a Table Of Content Index (TOC) using HTML templates.
  25793. * This method must be called after all Bookmarks were set.
  25794. * Before calling this method you have to open the page using the addTOCPage() method.
  25795. * After calling this method you have to call endTOCPage() to close the TOC page.
  25796. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  25797. * @param $toc_name (string) name to use for TOC bookmark.
  25798. * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
  25799. * @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)
  25800. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  25801. * @param $color (array) RGB color array for title (values from 0 to 255).
  25802. * @public
  25803. * @author Nicola Asuni
  25804. * @since 5.0.001 (2010-05-06)
  25805. * @see addTOCPage(), endTOCPage(), addTOC()
  25806. */
  25807. public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
  25808. $filler = ' ';
  25809. $prev_htmlLinkColorArray = $this->htmlLinkColorArray;
  25810. $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
  25811. // set new style for link
  25812. $this->htmlLinkColorArray = array();
  25813. $this->htmlLinkFontStyle = '';
  25814. $page_first = $this->getPage();
  25815. $page_fill_start = false;
  25816. $page_fill_end = false;
  25817. // get the font type used for numbers in each template
  25818. $current_font = $this->FontFamily;
  25819. foreach ($templates as $level => $html) {
  25820. $dom = $this->getHtmlDomArray($html);
  25821. foreach ($dom as $key => $value) {
  25822. if ($value['value'] == '#TOC_PAGE_NUMBER#') {
  25823. $this->SetFont($dom[($key - 1)]['fontname']);
  25824. $templates['F'.$level] = $this->isUnicodeFont();
  25825. }
  25826. }
  25827. }
  25828. $this->SetFont($current_font);
  25829. $maxpage = 0; //used for pages on attached documents
  25830. foreach ($this->outlines as $key => $outline) {
  25831. // get HTML template
  25832. $row = $templates[$outline['l']];
  25833. if ($this->empty_string($page)) {
  25834. $pagenum = $outline['p'];
  25835. } else {
  25836. // placemark to be replaced with the correct number
  25837. $pagenum = '{#'.($outline['p']).'}';
  25838. if ($templates['F'.$outline['l']]) {
  25839. $pagenum = '{'.$pagenum.'}';
  25840. }
  25841. $maxpage = max($maxpage, $outline['p']);
  25842. }
  25843. // replace templates with current values
  25844. $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
  25845. $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
  25846. // add link to page
  25847. $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
  25848. // write bookmark entry
  25849. $this->writeHTML($row, false, false, true, false, '');
  25850. }
  25851. // restore link styles
  25852. $this->htmlLinkColorArray = $prev_htmlLinkColorArray;
  25853. $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
  25854. // move TOC page and replace numbers
  25855. $page_last = $this->getPage();
  25856. $numpages = ($page_last - $page_first + 1);
  25857. // account for booklet mode
  25858. if ($this->booklet) {
  25859. // check if a blank page is required before TOC
  25860. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  25861. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  25862. if ($page_fill_start) {
  25863. // add a page at the end (to be moved before TOC)
  25864. $this->addPage();
  25865. ++$page_last;
  25866. ++$numpages;
  25867. }
  25868. if ($page_fill_end) {
  25869. // add a page at the end
  25870. $this->addPage();
  25871. ++$page_last;
  25872. ++$numpages;
  25873. }
  25874. }
  25875. $maxpage = max($maxpage, $page_last);
  25876. if (!$this->empty_string($page)) {
  25877. for ($p = $page_first; $p <= $page_last; ++$p) {
  25878. // get page data
  25879. $temppage = $this->getPageBuffer($p);
  25880. for ($n = 1; $n <= $maxpage; ++$n) {
  25881. // update page numbers
  25882. $a = '{#'.$n.'}';
  25883. // get page number aliases
  25884. $pnalias = $this->getInternalPageNumberAliases($a);
  25885. // calculate replacement number
  25886. if ($n >= $page) {
  25887. $np = $n + $numpages;
  25888. } else {
  25889. $np = $n;
  25890. }
  25891. $na = $this->formatTOCPageNumber(($this->starting_page_number + $np - 1));
  25892. $nu = $this->UTF8ToUTF16BE($na, false);
  25893. // replace aliases with numbers
  25894. foreach ($pnalias['u'] as $u) {
  25895. if ($correct_align) {
  25896. $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
  25897. if ($this->rtl) {
  25898. $nr = $nu.$this->UTF8ToUTF16BE(' '.$sfill);
  25899. } else {
  25900. $nr = $this->UTF8ToUTF16BE($sfill.' ').$nu;
  25901. }
  25902. } else {
  25903. $nr = $nu;
  25904. }
  25905. $temppage = str_replace($u, $nr, $temppage);
  25906. }
  25907. foreach ($pnalias['a'] as $a) {
  25908. if ($correct_align) {
  25909. $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
  25910. if ($this->rtl) {
  25911. $nr = $na.' '.$sfill;
  25912. } else {
  25913. $nr = $sfill.' '.$na;
  25914. }
  25915. } else {
  25916. $nr = $na;
  25917. }
  25918. $temppage = str_replace($a, $nr, $temppage);
  25919. }
  25920. }
  25921. // save changes
  25922. $this->setPageBuffer($p, $temppage);
  25923. }
  25924. // move pages
  25925. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  25926. if ($page_fill_start) {
  25927. $this->movePage($page_last, $page_first);
  25928. }
  25929. for ($i = 0; $i < $numpages; ++$i) {
  25930. $this->movePage($page_last, $page);
  25931. }
  25932. }
  25933. }
  25934. /**
  25935. * Stores a copy of the current TCPDF object used for undo operation.
  25936. * @public
  25937. * @since 4.5.029 (2009-03-19)
  25938. */
  25939. public function startTransaction() {
  25940. if (isset($this->objcopy)) {
  25941. // remove previous copy
  25942. $this->commitTransaction();
  25943. }
  25944. // record current page number and Y position
  25945. $this->start_transaction_page = $this->page;
  25946. $this->start_transaction_y = $this->y;
  25947. // clone current object
  25948. $this->objcopy = $this->objclone($this);
  25949. }
  25950. /**
  25951. * Delete the copy of the current TCPDF object used for undo operation.
  25952. * @public
  25953. * @since 4.5.029 (2009-03-19)
  25954. */
  25955. public function commitTransaction() {
  25956. if (isset($this->objcopy)) {
  25957. $this->objcopy->_destroy(true, true);
  25958. unset($this->objcopy);
  25959. }
  25960. }
  25961. /**
  25962. * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
  25963. * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
  25964. * @return TCPDF object.
  25965. * @public
  25966. * @since 4.5.029 (2009-03-19)
  25967. */
  25968. public function rollbackTransaction($self=false) {
  25969. if (isset($this->objcopy)) {
  25970. if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
  25971. // truncate files to previous values
  25972. foreach ($this->objcopy->cache_file_length as $file => $length) {
  25973. $file = substr($file, 1);
  25974. $handle = fopen($file, 'r+');
  25975. ftruncate($handle, $length);
  25976. }
  25977. }
  25978. $this->_destroy(true, true);
  25979. if ($self) {
  25980. $objvars = get_object_vars($this->objcopy);
  25981. foreach ($objvars as $key => $value) {
  25982. $this->$key = $value;
  25983. }
  25984. }
  25985. return $this->objcopy;
  25986. }
  25987. return $this;
  25988. }
  25989. /**
  25990. * Creates a copy of a class object
  25991. * @param $object (object) class object to be cloned
  25992. * @return cloned object
  25993. * @public
  25994. * @since 4.5.029 (2009-03-19)
  25995. */
  25996. public function objclone($object) {
  25997. return @clone($object);
  25998. }
  25999. /**
  26000. * Determine whether a string is empty.
  26001. * @param $str (string) string to be checked
  26002. * @return boolean true if string is empty
  26003. * @public
  26004. * @since 4.5.044 (2009-04-16)
  26005. */
  26006. public function empty_string($str) {
  26007. return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
  26008. }
  26009. /**
  26010. * Find position of last occurrence of a substring in a string
  26011. * @param $haystack (string) The string to search in.
  26012. * @param $needle (string) substring to search.
  26013. * @param $offset (int) May be specified to begin searching an arbitrary number of characters into the string.
  26014. * @return Returns the position where the needle exists. Returns FALSE if the needle was not found.
  26015. * @public
  26016. * @since 4.8.038 (2010-03-13)
  26017. */
  26018. public function revstrpos($haystack, $needle, $offset = 0) {
  26019. $length = strlen($haystack);
  26020. $offset = ($offset > 0)?($length - $offset):abs($offset);
  26021. $pos = strpos(strrev($haystack), strrev($needle), $offset);
  26022. return ($pos === false)?false:($length - $pos - strlen($needle));
  26023. }
  26024. // --- MULTI COLUMNS METHODS -----------------------
  26025. /**
  26026. * Set multiple columns of the same size
  26027. * @param $numcols (int) number of columns (set to zero to disable columns mode)
  26028. * @param $width (int) column width
  26029. * @param $y (int) column starting Y position (leave empty for current Y position)
  26030. * @public
  26031. * @since 4.9.001 (2010-03-28)
  26032. */
  26033. public function setEqualColumns($numcols=0, $width=0, $y='') {
  26034. $this->columns = array();
  26035. if ($numcols < 2) {
  26036. $numcols = 0;
  26037. $this->columns = array();
  26038. } else {
  26039. // maximum column width
  26040. $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
  26041. if (($width == 0) OR ($width > $maxwidth)) {
  26042. $width = $maxwidth;
  26043. }
  26044. if ($this->empty_string($y)) {
  26045. $y = $this->y;
  26046. }
  26047. // space between columns
  26048. $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
  26049. // fill the columns array (with, space, starting Y position)
  26050. for ($i = 0; $i < $numcols; ++$i) {
  26051. $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
  26052. }
  26053. }
  26054. $this->num_columns = $numcols;
  26055. $this->current_column = 0;
  26056. $this->column_start_page = $this->page;
  26057. $this->selectColumn(0);
  26058. }
  26059. /**
  26060. * Remove columns and reset page margins.
  26061. * @public
  26062. * @since 5.9.072 (2011-04-26)
  26063. */
  26064. public function resetColumns() {
  26065. $this->lMargin = $this->original_lMargin;
  26066. $this->rMargin = $this->original_rMargin;
  26067. $this->setEqualColumns();
  26068. }
  26069. /**
  26070. * Set columns array.
  26071. * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
  26072. * @param $columns (array)
  26073. * @public
  26074. * @since 4.9.001 (2010-03-28)
  26075. */
  26076. public function setColumnsArray($columns) {
  26077. $this->columns = $columns;
  26078. $this->num_columns = count($columns);
  26079. $this->current_column = 0;
  26080. $this->column_start_page = $this->page;
  26081. $this->selectColumn(0);
  26082. }
  26083. /**
  26084. * Set position at a given column
  26085. * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
  26086. * @public
  26087. * @since 4.9.001 (2010-03-28)
  26088. */
  26089. public function selectColumn($col='') {
  26090. if (is_string($col)) {
  26091. $col = $this->current_column;
  26092. } elseif ($col >= $this->num_columns) {
  26093. $col = 0;
  26094. }
  26095. $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  26096. $enable_thead = false;
  26097. if ($this->num_columns > 1) {
  26098. if ($col != $this->current_column) {
  26099. // move Y pointer at the top of the column
  26100. if ($this->column_start_page == $this->page) {
  26101. $this->y = $this->columns[$col]['y'];
  26102. } else {
  26103. $this->y = $this->tMargin;
  26104. }
  26105. // Avoid to write table headers more than once
  26106. if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
  26107. $enable_thead = true;
  26108. $this->maxselcol['page'] = $this->page;
  26109. $this->maxselcol['column'] = $col;
  26110. }
  26111. }
  26112. $xshift = $this->colxshift;
  26113. // set X position of the current column by case
  26114. $listindent = ($this->listindentlevel * $this->listindent);
  26115. // calculate column X position
  26116. $colpos = 0;
  26117. for ($i = 0; $i < $col; ++$i) {
  26118. $colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
  26119. }
  26120. if ($this->rtl) {
  26121. $x = $this->w - $this->original_rMargin - $colpos;
  26122. $this->rMargin = ($this->w - $x + $listindent);
  26123. $this->lMargin = ($x - $this->columns[$col]['w']);
  26124. $this->x = $x - $listindent;
  26125. } else {
  26126. $x = $this->original_lMargin + $colpos;
  26127. $this->lMargin = ($x + $listindent);
  26128. $this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
  26129. $this->x = $x + $listindent;
  26130. }
  26131. $this->columns[$col]['x'] = $x;
  26132. }
  26133. $this->current_column = $col;
  26134. // fix for HTML mode
  26135. $this->newline = true;
  26136. // print HTML table header (if any)
  26137. if ((!$this->empty_string($this->thead)) AND (!$this->inthead)) {
  26138. if ($enable_thead) {
  26139. // print table header
  26140. $this->writeHTML($this->thead, false, false, false, false, '');
  26141. $this->y += $xshift['s']['V'];
  26142. // store end of header position
  26143. if (!isset($this->columns[$col]['th'])) {
  26144. $this->columns[$col]['th'] = array();
  26145. }
  26146. $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
  26147. $this->lasth = 0;
  26148. } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
  26149. $this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
  26150. }
  26151. }
  26152. // account for an html table cell over multiple columns
  26153. if ($this->rtl) {
  26154. $this->rMargin += $xshift['x'];
  26155. $this->x -= ($xshift['x'] + $xshift['p']['R']);
  26156. } else {
  26157. $this->lMargin += $xshift['x'];
  26158. $this->x += $xshift['x'] + $xshift['p']['L'];
  26159. }
  26160. }
  26161. /**
  26162. * Return the current column number
  26163. * @return int current column number
  26164. * @public
  26165. * @since 5.5.011 (2010-07-08)
  26166. */
  26167. public function getColumn() {
  26168. return $this->current_column;
  26169. }
  26170. /**
  26171. * Return the current number of columns.
  26172. * @return int number of columns
  26173. * @public
  26174. * @since 5.8.018 (2010-08-25)
  26175. */
  26176. public function getNumberOfColumns() {
  26177. return $this->num_columns;
  26178. }
  26179. /**
  26180. * Serialize an array of parameters to be used with TCPDF tag in HTML code.
  26181. * @param $pararray (array) parameters array
  26182. * @return sting containing serialized data
  26183. * @public
  26184. * @since 4.9.006 (2010-04-02)
  26185. */
  26186. public function serializeTCPDFtagParameters($pararray) {
  26187. return urlencode(serialize($pararray));
  26188. }
  26189. /**
  26190. * Set Text rendering mode.
  26191. * @param $stroke (int) outline size in user units (0 = disable).
  26192. * @param $fill (boolean) if true fills the text (default).
  26193. * @param $clip (boolean) if true activate clipping mode
  26194. * @public
  26195. * @since 4.9.008 (2009-04-02)
  26196. */
  26197. public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
  26198. // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
  26199. // convert text rendering parameters
  26200. if ($stroke < 0) {
  26201. $stroke = 0;
  26202. }
  26203. if ($fill === true) {
  26204. if ($stroke > 0) {
  26205. if ($clip === true) {
  26206. // Fill, then stroke text and add to path for clipping
  26207. $textrendermode = 6;
  26208. } else {
  26209. // Fill, then stroke text
  26210. $textrendermode = 2;
  26211. }
  26212. $textstrokewidth = $stroke;
  26213. } else {
  26214. if ($clip === true) {
  26215. // Fill text and add to path for clipping
  26216. $textrendermode = 4;
  26217. } else {
  26218. // Fill text
  26219. $textrendermode = 0;
  26220. }
  26221. }
  26222. } else {
  26223. if ($stroke > 0) {
  26224. if ($clip === true) {
  26225. // Stroke text and add to path for clipping
  26226. $textrendermode = 5;
  26227. } else {
  26228. // Stroke text
  26229. $textrendermode = 1;
  26230. }
  26231. $textstrokewidth = $stroke;
  26232. } else {
  26233. if ($clip === true) {
  26234. // Add text to path for clipping
  26235. $textrendermode = 7;
  26236. } else {
  26237. // Neither fill nor stroke text (invisible)
  26238. $textrendermode = 3;
  26239. }
  26240. }
  26241. }
  26242. $this->textrendermode = $textrendermode;
  26243. $this->textstrokewidth = $stroke;
  26244. }
  26245. /**
  26246. * Set parameters for drop shadow effect for text.
  26247. * @param $params (array) Array of parameters: enabled (boolean) set to true to enable shadow; depth_w (float) shadow width in user units; depth_h (float) shadow height in user units; color (array) shadow color or false to use the stroke color; opacity (float) Alpha value: real value from 0 (transparent) to 1 (opaque); blend_mode (string) blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity.
  26248. * @since 5.9.174 (2012-07-25)
  26249. * @public
  26250. */
  26251. public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
  26252. if (isset($params['enabled'])) {
  26253. $this->txtshadow['enabled'] = $params['enabled']?true:false;
  26254. } else {
  26255. $this->txtshadow['enabled'] = false;
  26256. }
  26257. if (isset($params['depth_w'])) {
  26258. $this->txtshadow['depth_w'] = floatval($params['depth_w']);
  26259. } else {
  26260. $this->txtshadow['depth_w'] = 0;
  26261. }
  26262. if (isset($params['depth_h'])) {
  26263. $this->txtshadow['depth_h'] = floatval($params['depth_h']);
  26264. } else {
  26265. $this->txtshadow['depth_h'] = 0;
  26266. }
  26267. if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
  26268. $this->txtshadow['color'] = $params['color'];
  26269. } else {
  26270. $this->txtshadow['color'] = $this->strokecolor;
  26271. }
  26272. if (isset($params['opacity'])) {
  26273. $this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
  26274. } else {
  26275. $this->txtshadow['opacity'] = 1;
  26276. }
  26277. if (isset($params['blend_mode']) AND in_array($params['blend_mode'], array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
  26278. $this->txtshadow['blend_mode'] = $params['blend_mode'];
  26279. } else {
  26280. $this->txtshadow['blend_mode'] = 'Normal';
  26281. }
  26282. if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
  26283. $this->txtshadow['enabled'] = false;
  26284. }
  26285. }
  26286. /**
  26287. * Return the text shadow parameters array.
  26288. * @return Array of parameters.
  26289. * @since 5.9.174 (2012-07-25)
  26290. * @public
  26291. */
  26292. public function getTextShadow() {
  26293. return $this->txtshadow;
  26294. }
  26295. /**
  26296. * Returns an array of chars containing soft hyphens.
  26297. * @param $word (array) array of chars
  26298. * @param $patterns (array) Array of hypenation patterns.
  26299. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algoritm.
  26300. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  26301. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  26302. * @param $charmin (int) Minimum word length to apply the hyphenation algoritm.
  26303. * @param $charmax (int) Maximum length of broken piece of word.
  26304. * @return array text with soft hyphens
  26305. * @author Nicola Asuni
  26306. * @since 4.9.012 (2010-04-12)
  26307. * @protected
  26308. */
  26309. protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  26310. $hyphenword = array(); // hyphens positions
  26311. $numchars = count($word);
  26312. if ($numchars <= $charmin) {
  26313. return $word;
  26314. }
  26315. $word_string = $this->UTF8ArrSubString($word);
  26316. // some words will be returned as-is
  26317. $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})(\]?)$/';
  26318. if (preg_match($pattern, $word_string) > 0) {
  26319. // email
  26320. return $word;
  26321. }
  26322. $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})(\]?)$/';
  26323. if (preg_match($pattern, $word_string) > 0) {
  26324. // URL
  26325. return $word;
  26326. }
  26327. if (isset($dictionary[$word_string])) {
  26328. return $this->UTF8StringToArray($dictionary[$word_string]);
  26329. }
  26330. // suround word with '_' characters
  26331. $tmpword = array_merge(array(95), $word, array(95));
  26332. $tmpnumchars = $numchars + 2;
  26333. $maxpos = $tmpnumchars - $charmin;
  26334. for ($pos = 0; $pos < $maxpos; ++$pos) {
  26335. $imax = min(($tmpnumchars - $pos), $charmax);
  26336. for ($i = $charmin; $i <= $imax; ++$i) {
  26337. $subword = strtolower($this->UTF8ArrSubString($tmpword, $pos, $pos + $i));
  26338. if (isset($patterns[$subword])) {
  26339. $pattern = $this->UTF8StringToArray($patterns[$subword]);
  26340. $pattern_length = count($pattern);
  26341. $digits = 1;
  26342. for ($j = 0; $j < $pattern_length; ++$j) {
  26343. // check if $pattern[$j] is a number
  26344. if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
  26345. if ($j == 0) {
  26346. $zero = $pos - 1;
  26347. } else {
  26348. $zero = $pos + $j - $digits;
  26349. }
  26350. if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] != $pattern[$j])) {
  26351. $hyphenword[$zero] = $this->unichr($pattern[$j]);
  26352. }
  26353. ++$digits;
  26354. }
  26355. }
  26356. }
  26357. }
  26358. }
  26359. $inserted = 0;
  26360. $maxpos = $numchars - $rightmin;
  26361. for ($i = $leftmin; $i <= $maxpos; ++$i) {
  26362. if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
  26363. // 173 = soft hyphen character
  26364. array_splice($word, $i + $inserted, 0, 173);
  26365. ++$inserted;
  26366. }
  26367. }
  26368. return $word;
  26369. }
  26370. /**
  26371. * Returns an array of hyphenation patterns.
  26372. * @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/
  26373. * @return array of hyphenation patterns
  26374. * @author Nicola Asuni
  26375. * @since 4.9.012 (2010-04-12)
  26376. * @public
  26377. */
  26378. public function getHyphenPatternsFromTEX($file) {
  26379. // TEX patterns are available at:
  26380. // http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
  26381. $data = file_get_contents($file);
  26382. $patterns = array();
  26383. // remove comments
  26384. $data = preg_replace('/\%[^\n]*/', '', $data);
  26385. // extract the patterns part
  26386. preg_match('/\\\\patterns\{([^\}]*)\}/i', $data, $matches);
  26387. $data = trim(substr($matches[0], 10, -1));
  26388. // extract each pattern
  26389. $patterns_array = preg_split('/[\s]+/', $data);
  26390. // create new language array of patterns
  26391. $patterns = array();
  26392. foreach($patterns_array as $val) {
  26393. if (!$this->empty_string($val)) {
  26394. $val = trim($val);
  26395. $val = str_replace('\'', '\\\'', $val);
  26396. $key = preg_replace('/[0-9]+/', '', $val);
  26397. $patterns[$key] = $val;
  26398. }
  26399. }
  26400. return $patterns;
  26401. }
  26402. /**
  26403. * Returns text with soft hyphens.
  26404. * @param $text (string) text to process
  26405. * @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/
  26406. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algoritm.
  26407. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  26408. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  26409. * @param $charmin (int) Minimum word length to apply the hyphenation algoritm.
  26410. * @param $charmax (int) Maximum length of broken piece of word.
  26411. * @return array text with soft hyphens
  26412. * @author Nicola Asuni
  26413. * @since 4.9.012 (2010-04-12)
  26414. * @public
  26415. */
  26416. public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  26417. $text = $this->unhtmlentities($text);
  26418. $word = array(); // last word
  26419. $txtarr = array(); // text to be returned
  26420. $intag = false; // true if we are inside an HTML tag
  26421. if (!is_array($patterns)) {
  26422. $patterns = $this->getHyphenPatternsFromTEX($patterns);
  26423. }
  26424. // get array of characters
  26425. $unichars = $this->UTF8StringToArray($text);
  26426. // for each char
  26427. foreach ($unichars as $char) {
  26428. if ((!$intag) AND $this->unicode->uni_type[$char] == 'L') {
  26429. // letter character
  26430. $word[] = $char;
  26431. } else {
  26432. // other type of character
  26433. if (!$this->empty_string($word)) {
  26434. // hypenate the word
  26435. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  26436. $word = array();
  26437. }
  26438. $txtarr[] = $char;
  26439. if (chr($char) == '<') {
  26440. // we are inside an HTML tag
  26441. $intag = true;
  26442. } elseif ($intag AND (chr($char) == '>')) {
  26443. // end of HTML tag
  26444. $intag = false;
  26445. }
  26446. }
  26447. }
  26448. if (!$this->empty_string($word)) {
  26449. // hypenate the word
  26450. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  26451. }
  26452. // convert char array to string and return
  26453. return $this->UTF8ArrSubString($txtarr);
  26454. }
  26455. /**
  26456. * Enable/disable rasterization of vector images using ImageMagick library.
  26457. * @param $mode (boolean) if true enable rasterization, false otherwise.
  26458. * @public
  26459. * @since 5.0.000 (2010-04-27)
  26460. */
  26461. public function setRasterizeVectorImages($mode) {
  26462. $this->rasterize_vector_images = $mode;
  26463. }
  26464. /**
  26465. * Get the Path-Painting Operators.
  26466. * @param $style (string) Style of rendering. Possible values are:
  26467. * <ul>
  26468. * <li>S or D: Stroke the path.</li>
  26469. * <li>s or d: Close and stroke the path.</li>
  26470. * <li>f or F: Fill the path, using the nonzero winding number rule to determine the region to fill.</li>
  26471. * <li>f* or F*: Fill the path, using the even-odd rule to determine the region to fill.</li>
  26472. * <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>
  26473. * <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>
  26474. * <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>
  26475. * <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>
  26476. * <li>CNZ: Clipping mode using the even-odd rule to determine which regions lie inside the clipping path.</li>
  26477. * <li>CEO: Clipping mode using the nonzero winding number rule to determine which regions lie inside the clipping path</li>
  26478. * <li>n: End the path object without filling or stroking it.</li>
  26479. * </ul>
  26480. * @param $default (string) default style
  26481. * @author Nicola Asuni
  26482. * @since 5.0.000 (2010-04-30)
  26483. * @protected
  26484. */
  26485. protected function getPathPaintOperator($style, $default='S') {
  26486. $op = '';
  26487. switch($style) {
  26488. case 'S':
  26489. case 'D': {
  26490. $op = 'S';
  26491. break;
  26492. }
  26493. case 's':
  26494. case 'd': {
  26495. $op = 's';
  26496. break;
  26497. }
  26498. case 'f':
  26499. case 'F': {
  26500. $op = 'f';
  26501. break;
  26502. }
  26503. case 'f*':
  26504. case 'F*': {
  26505. $op = 'f*';
  26506. break;
  26507. }
  26508. case 'B':
  26509. case 'FD':
  26510. case 'DF': {
  26511. $op = 'B';
  26512. break;
  26513. }
  26514. case 'B*':
  26515. case 'F*D':
  26516. case 'DF*': {
  26517. $op = 'B*';
  26518. break;
  26519. }
  26520. case 'b':
  26521. case 'fd':
  26522. case 'df': {
  26523. $op = 'b';
  26524. break;
  26525. }
  26526. case 'b*':
  26527. case 'f*d':
  26528. case 'df*': {
  26529. $op = 'b*';
  26530. break;
  26531. }
  26532. case 'CNZ': {
  26533. $op = 'W n';
  26534. break;
  26535. }
  26536. case 'CEO': {
  26537. $op = 'W* n';
  26538. break;
  26539. }
  26540. case 'n': {
  26541. $op = 'n';
  26542. break;
  26543. }
  26544. default: {
  26545. if (!empty($default)) {
  26546. $op = $this->getPathPaintOperator($default, '');
  26547. } else {
  26548. $op = '';
  26549. }
  26550. }
  26551. }
  26552. return $op;
  26553. }
  26554. /**
  26555. * Enable or disable default option for font subsetting.
  26556. * @param $enable (boolean) if true enable font subsetting by default.
  26557. * @author Nicola Asuni
  26558. * @public
  26559. * @since 5.3.002 (2010-06-07)
  26560. */
  26561. public function setFontSubsetting($enable=true) {
  26562. if ($this->pdfa_mode) {
  26563. $this->font_subsetting = false;
  26564. } else {
  26565. $this->font_subsetting = $enable ? true : false;
  26566. }
  26567. }
  26568. /**
  26569. * Return the default option for font subsetting.
  26570. * @return boolean default font subsetting state.
  26571. * @author Nicola Asuni
  26572. * @public
  26573. * @since 5.3.002 (2010-06-07)
  26574. */
  26575. public function getFontSubsetting() {
  26576. return $this->font_subsetting;
  26577. }
  26578. /**
  26579. * Left trim the input string
  26580. * @param $str (string) string to trim
  26581. * @param $replace (string) string that replace spaces.
  26582. * @return left trimmed string
  26583. * @author Nicola Asuni
  26584. * @public
  26585. * @since 5.8.000 (2010-08-11)
  26586. */
  26587. public function stringLeftTrim($str, $replace='') {
  26588. return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
  26589. }
  26590. /**
  26591. * Right trim the input string
  26592. * @param $str (string) string to trim
  26593. * @param $replace (string) string that replace spaces.
  26594. * @return right trimmed string
  26595. * @author Nicola Asuni
  26596. * @public
  26597. * @since 5.8.000 (2010-08-11)
  26598. */
  26599. public function stringRightTrim($str, $replace='') {
  26600. return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
  26601. }
  26602. /**
  26603. * Trim the input string
  26604. * @param $str (string) string to trim
  26605. * @param $replace (string) string that replace spaces.
  26606. * @return trimmed string
  26607. * @author Nicola Asuni
  26608. * @public
  26609. * @since 5.8.000 (2010-08-11)
  26610. */
  26611. public function stringTrim($str, $replace='') {
  26612. $str = $this->stringLeftTrim($str, $replace);
  26613. $str = $this->stringRightTrim($str, $replace);
  26614. return $str;
  26615. }
  26616. /**
  26617. * Return true if the current font is unicode type.
  26618. * @return true for unicode font, false otherwise.
  26619. * @author Nicola Asuni
  26620. * @public
  26621. * @since 5.8.002 (2010-08-14)
  26622. */
  26623. public function isUnicodeFont() {
  26624. return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
  26625. }
  26626. /**
  26627. * Return normalized font name
  26628. * @param $fontfamily (string) property string containing font family names
  26629. * @return string normalized font name
  26630. * @author Nicola Asuni
  26631. * @public
  26632. * @since 5.8.004 (2010-08-17)
  26633. */
  26634. public function getFontFamilyName($fontfamily) {
  26635. // remove spaces and symbols
  26636. $fontfamily = preg_replace('/[^a-z0-9\,]/', '', strtolower($fontfamily));
  26637. // extract all font names
  26638. $fontslist = preg_split('/[,]/', $fontfamily);
  26639. // find first valid font name
  26640. foreach ($fontslist as $font) {
  26641. // replace font variations
  26642. $font = preg_replace('/italic$/', 'I', $font);
  26643. $font = preg_replace('/oblique$/', 'I', $font);
  26644. $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
  26645. // replace common family names and core fonts
  26646. $pattern = array();
  26647. $replacement = array();
  26648. $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
  26649. $replacement[] = 'times';
  26650. $pattern[] = '/^sansserif/';
  26651. $replacement[] = 'helvetica';
  26652. $pattern[] = '/^monospace/';
  26653. $replacement[] = 'courier';
  26654. $font = preg_replace($pattern, $replacement, $font);
  26655. if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
  26656. return $font;
  26657. }
  26658. }
  26659. // return current font as default
  26660. return $this->CurrentFont['fontkey'];
  26661. }
  26662. /**
  26663. * Start a new XObject Template.
  26664. * 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).
  26665. * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the