PageRenderTime 125ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/include/tcpdf/tcpdf.php

https://github.com/mikmagic/sugarcrm_dev
PHP | 13689 lines | 8693 code | 529 blank | 4467 comment | 2017 complexity | 5910187df5ca596767e5a384279c3f0b MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. /*
  3. Modification information for LGPL compliance
  4. Mon May 30 16:16:13 2011 +0300 - alex-vlasov - Bug 41216 - currency is displayed on 2 lines instead of one when printing a quote to PDF
  5. r57813 - 2010-08-19 10:34:44 -0700 (Thu, 19 Aug 2010) - kjing - Author: John Mertic <jmertic@sugarcrm.com>
  6. Bug 39085 - When loading the opposite search panel via ajax on the ListViews, call the index action instead of the ListView action to avoid touching pre-MVC code by accident.
  7. r56990 - 2010-06-16 13:05:36 -0700 (Wed, 16 Jun 2010) - kjing - snapshot "Mango" svn branch to a new one for GitHub sync
  8. r56989 - 2010-06-16 13:01:33 -0700 (Wed, 16 Jun 2010) - kjing - defunt "Mango" svn dev branch before github cutover
  9. r55980 - 2010-04-19 13:31:28 -0700 (Mon, 19 Apr 2010) - kjing - create Mango (6.1) based on windex
  10. r53409 - 2010-01-03 19:31:15 -0800 (Sun, 03 Jan 2010) - roger - merge -r50376:HEAD from fuji_newtag_tmp
  11. r51719 - 2009-10-22 10:18:00 -0700 (Thu, 22 Oct 2009) - mitani - Converted to Build 3 tags and updated the build system
  12. r51634 - 2009-10-19 13:32:22 -0700 (Mon, 19 Oct 2009) - mitani - Windex is the branch for Sugar Sales 1.0 development
  13. r51443 - 2009-10-12 13:34:36 -0700 (Mon, 12 Oct 2009) - jmertic - Bug 33332 - Made application PHP 5.3 compliant with E_DEPRECATED warnings on by:
  14. - Changing all ereg function to either preg or simple string based ones
  15. - No more references to magic quotes.
  16. - Change all the session_unregister() functions to just unset() the correct session variable instead.
  17. r50375 - 2009-08-24 18:07:43 -0700 (Mon, 24 Aug 2009) - dwong - branch kobe2 from tokyo r50372
  18. r47904 - 2009-06-02 11:54:10 -0700 (Tue, 02 Jun 2009) - jenny - Adding changes that were made to the earlier version of this file to support jpg images.
  19. r47900 - 2009-06-02 11:26:55 -0700 (Tue, 02 Jun 2009) - jenny - Updating with changes from bsoufflet.
  20. r46662 - 2009-04-29 10:48:07 -0700 (Wed, 29 Apr 2009) - jenny - Invoking native jpg image support which isnt' automatically there.
  21. r46617 - 2009-04-28 16:08:45 -0700 (Tue, 28 Apr 2009) - jenny - Fixing a bug in TCPDF that checks to see if the GD library is installed.
  22. r46451 - 2009-04-23 16:57:40 -0700 (Thu, 23 Apr 2009) - jenny - tcpdf initial checkin.
  23. */
  24. //============================================================+
  25. // File name : tcpdf.php
  26. // Begin : 2002-08-03
  27. // Last Update : 2009-05-28
  28. // Author : Nicola Asuni - info@tecnick.com - http://www.tcpdf.org
  29. // Version : 4.6.013
  30. // License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
  31. // ----------------------------------------------------------------------------
  32. // Copyright (C) 2002-2009 Nicola Asuni - Tecnick.com S.r.l.
  33. //
  34. // This program is free software: you can redistribute it and/or modify
  35. // it under the terms of the GNU Lesser General Public License as published by
  36. // the Free Software Foundation, either version 2.1 of the License, or
  37. // (at your option) any later version.
  38. //
  39. // This program is distributed in the hope that it will be useful,
  40. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  41. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  42. // GNU Lesser General Public License for more details.
  43. //
  44. // You should have received a copy of the GNU Lesser General Public License
  45. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  46. //
  47. // See LICENSE.TXT file for more information.
  48. // ----------------------------------------------------------------------------
  49. //
  50. // Description : This is a PHP class for generating PDF documents without
  51. // requiring external extensions.
  52. //
  53. // NOTE:
  54. // This class was originally derived in 2002 from the Public
  55. // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
  56. // but now is almost entirely rewritten.
  57. //
  58. // Main features:
  59. // * no external libraries are required for the basic functions;
  60. // * supports all ISO page formats;
  61. // * supports custom page formats, margins and units of measure;
  62. // * supports UTF-8 Unicode and Right-To-Left languages;
  63. // * supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;
  64. // * supports document encryption;
  65. // * includes methods to publish some XHTML code;
  66. // * includes graphic (geometric) and transformation methods;
  67. // * includes Javascript and forms support;
  68. // * includes a method to print various barcode formats: 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;
  69. // * includes methods to set Bookmarks and print a Table of Content;
  70. // * includes methods to move and delete pages;
  71. // * includes methods for automatic page header and footer management;
  72. // * supports automatic page break;
  73. // * supports automatic page numbering and page groups;
  74. // * supports automatic line break and text justification;
  75. // * supports JPEG and PNG 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)
  76. // * supports stroke and clipping mode for text;
  77. // * supports clipping masks;
  78. // * supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;
  79. // * supports several annotations, including links, text and file attachments;
  80. // * supports page compression (requires zlib extension);
  81. // * supports text hyphenation.
  82. // * supports transactions to UNDO commands.
  83. //
  84. // -----------------------------------------------------------
  85. // THANKS TO:
  86. //
  87. // Olivier Plathey (http://www.fpdf.org) for original FPDF.
  88. // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
  89. // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
  90. // Warren Sherliker (wsherliker@gmail.com) for better image handling.
  91. // dullus for text Justification.
  92. // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
  93. // Patrick Benny for text stretch suggestion on Cell().
  94. // Johannes G�ntert for JavaScript support.
  95. // Denis Van Nuffelen for Dynamic Form.
  96. // Jacek Czekaj for multibyte justification
  97. // Anthony Ferrara for the reintroduction of legacy image methods.
  98. // Sourceforge user 1707880 (hucste) for line-trough mode.
  99. // Larry Stanbery for page groups.
  100. // Martin Hall-May for transparency.
  101. // Aaron C. Spike for Polycurve method.
  102. // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
  103. // Moritz Wagner and Andreas Wurmser for graphic functions.
  104. // Andrew Whitehead for core fonts support.
  105. // Esteban Jo�l Mar�n for OpenType font conversion.
  106. // Teus Hagen for several suggestions and fixes.
  107. // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
  108. // Kosmas Papachristos for some CSS improvements.
  109. // Marcel Partap for some fixes.
  110. // Won Kyu Park for several suggestions, fixes and patches.
  111. // Anyone that has reported a bug or sent a suggestion.
  112. //============================================================+
  113. /**
  114. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  115. * 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>
  116. * <h3>TCPDF main features are:</h3>
  117. * <ul>
  118. * <li>no external libraries are required for the basic functions;</li>
  119. * <li>supports all ISO page formats;</li>
  120. * <li>supports custom page formats, margins and units of measure;</li>
  121. * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
  122. * <li>supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;</li>
  123. * <li>supports document encryption;</li>
  124. * <li>includes methods to publish some XHTML code;</li>
  125. * <li>includes graphic (geometric) and transformation methods;</li>
  126. * <li>includes Javascript and forms support;</li>
  127. * <li>includes a method to print various barcode formats: 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;</li>
  128. * <li>includes methods to set Bookmarks and print a Table of Content;</li>
  129. * <li>includes methods to move and delete pages;</li>
  130. * <li>includes methods for automatic page header and footer management;</li>
  131. * <li>supports automatic page break;</li>
  132. * <li>supports automatic page numbering and page groups;</li>
  133. * <li>supports automatic line break and text justification;</li>
  134. * <li>supports JPEG and PNG 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>
  135. * <li>supports stroke and clipping mode for text;</li>
  136. * <li>supports clipping masks;</li>
  137. * <li>supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
  138. * <li>supports several annotations, including links, text and file attachments;</li>
  139. * <li>supports page compression (requires zlib extension);</li>
  140. * <li>supports text hyphenation.</li>
  141. * <li>supports transactions to UNDO commands.</li>
  142. * </ul>
  143. * Tools to encode your unicode fonts are on fonts/utils directory.</p>
  144. * @package com.tecnick.tcpdf
  145. * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
  146. * @author Nicola Asuni
  147. * @copyright 2002-2009 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
  148. * @link http://www.tcpdf.org
  149. * @license http://www.gnu.org/copyleft/lesser.html LGPL
  150. * @version 4.6.013
  151. */
  152. /**
  153. * main configuration file
  154. */
  155. require_once(dirname(__FILE__).'/config/tcpdf_config.php');
  156. // includes some support files
  157. /**
  158. * unicode data
  159. */
  160. require_once(dirname(__FILE__).'/unicode_data.php');
  161. /**
  162. * html colors table
  163. */
  164. require_once(dirname(__FILE__).'/htmlcolors.php');
  165. if (!class_exists('TCPDF', false)) {
  166. /**
  167. * define default PDF document producer
  168. */
  169. define('PDF_PRODUCER', 'TCPDF 4.6.013 (http://www.tcpdf.org)');
  170. /**
  171. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  172. * 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>
  173. * @name TCPDF
  174. * @package com.tecnick.tcpdf
  175. * @version 4.6.013
  176. * @author Nicola Asuni - info@tecnick.com
  177. * @link http://www.tcpdf.org
  178. * @license http://www.gnu.org/copyleft/lesser.html LGPL
  179. */
  180. class TCPDF {
  181. // protected or Protected properties
  182. /**
  183. * @var current page number
  184. * @access protected
  185. */
  186. protected $page;
  187. /**
  188. * @var current object number
  189. * @access protected
  190. */
  191. protected $n;
  192. /**
  193. * @var array of object offsets
  194. * @access protected
  195. */
  196. protected $offsets;
  197. /**
  198. * @var buffer holding in-memory PDF
  199. * @access protected
  200. */
  201. protected $buffer;
  202. /**
  203. * @var array containing pages
  204. * @access protected
  205. */
  206. protected $pages = array();
  207. /**
  208. * @var current document state
  209. * @access protected
  210. */
  211. protected $state;
  212. /**
  213. * @var compression flag
  214. * @access protected
  215. */
  216. protected $compress;
  217. /**
  218. * @var current page orientation (P = Portrait, L = Landscape)
  219. * @access protected
  220. */
  221. protected $CurOrientation;
  222. /**
  223. * @var array that stores page dimensions and graphic status.<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_points</li><li>$this->pagedim[$this->page]['hk'] => height</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></ul>
  224. * @access protected
  225. */
  226. protected $pagedim = array();
  227. /**
  228. * @var scale factor (number of points in user unit)
  229. * @access protected
  230. */
  231. protected $k;
  232. /**
  233. * @var width of page format in points
  234. * @access protected
  235. */
  236. protected $fwPt;
  237. /**
  238. * @var height of page format in points
  239. * @access protected
  240. */
  241. protected $fhPt;
  242. /**
  243. * @var current width of page in points
  244. * @access protected
  245. */
  246. protected $wPt;
  247. /**
  248. * @var current height of page in points
  249. * @access protected
  250. */
  251. protected $hPt;
  252. /**
  253. * @var current width of page in user unit
  254. * @access protected
  255. */
  256. protected $w;
  257. /**
  258. * @var current height of page in user unit
  259. * @access protected
  260. */
  261. protected $h;
  262. /**
  263. * @var left margin
  264. * @access protected
  265. */
  266. protected $lMargin;
  267. /**
  268. * @var top margin
  269. * @access protected
  270. */
  271. protected $tMargin;
  272. /**
  273. * @var right margin
  274. * @access protected
  275. */
  276. protected $rMargin;
  277. /**
  278. * @var page break margin
  279. * @access protected
  280. */
  281. protected $bMargin;
  282. /**
  283. * @var cell internal padding
  284. * @access protected
  285. */
  286. //protected
  287. public $cMargin;
  288. /**
  289. * @var cell internal padding (previous value)
  290. * @access protected
  291. */
  292. protected $oldcMargin;
  293. /**
  294. * @var current horizontal position in user unit for cell positioning
  295. * @access protected
  296. */
  297. protected $x;
  298. /**
  299. * @var current vertical position in user unit for cell positioning
  300. * @access protected
  301. */
  302. protected $y;
  303. /**
  304. * @var height of last cell printed
  305. * @access protected
  306. */
  307. protected $lasth;
  308. /**
  309. * @var line width in user unit
  310. * @access protected
  311. */
  312. protected $LineWidth;
  313. /**
  314. * @var array of standard font names
  315. * @access protected
  316. */
  317. protected $CoreFonts;
  318. /**
  319. * @var array of used fonts
  320. * @access protected
  321. */
  322. protected $fonts = array();
  323. /**
  324. * @var array of font files
  325. * @access protected
  326. */
  327. protected $FontFiles = array();
  328. /**
  329. * @var array of encoding differences
  330. * @access protected
  331. */
  332. protected $diffs = array();
  333. /**
  334. * @var array of used images
  335. * @access protected
  336. */
  337. protected $images = array();
  338. /**
  339. * @var array of Annotations in pages
  340. * @access protected
  341. */
  342. protected $PageAnnots = array();
  343. /**
  344. * @var array of internal links
  345. * @access protected
  346. */
  347. protected $links = array();
  348. /**
  349. * @var current font family
  350. * @access protected
  351. */
  352. protected $FontFamily;
  353. /**
  354. * @var current font style
  355. * @access protected
  356. */
  357. protected $FontStyle;
  358. /**
  359. * @var current font ascent (distance between font top and baseline)
  360. * @access protected
  361. * @since 2.8.000 (2007-03-29)
  362. */
  363. protected $FontAscent;
  364. /**
  365. * @var current font descent (distance between font bottom and baseline)
  366. * @access protected
  367. * @since 2.8.000 (2007-03-29)
  368. */
  369. protected $FontDescent;
  370. /**
  371. * @var underlining flag
  372. * @access protected
  373. */
  374. protected $underline;
  375. /**
  376. * @var current font info
  377. * @access protected
  378. */
  379. protected $CurrentFont;
  380. /**
  381. * @var current font size in points
  382. * @access protected
  383. */
  384. protected $FontSizePt;
  385. /**
  386. * @var current font size in user unit
  387. * @access protected
  388. */
  389. protected $FontSize;
  390. /**
  391. * @var commands for drawing color
  392. * @access protected
  393. */
  394. protected $DrawColor;
  395. /**
  396. * @var commands for filling color
  397. * @access protected
  398. */
  399. protected $FillColor;
  400. /**
  401. * @var commands for text color
  402. * @access protected
  403. */
  404. protected $TextColor;
  405. /**
  406. * @var indicates whether fill and text colors are different
  407. * @access protected
  408. */
  409. protected $ColorFlag;
  410. /**
  411. * @var automatic page breaking
  412. * @access protected
  413. */
  414. protected $AutoPageBreak;
  415. /**
  416. * @var threshold used to trigger page breaks
  417. * @access protected
  418. */
  419. protected $PageBreakTrigger;
  420. /**
  421. * @var flag set when processing footer
  422. * @access protected
  423. */
  424. protected $InFooter = false;
  425. /**
  426. * @var zoom display mode
  427. * @access protected
  428. */
  429. protected $ZoomMode;
  430. /**
  431. * @var layout display mode
  432. * @access protected
  433. */
  434. protected $LayoutMode;
  435. /**
  436. * @var title
  437. * @access protected
  438. */
  439. protected $title = '';
  440. /**
  441. * @var subject
  442. * @access protected
  443. */
  444. protected $subject = '';
  445. /**
  446. * @var author
  447. * @access protected
  448. */
  449. protected $author = '';
  450. /**
  451. * @var keywords
  452. * @access protected
  453. */
  454. protected $keywords = '';
  455. /**
  456. * @var creator
  457. * @access protected
  458. */
  459. protected $creator = '';
  460. /**
  461. * @var alias for total number of pages
  462. * @access protected
  463. */
  464. protected $AliasNbPages = '{nb}';
  465. /**
  466. * @var alias for page number
  467. * @access protected
  468. */
  469. protected $AliasNumPage = '{pnb}';
  470. /**
  471. * @var right-bottom corner X coordinate of inserted image
  472. * @since 2002-07-31
  473. * @author Nicola Asuni
  474. * @access protected
  475. */
  476. protected $img_rb_x;
  477. /**
  478. * @var right-bottom corner Y coordinate of inserted image
  479. * @since 2002-07-31
  480. * @author Nicola Asuni
  481. * @access protected
  482. */
  483. protected $img_rb_y;
  484. /**
  485. * @var adjusting factor to convert pixels to user units.
  486. * @since 2004-06-14
  487. * @author Nicola Asuni
  488. * @access protected
  489. */
  490. protected $imgscale = 1;
  491. /**
  492. * @var boolean set to true when the input text is unicode (require unicode fonts)
  493. * @since 2005-01-02
  494. * @author Nicola Asuni
  495. * @access protected
  496. */
  497. protected $isunicode = false;
  498. /**
  499. * @var PDF version
  500. * @since 1.5.3
  501. * @access protected
  502. */
  503. protected $PDFVersion = '1.7';
  504. // ----------------------
  505. /**
  506. * @var Minimum distance between header and top page margin.
  507. * @access protected
  508. */
  509. protected $header_margin;
  510. /**
  511. * @var Minimum distance between footer and bottom page margin.
  512. * @access protected
  513. */
  514. protected $footer_margin;
  515. /**
  516. * @var original left margin value
  517. * @access protected
  518. * @since 1.53.0.TC013
  519. */
  520. protected $original_lMargin;
  521. /**
  522. * @var original right margin value
  523. * @access protected
  524. * @since 1.53.0.TC013
  525. */
  526. protected $original_rMargin;
  527. /**
  528. * @var Header font.
  529. * @access protected
  530. */
  531. protected $header_font;
  532. /**
  533. * @var Footer font.
  534. * @access protected
  535. */
  536. protected $footer_font;
  537. /**
  538. * @var Language templates.
  539. * @access protected
  540. */
  541. protected $l;
  542. /**
  543. * @var Barcode to print on page footer (only if set).
  544. * @access protected
  545. */
  546. protected $barcode = false;
  547. /**
  548. * @var If true prints header
  549. * @access protected
  550. */
  551. protected $print_header = true;
  552. /**
  553. * @var If true prints footer.
  554. * @access protected
  555. */
  556. protected $print_footer = true;
  557. /**
  558. * @var Header image logo.
  559. * @access protected
  560. */
  561. protected $header_logo = '';
  562. /**
  563. * @var Header image logo width in mm.
  564. * @access protected
  565. */
  566. protected $header_logo_width = 30;
  567. /**
  568. * @var String to print as title on document header.
  569. * @access protected
  570. */
  571. protected $header_title = '';
  572. /**
  573. * @var String to print on document header.
  574. * @access protected
  575. */
  576. protected $header_string = '';
  577. /**
  578. * @var Default number of columns for html table.
  579. * @access protected
  580. */
  581. protected $default_table_columns = 4;
  582. // variables for html parser
  583. /**
  584. * @var HTML PARSER: array to store current link and rendering styles.
  585. * @access protected
  586. */
  587. protected $HREF = array();
  588. /**
  589. * @var store a list of available fonts on filesystem.
  590. * @access protected
  591. */
  592. protected $fontlist = array();
  593. /**
  594. * @var current foreground color
  595. * @access protected
  596. */
  597. protected $fgcolor;
  598. /**
  599. * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
  600. * @access protected
  601. */
  602. protected $listordered = array();
  603. /**
  604. * @var HTML PARSER: array count list items on nested lists.
  605. * @access protected
  606. */
  607. protected $listcount = array();
  608. /**
  609. * @var HTML PARSER: current list nesting level.
  610. * @access protected
  611. */
  612. protected $listnum = 0;
  613. /**
  614. * @var HTML PARSER: indent amount for lists.
  615. * @access protected
  616. */
  617. protected $listindent;
  618. /**
  619. * @var current background color
  620. * @access protected
  621. */
  622. protected $bgcolor;
  623. /**
  624. * @var Store temporary font size in points.
  625. * @access protected
  626. */
  627. protected $tempfontsize = 10;
  628. /**
  629. * @var spacer for LI tags.
  630. * @access protected
  631. */
  632. protected $lispacer = '';
  633. /**
  634. * @var default encoding
  635. * @access protected
  636. * @since 1.53.0.TC010
  637. */
  638. protected $encoding = 'UTF-8';
  639. /**
  640. * @var PHP internal encoding
  641. * @access protected
  642. * @since 1.53.0.TC016
  643. */
  644. protected $internal_encoding;
  645. /**
  646. * @var indicates if the document language is Right-To-Left
  647. * @access protected
  648. * @since 2.0.000
  649. */
  650. protected $rtl = false;
  651. /**
  652. * @var used to force RTL or LTR string inversion
  653. * @access protected
  654. * @since 2.0.000
  655. */
  656. protected $tmprtl = false;
  657. // --- Variables used for document encryption:
  658. /**
  659. * Indicates whether document is protected
  660. * @access protected
  661. * @since 2.0.000 (2008-01-02)
  662. */
  663. protected $encrypted;
  664. /**
  665. * U entry in pdf document
  666. * @access protected
  667. * @since 2.0.000 (2008-01-02)
  668. */
  669. protected $Uvalue;
  670. /**
  671. * O entry in pdf document
  672. * @access protected
  673. * @since 2.0.000 (2008-01-02)
  674. */
  675. protected $Ovalue;
  676. /**
  677. * P entry in pdf document
  678. * @access protected
  679. * @since 2.0.000 (2008-01-02)
  680. */
  681. protected $Pvalue;
  682. /**
  683. * encryption object id
  684. * @access protected
  685. * @since 2.0.000 (2008-01-02)
  686. */
  687. protected $enc_obj_id;
  688. /**
  689. * last RC4 key encrypted (cached for optimisation)
  690. * @access protected
  691. * @since 2.0.000 (2008-01-02)
  692. */
  693. protected $last_rc4_key;
  694. /**
  695. * last RC4 computed key
  696. * @access protected
  697. * @since 2.0.000 (2008-01-02)
  698. */
  699. protected $last_rc4_key_c;
  700. /**
  701. * RC4 padding
  702. * @access protected
  703. */
  704. protected $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";
  705. /**
  706. * RC4 encryption key
  707. * @access protected
  708. */
  709. protected $encryption_key;
  710. // --- bookmark ---
  711. /**
  712. * Outlines for bookmark
  713. * @access protected
  714. * @since 2.1.002 (2008-02-12)
  715. */
  716. protected $outlines = array();
  717. /**
  718. * Outline root for bookmark
  719. * @access protected
  720. * @since 2.1.002 (2008-02-12)
  721. */
  722. protected $OutlineRoot;
  723. // --- javascript and form ---
  724. /**
  725. * javascript code
  726. * @access protected
  727. * @since 2.1.002 (2008-02-12)
  728. */
  729. protected $javascript = '';
  730. /**
  731. * javascript counter
  732. * @access protected
  733. * @since 2.1.002 (2008-02-12)
  734. */
  735. protected $n_js;
  736. /**
  737. * line trough state
  738. * @access protected
  739. * @since 2.8.000 (2008-03-19)
  740. */
  741. protected $linethrough;
  742. // --- Variables used for User's Rights ---
  743. // See PDF reference chapter 8.7 Digital Signatures
  744. /**
  745. * If true enables user's rights on PDF reader
  746. * @access protected
  747. * @since 2.9.000 (2008-03-26)
  748. */
  749. protected $ur;
  750. /**
  751. * Names specifying additional document-wide usage rights for the document.
  752. * @access protected
  753. * @since 2.9.000 (2008-03-26)
  754. */
  755. protected $ur_document;
  756. /**
  757. * Names specifying additional annotation-related usage rights for the document.
  758. * @access protected
  759. * @since 2.9.000 (2008-03-26)
  760. */
  761. protected $ur_annots;
  762. /**
  763. * Names specifying additional form-field-related usage rights for the document.
  764. * @access protected
  765. * @since 2.9.000 (2008-03-26)
  766. */
  767. protected $ur_form;
  768. /**
  769. * Names specifying additional signature-related usage rights for the document.
  770. * @access protected
  771. * @since 2.9.000 (2008-03-26)
  772. */
  773. protected $ur_signature;
  774. /**
  775. * Dot Per Inch Document Resolution (do not change)
  776. * @access protected
  777. * @since 3.0.000 (2008-03-27)
  778. */
  779. protected $dpi = 72;
  780. /**
  781. * Array of page numbers were a new page group was started
  782. * @access protected
  783. * @since 3.0.000 (2008-03-27)
  784. */
  785. protected $newpagegroup = array();
  786. /**
  787. * Contains the number of pages of the groups
  788. * @access protected
  789. * @since 3.0.000 (2008-03-27)
  790. */
  791. protected $pagegroups;
  792. /**
  793. * Contains the alias of the current page group
  794. * @access protected
  795. * @since 3.0.000 (2008-03-27)
  796. */
  797. protected $currpagegroup;
  798. /**
  799. * Restrict the rendering of some elements to screen or printout.
  800. * @access protected
  801. * @since 3.0.000 (2008-03-27)
  802. */
  803. protected $visibility = 'all';
  804. /**
  805. * Print visibility.
  806. * @access protected
  807. * @since 3.0.000 (2008-03-27)
  808. */
  809. protected $n_ocg_print;
  810. /**
  811. * View visibility.
  812. * @access protected
  813. * @since 3.0.000 (2008-03-27)
  814. */
  815. protected $n_ocg_view;
  816. /**
  817. * Array of transparency objects and parameters.
  818. * @access protected
  819. * @since 3.0.000 (2008-03-27)
  820. */
  821. protected $extgstates;
  822. /**
  823. * Set the default JPEG compression quality (1-100)
  824. * @access protected
  825. * @since 3.0.000 (2008-03-27)
  826. */
  827. protected $jpeg_quality;
  828. /**
  829. * Default cell height ratio.
  830. * @access protected
  831. * @since 3.0.014 (2008-05-23)
  832. */
  833. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  834. /**
  835. * PDF viewer preferences.
  836. * @access protected
  837. * @since 3.1.000 (2008-06-09)
  838. */
  839. protected $viewer_preferences;
  840. /**
  841. * A name object specifying how the document should be displayed when opened.
  842. * @access protected
  843. * @since 3.1.000 (2008-06-09)
  844. */
  845. protected $PageMode;
  846. /**
  847. * Array for storing gradient information.
  848. * @access protected
  849. * @since 3.1.000 (2008-06-09)
  850. */
  851. protected $gradients = array();
  852. /**
  853. * Array used to store positions inside the pages buffer.
  854. * keys are the page numbers
  855. * @access protected
  856. * @since 3.2.000 (2008-06-26)
  857. */
  858. protected $intmrk = array();
  859. /**
  860. * Array used to store footer positions of each page.
  861. * @access protected
  862. * @since 3.2.000 (2008-07-01)
  863. */
  864. protected $footerpos = array();
  865. /**
  866. * Array used to store footer lenght of each page.
  867. * @access protected
  868. * @since 4.0.014 (2008-07-29)
  869. */
  870. protected $footerlen = array();
  871. /**
  872. * True if a newline is created.
  873. * @access protected
  874. * @since 3.2.000 (2008-07-01)
  875. */
  876. protected $newline = true;
  877. /**
  878. * End position of the latest inserted line
  879. * @access protected
  880. * @since 3.2.000 (2008-07-01)
  881. */
  882. protected $endlinex = 0;
  883. /**
  884. * PDF string for last line width
  885. * @access protected
  886. * @since 4.0.006 (2008-07-16)
  887. */
  888. protected $linestyleWidth = '';
  889. /**
  890. * PDF string for last line width
  891. * @access protected
  892. * @since 4.0.006 (2008-07-16)
  893. */
  894. protected $linestyleCap = '0 J';
  895. /**
  896. * PDF string for last line width
  897. * @access protected
  898. * @since 4.0.006 (2008-07-16)
  899. */
  900. protected $linestyleJoin = '0 j';
  901. /**
  902. * PDF string for last line width
  903. * @access protected
  904. * @since 4.0.006 (2008-07-16)
  905. */
  906. protected $linestyleDash = '[] 0 d';
  907. /**
  908. * True if marked-content sequence is open
  909. * @access protected
  910. * @since 4.0.013 (2008-07-28)
  911. */
  912. protected $openMarkedContent = false;
  913. /**
  914. * Count the latest inserted vertical spaces on HTML
  915. * @access protected
  916. * @since 4.0.021 (2008-08-24)
  917. */
  918. protected $htmlvspace = 0;
  919. /**
  920. * Array of Spot colors
  921. * @access protected
  922. * @since 4.0.024 (2008-09-12)
  923. */
  924. protected $spot_colors = array();
  925. /**
  926. * Symbol used for HTML unordered list items
  927. * @access protected
  928. * @since 4.0.028 (2008-09-26)
  929. */
  930. protected $lisymbol = '';
  931. /**
  932. * String used to mark the beginning and end of EPS image blocks
  933. * @access protected
  934. * @since 4.1.000 (2008-10-18)
  935. */
  936. protected $epsmarker = 'x#!#EPS#!#x';
  937. /**
  938. * Array of transformation matrix
  939. * @access protected
  940. * @since 4.2.000 (2008-10-29)
  941. */
  942. protected $transfmatrix = array();
  943. /**
  944. * Booklet mode for double-sided pages
  945. * @access protected
  946. * @since 4.2.000 (2008-10-29)
  947. */
  948. protected $booklet = false;
  949. /**
  950. * Epsilon value used for float calculations
  951. * @access protected
  952. * @since 4.2.000 (2008-10-29)
  953. */
  954. protected $feps = 0.001;
  955. /**
  956. * Array used for custom vertical spaces for HTML tags
  957. * @access protected
  958. * @since 4.2.001 (2008-10-30)
  959. */
  960. protected $tagvspaces = array();
  961. /**
  962. * @var HTML PARSER: custom indent amount for lists.
  963. * Negative value means disabled.
  964. * @access protected
  965. * @since 4.2.007 (2008-11-12)
  966. */
  967. protected $customlistindent = -1;
  968. /**
  969. * @var if true keeps the border open for the cell sides that cross the page.
  970. * @access protected
  971. * @since 4.2.010 (2008-11-14)
  972. */
  973. protected $opencell = true;
  974. /**
  975. * @var array of files to embedd
  976. * @access protected
  977. * @since 4.4.000 (2008-12-07)
  978. */
  979. protected $embeddedfiles = array();
  980. /**
  981. * @var boolean true when inside html pre tag
  982. * @access protected
  983. * @since 4.4.001 (2008-12-08)
  984. */
  985. protected $premode = false;
  986. /**
  987. * Array used to store positions of graphics transformation blocks inside the page buffer.
  988. * keys are the page numbers
  989. * @access protected
  990. * @since 4.4.002 (2008-12-09)
  991. */
  992. protected $transfmrk = array();
  993. /**
  994. * Default color for html links
  995. * @access protected
  996. * @since 4.4.003 (2008-12-09)
  997. */
  998. protected $htmlLinkColorArray = array(0, 0, 255);
  999. /**
  1000. * Default font style to add to html links
  1001. * @access protected
  1002. * @since 4.4.003 (2008-12-09)
  1003. */
  1004. protected $htmlLinkFontStyle = 'U';
  1005. /**
  1006. * Counts the number of pages.
  1007. * @access protected
  1008. * @since 4.5.000 (2008-12-31)
  1009. */
  1010. protected $numpages = 0;
  1011. /**
  1012. * Array containing page lenghts in bytes.
  1013. * @access protected
  1014. * @since 4.5.000 (2008-12-31)
  1015. */
  1016. protected $pagelen = array();
  1017. /**
  1018. * Counts the number of pages.
  1019. * @access protected
  1020. * @since 4.5.000 (2008-12-31)
  1021. */
  1022. protected $numimages = 0;
  1023. /**
  1024. * Store the image keys.
  1025. * @access protected
  1026. * @since 4.5.000 (2008-12-31)
  1027. */
  1028. protected $imagekeys = array();
  1029. /**
  1030. * Lenght of the buffer in bytes.
  1031. * @access protected
  1032. * @since 4.5.000 (2008-12-31)
  1033. */
  1034. protected $bufferlen = 0;
  1035. /**
  1036. * If true enables disk caching.
  1037. * @access protected
  1038. * @since 4.5.000 (2008-12-31)
  1039. */
  1040. protected $diskcache = false;
  1041. /**
  1042. * Counts the number of fonts.
  1043. * @access protected
  1044. * @since 4.5.000 (2009-01-02)
  1045. */
  1046. protected $numfonts = 0;
  1047. /**
  1048. * Store the font keys.
  1049. * @access protected
  1050. * @since 4.5.000 (2009-01-02)
  1051. */
  1052. protected $fontkeys = array();
  1053. /**
  1054. * Store the fage status (true when opened, false when closed).
  1055. * @access protected
  1056. * @since 4.5.000 (2009-01-02)
  1057. */
  1058. protected $pageopen = array();
  1059. /**
  1060. * Default monospaced font
  1061. * @access protected
  1062. * @since 4.5.025 (2009-03-10)
  1063. */
  1064. protected $default_monospaced_font = 'courier';
  1065. /**
  1066. * Used to store a cloned copy of the current class object
  1067. * @access protected
  1068. * @since 4.5.029 (2009-03-19)
  1069. */
  1070. protected $objcopy;
  1071. /**
  1072. * Array used to store the lenghts of cache files
  1073. * @access protected
  1074. * @since 4.5.029 (2009-03-19)
  1075. */
  1076. protected $cache_file_lenght = array();
  1077. /**
  1078. * Table header content to be repeated on each new page
  1079. * @access protected
  1080. * @since 4.5.030 (2009-03-20)
  1081. */
  1082. protected $thead = '';
  1083. /**
  1084. * Distance between the top of page and end of table headers on a new page.
  1085. * @access protected
  1086. * @since 4.5.030 (2009-03-20)
  1087. */
  1088. protected $theadMargin = '';
  1089. /**
  1090. * Cache array for UTF8StringToArray() method.
  1091. * @access protected
  1092. * @since 4.5.037 (2009-04-07)
  1093. */
  1094. protected $cache_UTF8StringToArray = array();
  1095. /**
  1096. * Maximum size of cache array used for UTF8StringToArray() method.
  1097. * @access protected
  1098. * @since 4.5.037 (2009-04-07)
  1099. */
  1100. protected $cache_maxsize_UTF8StringToArray = 8;
  1101. /**
  1102. * Current size of cache array used for UTF8StringToArray() method.
  1103. * @access protected
  1104. * @since 4.5.037 (2009-04-07)
  1105. */
  1106. protected $cache_size_UTF8StringToArray = 0;
  1107. /**
  1108. * If true enables document signing
  1109. * @access protected
  1110. * @since 4.6.005 (2009-04-24)
  1111. */
  1112. protected $sign = false;
  1113. /**
  1114. * Signature data
  1115. * @access protected
  1116. * @since 4.6.005 (2009-04-24)
  1117. */
  1118. protected $signature_data = array();
  1119. /**
  1120. * Signature max lenght
  1121. * @access protected
  1122. * @since 4.6.005 (2009-04-24)
  1123. */
  1124. protected $signature_max_lenght = 5120;
  1125. /**
  1126. * Regular expression used to find blank characters used for word-wrapping.
  1127. * @access protected
  1128. * @since 4.6.006 (2009-04-28)
  1129. */
  1130. protected $re_spaces = '/[\s\p{Z}\p{Lo}]/';
  1131. //------------------------------------------------------------
  1132. // METHODS
  1133. //------------------------------------------------------------
  1134. /**
  1135. * This is the class constructor.
  1136. * It allows to set up the page format, the orientation and
  1137. * the measure unit used in all the methods (except for the font sizes).
  1138. * @since 1.0
  1139. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
  1140. * @param string $unit 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.
  1141. * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
  1142. * @param boolean $unicode TRUE means that the input text is unicode (default = true)
  1143. * @param boolean $diskcache if TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
  1144. * @param String $encoding charset encoding; default is UTF-8
  1145. * @access public
  1146. */
  1147. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false) {
  1148. /* Set internal character encoding to ASCII */
  1149. if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
  1150. $this->internal_encoding = mb_internal_encoding();
  1151. mb_internal_encoding('ASCII');
  1152. }
  1153. // set disk caching
  1154. $this->diskcache = $diskcache ? true : false;
  1155. // set language direction
  1156. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  1157. $this->tmprtl = false;
  1158. //Some checks
  1159. $this->_dochecks();
  1160. //Initialization of properties
  1161. $this->isunicode = $unicode;
  1162. $this->page = 0;
  1163. $this->transfmrk[0] = array();
  1164. $this->pagedim = array();
  1165. $this->n = 2;
  1166. $this->buffer = '';
  1167. $this->pages = array();
  1168. $this->state = 0;
  1169. $this->fonts = array();
  1170. $this->FontFiles = array();
  1171. $this->diffs = array();
  1172. $this->images = array();
  1173. $this->links = array();
  1174. $this->gradients = array();
  1175. $this->InFooter = false;
  1176. $this->lasth = 0;
  1177. $this->FontFamily = 'helvetica';
  1178. $this->FontStyle = '';
  1179. $this->FontSizePt = 12;
  1180. $this->underline = false;
  1181. $this->linethrough = false;
  1182. $this->DrawColor = '0 G';
  1183. $this->FillColor = '0 g';
  1184. $this->TextColor = '0 g';
  1185. $this->ColorFlag = false;
  1186. // encryption values
  1187. $this->encrypted = false;
  1188. $this->last_rc4_key = '';
  1189. $this->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";
  1190. //Standard Unicode fonts
  1191. $this->CoreFonts = array(
  1192. 'courier'=>'Courier',
  1193. 'courierB'=>'Courier-Bold',
  1194. 'courierI'=>'Courier-Oblique',
  1195. 'courierBI'=>'Courier-BoldOblique',
  1196. 'helvetica'=>'Helvetica',
  1197. 'helveticaB'=>'Helvetica-Bold',
  1198. 'helveticaI'=>'Helvetica-Oblique',
  1199. 'helveticaBI'=>'Helvetica-BoldOblique',
  1200. 'times'=>'Times-Roman',
  1201. 'timesB'=>'Times-Bold',
  1202. 'timesI'=>'Times-Italic',
  1203. 'timesBI'=>'Times-BoldItalic',
  1204. 'symbol'=>'Symbol',
  1205. 'zapfdingbats'=>'ZapfDingbats'
  1206. );
  1207. //Set scale factor
  1208. $this->setPageUnit($unit);
  1209. // set page format and orientation
  1210. $this->setPageFormat($format, $orientation);
  1211. //Page margins (1 cm)
  1212. $margin = 28.35 / $this->k;
  1213. $this->SetMargins($margin, $margin);
  1214. //Interior cell margin
  1215. $this->cMargin = $margin / 10;
  1216. //Line width (0.2 mm)
  1217. $this->LineWidth = 0.57 / $this->k;
  1218. $this->linestyleWidth = sprintf('%.2F w', ($this->LineWidth * $this->k));
  1219. $this->linestyleCap = '0 J';
  1220. $this->linestyleJoin = '0 j';
  1221. $this->linestyleDash = '[] 0 d';
  1222. //Automatic page break
  1223. $this->SetAutoPageBreak(true, (2 * $margin));
  1224. //Full width display mode
  1225. $this->SetDisplayMode('fullwidth');
  1226. //Compression
  1227. $this->SetCompression(true);
  1228. //Set default PDF version number
  1229. $this->PDFVersion = '1.7';
  1230. $this->encoding = $encoding;
  1231. $this->HREF = array();
  1232. $this->getFontsList();
  1233. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1234. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1235. $this->extgstates = array();
  1236. // user's rights
  1237. $this->sign = false;
  1238. $this->ur = false;
  1239. $this->ur_document = '/FullSave';
  1240. $this->ur_annots = '/Create/Delete/Modify/Copy/Import/Export';
  1241. $this->ur_form = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1242. $this->ur_signature = '/Modify';
  1243. // set default JPEG quality
  1244. $this->jpeg_quality = 75;
  1245. // initialize some settings
  1246. $this->utf8Bidi(array(''), '');
  1247. // set default font
  1248. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1249. // check if PCRE Unicode support is enabled
  1250. if (@preg_match('/\pL/u', 'a') == 1) {
  1251. // PCRE unicode support is turned ON
  1252. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  1253. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  1254. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  1255. $this->re_spaces = '/[\s\p{Z}\p{Lo}]/';
  1256. } else {
  1257. // PCRE unicode support is turned OFF
  1258. $this->re_spaces = '/[\s]/';
  1259. }
  1260. }
  1261. /**
  1262. * Default destructor.
  1263. * @access public
  1264. * @since 1.53.0.TC016
  1265. */
  1266. public function __destruct() {
  1267. // restore internal encoding
  1268. if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
  1269. mb_internal_encoding($this->internal_encoding);
  1270. }
  1271. // unset all class variables
  1272. $this->_destroy(true);
  1273. }
  1274. /**
  1275. * Set the units of measure for the document.
  1276. * @param string $unit 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.
  1277. * @access public
  1278. * @since 3.0.015 (2008-06-06)
  1279. */
  1280. public function setPageUnit($unit) {
  1281. //Set scale factor
  1282. switch (strtolower($unit)) {
  1283. // points
  1284. case 'px':
  1285. case 'pt': {
  1286. $this->k = 1;
  1287. break;
  1288. }
  1289. // millimeters
  1290. case 'mm': {
  1291. $this->k = $this->dpi / 25.4;
  1292. break;
  1293. }
  1294. // centimeters
  1295. case 'cm': {
  1296. $this->k = $this->dpi / 2.54;
  1297. break;
  1298. }
  1299. // inches
  1300. case 'in': {
  1301. $this->k = $this->dpi;
  1302. break;
  1303. }
  1304. // unsupported unit
  1305. default : {
  1306. $this->Error('Incorrect unit: '.$unit);
  1307. break;
  1308. }
  1309. }
  1310. if (isset($this->CurOrientation)) {
  1311. $this->setPageOrientation($this->CurOrientation);
  1312. }
  1313. }
  1314. /**
  1315. * Set the page format
  1316. * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
  1317. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  1318. * @access public
  1319. * @since 3.0.015 (2008-06-06)
  1320. */
  1321. public function setPageFormat($format, $orientation='P') {
  1322. //Page format
  1323. if (is_string($format)) {
  1324. // Page formats (45 standard ISO paper formats and 4 american common formats).
  1325. // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
  1326. switch (strtoupper($format)) {
  1327. case '4A0': {$format = array(4767.87,6740.79); break;}
  1328. case '2A0': {$format = array(3370.39,4767.87); break;}
  1329. case 'A0': {$format = array(2383.94,3370.39); break;}
  1330. case 'A1': {$format = array(1683.78,2383.94); break;}
  1331. case 'A2': {$format = array(1190.55,1683.78); break;}
  1332. case 'A3': {$format = array(841.89,1190.55); break;}
  1333. case 'A4': default: {$format = array(595.28,841.89); break;}
  1334. case 'A5': {$format = array(419.53,595.28); break;}
  1335. case 'A6': {$format = array(297.64,419.53); break;}
  1336. case 'A7': {$format = array(209.76,297.64); break;}
  1337. case 'A8': {$format = array(147.40,209.76); break;}
  1338. case 'A9': {$format = array(104.88,147.40); break;}
  1339. case 'A10': {$format = array(73.70,104.88); break;}
  1340. case 'B0': {$format = array(2834.65,4008.19); break;}
  1341. case 'B1': {$format = array(2004.09,2834.65); break;}
  1342. case 'B2': {$format = array(1417.32,2004.09); break;}
  1343. case 'B3': {$format = array(1000.63,1417.32); break;}
  1344. case 'B4': {$format = array(708.66,1000.63); break;}
  1345. case 'B5': {$format = array(498.90,708.66); break;}
  1346. case 'B6': {$format = array(354.33,498.90); break;}
  1347. case 'B7': {$format = array(249.45,354.33); break;}
  1348. case 'B8': {$format = array(175.75,249.45); break;}
  1349. case 'B9': {$format = array(124.72,175.75); break;}
  1350. case 'B10': {$format = array(87.87,124.72); break;}
  1351. case 'C0': {$format = array(2599.37,3676.54); break;}
  1352. case 'C1': {$format = array(1836.85,2599.37); break;}
  1353. case 'C2': {$format = array(1298.27,1836.85); break;}
  1354. case 'C3': {$format = array(918.43,1298.27); break;}
  1355. case 'C4': {$format = array(649.13,918.43); break;}
  1356. case 'C5': {$format = array(459.21,649.13); break;}
  1357. case 'C6': {$format = array(323.15,459.21); break;}
  1358. case 'C7': {$format = array(229.61,323.15); break;}
  1359. case 'C8': {$format = array(161.57,229.61); break;}
  1360. case 'C9': {$format = array(113.39,161.57); break;}
  1361. case 'C10': {$format = array(79.37,113.39); break;}
  1362. case 'RA0': {$format = array(2437.80,3458.27); break;}
  1363. case 'RA1': {$format = array(1729.13,2437.80); break;}
  1364. case 'RA2': {$format = array(1218.90,1729.13); break;}
  1365. case 'RA3': {$format = array(864.57,1218.90); break;}
  1366. case 'RA4': {$format = array(609.45,864.57); break;}
  1367. case 'SRA0': {$format = array(2551.18,3628.35); break;}
  1368. case 'SRA1': {$format = array(1814.17,2551.18); break;}
  1369. case 'SRA2': {$format = array(1275.59,1814.17); break;}
  1370. case 'SRA3': {$format = array(907.09,1275.59); break;}
  1371. case 'SRA4': {$format = array(637.80,907.09); break;}
  1372. case 'LETTER': {$format = array(612.00,792.00); break;}
  1373. case 'LEGAL': {$format = array(612.00,1008.00); break;}
  1374. case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
  1375. case 'FOLIO': {$format = array(612.00,936.00); break;}
  1376. }
  1377. $this->fwPt = $format[0];
  1378. $this->fhPt = $format[1];
  1379. } else {
  1380. $this->fwPt = $format[0] * $this->k;
  1381. $this->fhPt = $format[1] * $this->k;
  1382. }
  1383. $this->setPageOrientation($orientation);
  1384. }
  1385. /**
  1386. * Set page orientation.
  1387. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  1388. * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
  1389. * @param float $bottommargin bottom margin of the page.
  1390. * @access public
  1391. * @since 3.0.015 (2008-06-06)
  1392. */
  1393. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  1394. $orientation = strtoupper($orientation);
  1395. if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
  1396. $this->CurOrientation = 'P';
  1397. $this->wPt = $this->fwPt;
  1398. $this->hPt = $this->fhPt;
  1399. } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
  1400. $this->CurOrientation = 'L';
  1401. $this->wPt = $this->fhPt;
  1402. $this->hPt = $this->fwPt;
  1403. } else {
  1404. $this->Error('Incorrect orientation: '.$orientation);
  1405. }
  1406. $this->w = $this->wPt / $this->k;
  1407. $this->h = $this->hPt / $this->k;
  1408. if ($this->empty_string($autopagebreak)) {
  1409. if (isset($this->AutoPageBreak)) {
  1410. $autopagebreak = $this->AutoPageBreak;
  1411. } else {
  1412. $autopagebreak = true;
  1413. }
  1414. }
  1415. if ($this->empty_string($bottommargin)) {
  1416. if (isset($this->bMargin)) {
  1417. $bottommargin = $this->bMargin;
  1418. } else {
  1419. // default value = 2 cm
  1420. $bottommargin = 2 * 28.35 / $this->k;
  1421. }
  1422. }
  1423. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  1424. // store page dimensions
  1425. $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'wk' => $this->w, 'hk' => $this->h, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation, 'olm' => $this->original_lMargin, 'orm' => $this->original_rMargin);
  1426. }
  1427. /**
  1428. * Enable or disable Right-To-Left language mode
  1429. * @param Boolean $enable if true enable Right-To-Left language mode.
  1430. * @access public
  1431. * @since 2.0.000 (2008-01-03)
  1432. */
  1433. public function setRTL($enable) {
  1434. $this->rtl = $enable ? true : false;
  1435. $this->tmprtl = false;
  1436. }
  1437. /**
  1438. * Return the RTL status
  1439. * @return boolean
  1440. * @access public
  1441. * @since 4.0.012 (2008-07-24)
  1442. */
  1443. public function getRTL() {
  1444. return $this->rtl;
  1445. }
  1446. /**
  1447. * Force temporary RTL language direction
  1448. * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
  1449. * @access public
  1450. * @since 2.1.000 (2008-01-09)
  1451. */
  1452. public function setTempRTL($mode) {
  1453. switch ($mode) {
  1454. case false:
  1455. case 'L':
  1456. case 'R': {
  1457. $this->tmprtl = $mode;
  1458. }
  1459. }
  1460. }
  1461. /**
  1462. * Set the last cell height.
  1463. * @param float $h cell height.
  1464. * @author Nicola Asuni
  1465. * @access public
  1466. * @since 1.53.0.TC034
  1467. */
  1468. public function setLastH($h) {
  1469. $this->lasth = $h;
  1470. }
  1471. /**
  1472. * Get the last cell height.
  1473. * @return last cell height
  1474. * @access public
  1475. * @since 4.0.017 (2008-08-05)
  1476. */
  1477. public function getLastH() {
  1478. return $this->lasth;
  1479. }
  1480. /**
  1481. * Set the adjusting factor to convert pixels to user units.
  1482. * @param float $scale adjusting factor to convert pixels to user units.
  1483. * @author Nicola Asuni
  1484. * @access public
  1485. * @since 1.5.2
  1486. */
  1487. public function setImageScale($scale) {
  1488. $this->imgscale = $scale;
  1489. }
  1490. /**
  1491. * Returns the adjusting factor to convert pixels to user units.
  1492. * @return float adjusting factor to convert pixels to user units.
  1493. * @author Nicola Asuni
  1494. * @access public
  1495. * @since 1.5.2
  1496. */
  1497. public function getImageScale() {
  1498. return $this->imgscale;
  1499. }
  1500. /**
  1501. * Returns an array of page dimensions:
  1502. * <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_points</li><li>$this->pagedim[$this->page]['hk'] => height</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></ul>
  1503. * @param int $pagenum page number (empty = current page)
  1504. * @return array of page dimensions.
  1505. * @author Nicola Asuni
  1506. * @access public
  1507. * @since 4.5.027 (2009-03-16)
  1508. */
  1509. public function getPageDimensions($pagenum='') {
  1510. if (empty($pagenum)) {
  1511. $pagenum = $this->page;
  1512. }
  1513. return $this->pagedim[$pagenum];
  1514. }
  1515. /**
  1516. * Returns the page width in units.
  1517. * @param int $pagenum page number (empty = current page)
  1518. * @return int page width.
  1519. * @author Nicola Asuni
  1520. * @access public
  1521. * @since 1.5.2
  1522. * @see getPageDimensions()
  1523. */
  1524. public function getPageWidth($pagenum='') {
  1525. if (empty($pagenum)) {
  1526. return $this->w;
  1527. }
  1528. return $this->pagedim[$pagenum]['w'];
  1529. }
  1530. /**
  1531. * Returns the page height in units.
  1532. * @param int $pagenum page number (empty = current page)
  1533. * @return int page height.
  1534. * @author Nicola Asuni
  1535. * @access public
  1536. * @since 1.5.2
  1537. * @see getPageDimensions()
  1538. */
  1539. public function getPageHeight($pagenum='') {
  1540. if (empty($pagenum)) {
  1541. return $this->h;
  1542. }
  1543. return $this->pagedim[$pagenum]['h'];
  1544. }
  1545. /**
  1546. * Returns the page break margin.
  1547. * @param int $pagenum page number (empty = current page)
  1548. * @return int page break margin.
  1549. * @author Nicola Asuni
  1550. * @access public
  1551. * @since 1.5.2
  1552. * @see getPageDimensions()
  1553. */
  1554. public function getBreakMargin($pagenum='') {
  1555. if (empty($pagenum)) {
  1556. return $this->bMargin;
  1557. }
  1558. return $this->pagedim[$pagenum]['bm'];
  1559. }
  1560. /**
  1561. * Returns the scale factor (number of points in user unit).
  1562. * @return int scale factor.
  1563. * @author Nicola Asuni
  1564. * @access public
  1565. * @since 1.5.2
  1566. */
  1567. public function getScaleFactor() {
  1568. return $this->k;
  1569. }
  1570. /**
  1571. * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
  1572. * @param float $left Left margin.
  1573. * @param float $top Top margin.
  1574. * @param float $right Right margin. Default value is the left one.
  1575. * @access public
  1576. * @since 1.0
  1577. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  1578. */
  1579. public function SetMargins($left, $top, $right=-1) {
  1580. //Set left, top and right margins
  1581. $this->lMargin = $left;
  1582. $this->tMargin = $top;
  1583. if ($right == -1) {
  1584. $right = $left;
  1585. }
  1586. $this->rMargin = $right;
  1587. }
  1588. /**
  1589. * 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.
  1590. * @param float $margin The margin.
  1591. * @access public
  1592. * @since 1.4
  1593. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  1594. */
  1595. public function SetLeftMargin($margin) {
  1596. //Set left margin
  1597. $this->lMargin=$margin;
  1598. if (($this->page > 0) AND ($this->x < $margin)) {
  1599. $this->x = $margin;
  1600. }
  1601. }
  1602. /**
  1603. * Defines the top margin. The method can be called before creating the first page.
  1604. * @param float $margin The margin.
  1605. * @access public
  1606. * @since 1.5
  1607. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  1608. */
  1609. public function SetTopMargin($margin) {
  1610. //Set top margin
  1611. $this->tMargin=$margin;
  1612. if (($this->page > 0) AND ($this->y < $margin)) {
  1613. $this->y = $margin;
  1614. }
  1615. }
  1616. /**
  1617. * Defines the right margin. The method can be called before creating the first page.
  1618. * @param float $margin The margin.
  1619. * @access public
  1620. * @since 1.5
  1621. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  1622. */
  1623. public function SetRightMargin($margin) {
  1624. $this->rMargin=$margin;
  1625. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  1626. $this->x = $this->w - $margin;
  1627. }
  1628. }
  1629. /**
  1630. * Set the internal Cell padding.
  1631. * @param float $pad internal padding.
  1632. * @access public
  1633. * @since 2.1.000 (2008-01-09)
  1634. * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  1635. */
  1636. public function SetCellPadding($pad) {
  1637. $this->cMargin = $pad;
  1638. }
  1639. /**
  1640. * 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.
  1641. * @param boolean $auto Boolean indicating if mode should be on or off.
  1642. * @param float $margin Distance from the bottom of the page.
  1643. * @access public
  1644. * @since 1.0
  1645. * @see Cell(), MultiCell(), AcceptPageBreak()
  1646. */
  1647. public function SetAutoPageBreak($auto, $margin=0) {
  1648. //Set auto page break mode and triggering margin
  1649. $this->AutoPageBreak = $auto;
  1650. $this->bMargin = $margin;
  1651. $this->PageBreakTrigger = $this->h - $margin;
  1652. }
  1653. /**
  1654. * Defines the way the document is to be displayed by the viewer.
  1655. * @param mixed $zoom 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>
  1656. * @param string $layout 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>
  1657. * @param string $mode 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>
  1658. * @access public
  1659. * @since 1.2
  1660. */
  1661. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  1662. //Set display mode in viewer
  1663. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  1664. $this->ZoomMode = $zoom;
  1665. } else {
  1666. $this->Error('Incorrect zoom display mode: '.$zoom);
  1667. }
  1668. switch ($layout) {
  1669. case 'default':
  1670. case 'single':
  1671. case 'SinglePage': {
  1672. $this->LayoutMode = 'SinglePage';
  1673. break;
  1674. }
  1675. case 'continuous':
  1676. case 'OneColumn': {
  1677. $this->LayoutMode = 'OneColumn';
  1678. break;
  1679. }
  1680. case 'two':
  1681. case 'TwoColumnLeft': {
  1682. $this->LayoutMode = 'TwoColumnLeft';
  1683. break;
  1684. }
  1685. case 'TwoColumnRight': {
  1686. $this->LayoutMode = 'TwoColumnRight';
  1687. break;
  1688. }
  1689. case 'TwoPageLeft': {
  1690. $this->LayoutMode = 'TwoPageLeft';
  1691. break;
  1692. }
  1693. case 'TwoPageRight': {
  1694. $this->LayoutMode = 'TwoPageRight';
  1695. break;
  1696. }
  1697. default: {
  1698. $this->LayoutMode = 'SinglePage';
  1699. }
  1700. }
  1701. switch ($mode) {
  1702. case 'UseNone': {
  1703. $this->PageMode = 'UseNone';
  1704. break;
  1705. }
  1706. case 'UseOutlines': {
  1707. $this->PageMode = 'UseOutlines';
  1708. break;
  1709. }
  1710. case 'UseThumbs': {
  1711. $this->PageMode = 'UseThumbs';
  1712. break;
  1713. }
  1714. case 'FullScreen': {
  1715. $this->PageMode = 'FullScreen';
  1716. break;
  1717. }
  1718. case 'UseOC': {
  1719. $this->PageMode = 'UseOC';
  1720. break;
  1721. }
  1722. case '': {
  1723. $this->PageMode = 'UseAttachments';
  1724. break;
  1725. }
  1726. default: {
  1727. $this->PageMode = 'UseNone';
  1728. }
  1729. }
  1730. }
  1731. /**
  1732. * 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.
  1733. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  1734. * @param boolean $compress Boolean indicating if compression must be enabled.
  1735. * @access public
  1736. * @since 1.4
  1737. */
  1738. public function SetCompression($compress) {
  1739. //Set page compression
  1740. if (function_exists('gzcompress')) {
  1741. $this->compress = $compress;
  1742. } else {
  1743. $this->compress = false;
  1744. }
  1745. }
  1746. /**
  1747. * Defines the title of the document.
  1748. * @param string $title The title.
  1749. * @access public
  1750. * @since 1.2
  1751. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  1752. */
  1753. public function SetTitle($title) {
  1754. //Title of document
  1755. $this->title = $title;
  1756. }
  1757. /**
  1758. * Defines the subject of the document.
  1759. * @param string $subject The subject.
  1760. * @access public
  1761. * @since 1.2
  1762. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  1763. */
  1764. public function SetSubject($subject) {
  1765. //Subject of document
  1766. $this->subject = $subject;
  1767. }
  1768. /**
  1769. * Defines the author of the document.
  1770. * @param string $author The name of the author.
  1771. * @access public
  1772. * @since 1.2
  1773. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  1774. */
  1775. public function SetAuthor($author) {
  1776. //Author of document
  1777. $this->author = $author;
  1778. }
  1779. /**
  1780. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  1781. * @param string $keywords The list of keywords.
  1782. * @access public
  1783. * @since 1.2
  1784. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  1785. */
  1786. public function SetKeywords($keywords) {
  1787. //Keywords of document
  1788. $this->keywords = $keywords;
  1789. }
  1790. /**
  1791. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  1792. * @param string $creator The name of the creator.
  1793. * @access public
  1794. * @since 1.2
  1795. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  1796. */
  1797. public function SetCreator($creator) {
  1798. //Creator of document
  1799. $this->creator = $creator;
  1800. }
  1801. /**
  1802. * 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.
  1803. * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
  1804. * @param string $msg The error message
  1805. * @access public
  1806. * @since 1.0
  1807. */
  1808. public function Error($msg) {
  1809. // unset all class variables
  1810. $this->_destroy(true);
  1811. // exit program and print error
  1812. die('<strong>TCPDF ERROR: </strong>'.$msg);
  1813. }
  1814. /**
  1815. * This method begins the generation of the PDF document.
  1816. * It is not necessary to call it explicitly because AddPage() does it automatically.
  1817. * Note: no page is created by this method
  1818. * @access public
  1819. * @since 1.0
  1820. * @see AddPage(), Close()
  1821. */
  1822. public function Open() {
  1823. //Begin document
  1824. $this->state = 1;
  1825. }
  1826. /**
  1827. * Terminates the PDF document.
  1828. * It is not necessary to call this method explicitly because Output() does it automatically.
  1829. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  1830. * @access public
  1831. * @since 1.0
  1832. * @see Open(), Output()
  1833. */
  1834. public function Close() {
  1835. if ($this->state == 3) {
  1836. return;
  1837. }
  1838. if ($this->page == 0) {
  1839. $this->AddPage();
  1840. }
  1841. // close page
  1842. $this->endPage();
  1843. // close document
  1844. $this->_enddoc();
  1845. // unset all class variables (except critical ones)
  1846. $this->_destroy(false);
  1847. }
  1848. /**
  1849. * Move pointer at the specified document page and update page dimensions.
  1850. * @param int $pnum page number
  1851. * @param boolean $resetmargins if true reset left, right, top margins and Y position.
  1852. * @access public
  1853. * @since 2.1.000 (2008-01-07)
  1854. * @see getPage(), lastpage(), getNumPages()
  1855. */
  1856. public function setPage($pnum, $resetmargins=false) {
  1857. if ($pnum == $this->page) {
  1858. return;
  1859. }
  1860. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  1861. $this->state = 2;
  1862. // save current graphic settings
  1863. //$gvars = $this->getGraphicVars();
  1864. $oldpage = $this->page;
  1865. $this->page = $pnum;
  1866. $this->wPt = $this->pagedim[$this->page]['w'];
  1867. $this->hPt = $this->pagedim[$this->page]['h'];
  1868. $this->w = $this->wPt / $this->k;
  1869. $this->h = $this->hPt / $this->k;
  1870. $this->tMargin = $this->pagedim[$this->page]['tm'];
  1871. $this->bMargin = $this->pagedim[$this->page]['bm'];
  1872. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  1873. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  1874. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  1875. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  1876. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  1877. // restore graphic settings
  1878. //$this->setGraphicVars($gvars);
  1879. if ($resetmargins) {
  1880. $this->lMargin = $this->pagedim[$this->page]['olm'];
  1881. $this->rMargin = $this->pagedim[$this->page]['orm'];
  1882. $this->SetY($this->tMargin);
  1883. } else {
  1884. // account for booklet mode
  1885. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  1886. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  1887. $this->lMargin += $deltam;
  1888. $this->rMargin -= $deltam;
  1889. }
  1890. }
  1891. } else {
  1892. $this->Error('Wrong page number on setPage() function.');
  1893. }
  1894. }
  1895. /**
  1896. * Reset pointer to the last document page.
  1897. * @param boolean $resetmargins if true reset left, right, top margins and Y position.
  1898. * @access public
  1899. * @since 2.0.000 (2008-01-04)
  1900. * @see setPage(), getPage(), getNumPages()
  1901. */
  1902. public function lastPage($resetmargins=false) {
  1903. $this->setPage($this->getNumPages(), $resetmargins);
  1904. }
  1905. /**
  1906. * Get current document page number.
  1907. * @return int page number
  1908. * @access public
  1909. * @since 2.1.000 (2008-01-07)
  1910. * @see setPage(), lastpage(), getNumPages()
  1911. */
  1912. public function getPage() {
  1913. return $this->page;
  1914. }
  1915. /**
  1916. * Get the total number of insered pages.
  1917. * @return int number of pages
  1918. * @access public
  1919. * @since 2.1.000 (2008-01-07)
  1920. * @see setPage(), getPage(), lastpage()
  1921. */
  1922. public function getNumPages() {
  1923. return $this->numpages;
  1924. }
  1925. /**
  1926. * 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).
  1927. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  1928. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  1929. * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
  1930. * @access public
  1931. * @since 1.0
  1932. * @see startPage(), endPage()
  1933. */
  1934. public function AddPage($orientation='', $format='') {
  1935. if (!isset($this->original_lMargin)) {
  1936. $this->original_lMargin = $this->lMargin;
  1937. }
  1938. if (!isset($this->original_rMargin)) {
  1939. $this->original_rMargin = $this->rMargin;
  1940. }
  1941. // terminate previous page
  1942. $this->endPage();
  1943. // start new page
  1944. $this->startPage($orientation, $format);
  1945. }
  1946. /**
  1947. * Terminate the current page
  1948. * @access protected
  1949. * @since 4.2.010 (2008-11-14)
  1950. * @see startPage(), AddPage()
  1951. */
  1952. protected function endPage() {
  1953. // check if page is already closed
  1954. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  1955. return;
  1956. }
  1957. $this->InFooter = true;
  1958. // print page footer
  1959. $this->setFooter();
  1960. // close page
  1961. $this->_endpage();
  1962. // mark page as closed
  1963. $this->pageopen[$this->page] = false;
  1964. $this->InFooter = false;
  1965. }
  1966. /**
  1967. * Starts a new page to the document. The page must be closed using the endPage() function.
  1968. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  1969. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  1970. * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
  1971. * @access protected
  1972. * @since 4.2.010 (2008-11-14)
  1973. * @see endPage(), AddPage()
  1974. */
  1975. protected function startPage($orientation='', $format='') {
  1976. if ($this->numpages > $this->page) {
  1977. // this page has been already added
  1978. $this->setPage($this->page + 1);
  1979. $this->SetY($this->tMargin);
  1980. return;
  1981. }
  1982. // start a new page
  1983. if ($this->state == 0) {
  1984. $this->Open();
  1985. }
  1986. ++$this->numpages;
  1987. $this->swapMargins($this->booklet);
  1988. // save current graphic settings
  1989. $gvars = $this->getGraphicVars();
  1990. // start new page
  1991. $this->_beginpage($orientation, $format);
  1992. // mark page as open
  1993. $this->pageopen[$this->page] = true;
  1994. // restore graphic settings
  1995. $this->setGraphicVars($gvars);
  1996. // mark this point
  1997. $this->setPageMark();
  1998. // print page header
  1999. $this->setHeader();
  2000. // restore graphic settings
  2001. $this->setGraphicVars($gvars);
  2002. // mark this point
  2003. $this->setPageMark();
  2004. // print table header (if any)
  2005. $this->setTableHeader();
  2006. }
  2007. /**
  2008. * Set start-writing mark on current page for multicell borders and fills.
  2009. * This function must be called after calling Image() function for a background image.
  2010. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  2011. * @access public
  2012. * @since 4.0.016 (2008-07-30)
  2013. */
  2014. public function setPageMark() {
  2015. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  2016. }
  2017. /**
  2018. * Set header data.
  2019. * @param string $ln header image logo
  2020. * @param string $lw header image logo width in mm
  2021. * @param string $ht string to print as title on document header
  2022. * @param string $hs string to print on document header
  2023. * @access public
  2024. */
  2025. public function setHeaderData($ln='', $lw=0, $ht='', $hs='') {
  2026. $this->header_logo = $ln;
  2027. $this->header_logo_width = $lw;
  2028. $this->header_title = $ht;
  2029. $this->header_string = $hs;
  2030. }
  2031. /**
  2032. * Returns header data:
  2033. * <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>
  2034. * @return array()
  2035. * @access public
  2036. * @since 4.0.012 (2008-07-24)
  2037. */
  2038. public function getHeaderData() {
  2039. $ret = array();
  2040. $ret['logo'] = $this->header_logo;
  2041. $ret['logo_width'] = $this->header_logo_width;
  2042. $ret['title'] = $this->header_title;
  2043. $ret['string'] = $this->header_string;
  2044. return $ret;
  2045. }
  2046. /**
  2047. * Set header margin.
  2048. * (minimum distance between header and top page margin)
  2049. * @param int $hm distance in user units
  2050. * @access public
  2051. */
  2052. public function setHeaderMargin($hm=10) {
  2053. $this->header_margin = $hm;
  2054. }
  2055. /**
  2056. * Returns header margin in user units.
  2057. * @return float
  2058. * @since 4.0.012 (2008-07-24)
  2059. * @access public
  2060. */
  2061. public function getHeaderMargin() {
  2062. return $this->header_margin;
  2063. }
  2064. /**
  2065. * Set footer margin.
  2066. * (minimum distance between footer and bottom page margin)
  2067. * @param int $fm distance in user units
  2068. * @access public
  2069. */
  2070. public function setFooterMargin($fm=10) {
  2071. $this->footer_margin = $fm;
  2072. }
  2073. /**
  2074. * Returns footer margin in user units.
  2075. * @return float
  2076. * @since 4.0.012 (2008-07-24)
  2077. * @access public
  2078. */
  2079. public function getFooterMargin() {
  2080. return $this->footer_margin;
  2081. }
  2082. /**
  2083. * Set a flag to print page header.
  2084. * @param boolean $val set to true to print the page header (default), false otherwise.
  2085. * @access public
  2086. */
  2087. public function setPrintHeader($val=true) {
  2088. $this->print_header = $val;
  2089. }
  2090. /**
  2091. * Set a flag to print page footer.
  2092. * @param boolean $value set to true to print the page footer (default), false otherwise.
  2093. * @access public
  2094. */
  2095. public function setPrintFooter($val=true) {
  2096. $this->print_footer = $val;
  2097. }
  2098. /**
  2099. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  2100. * @return float
  2101. * @access public
  2102. */
  2103. public function getImageRBX() {
  2104. return $this->img_rb_x;
  2105. }
  2106. /**
  2107. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  2108. * @return float
  2109. * @access public
  2110. */
  2111. public function getImageRBY() {
  2112. return $this->img_rb_y;
  2113. }
  2114. /**
  2115. * This method is used to render the page header.
  2116. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  2117. * @access public
  2118. */
  2119. public function Header() {
  2120. $ormargins = $this->getOriginalMargins();
  2121. $headerfont = $this->getHeaderFont();
  2122. $headerdata = $this->getHeaderData();
  2123. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  2124. $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
  2125. $imgy = $this->getImageRBY();
  2126. } else {
  2127. $imgy = $this->GetY();
  2128. }
  2129. $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
  2130. // set starting margin for text data cell
  2131. if ($this->getRTL()) {
  2132. $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
  2133. } else {
  2134. $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
  2135. }
  2136. $this->SetTextColor(0, 0, 0);
  2137. // header title
  2138. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  2139. $this->SetX($header_x);
  2140. $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  2141. // header string
  2142. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  2143. $this->SetX($header_x);
  2144. $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false);
  2145. // print an ending header line
  2146. $this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
  2147. $this->SetY((2.835 / $this->getScaleFactor()) + max($imgy, $this->GetY()));
  2148. if ($this->getRTL()) {
  2149. $this->SetX($ormargins['right']);
  2150. } else {
  2151. $this->SetX($ormargins['left']);
  2152. }
  2153. $this->Cell(0, 0, '', 'T', 0, 'C');
  2154. }
  2155. /**
  2156. * This method is used to render the page footer.
  2157. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  2158. * @access public
  2159. */
  2160. public function Footer() {
  2161. $cur_y = $this->GetY();
  2162. $ormargins = $this->getOriginalMargins();
  2163. $this->SetTextColor(0, 0, 0);
  2164. //set style for cell border
  2165. $line_width = 0.85 / $this->getScaleFactor();
  2166. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
  2167. //print document barcode
  2168. $barcode = $this->getBarcode();
  2169. if (!empty($barcode)) {
  2170. $this->Ln($line_width);
  2171. $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
  2172. $this->write1DBarcode($barcode, 'C128B', $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
  2173. }
  2174. if (empty($this->pagegroups)) {
  2175. $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  2176. } else {
  2177. $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  2178. }
  2179. $this->SetY($cur_y);
  2180. //Print page number
  2181. if ($this->getRTL()) {
  2182. $this->SetX($ormargins['right']);
  2183. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  2184. } else {
  2185. $this->SetX($ormargins['left']);
  2186. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
  2187. }
  2188. }
  2189. /**
  2190. * This method is used to render the page header.
  2191. * @access protected
  2192. * @since 4.0.012 (2008-07-24)
  2193. */
  2194. protected function setHeader() {
  2195. if ($this->print_header) {
  2196. $lasth = $this->lasth;
  2197. $this->_out('q');
  2198. $this->rMargin = $this->original_rMargin;
  2199. $this->lMargin = $this->original_lMargin;
  2200. $this->cMargin = 0;
  2201. //set current position
  2202. if ($this->rtl) {
  2203. $this->SetXY($this->original_rMargin, $this->header_margin);
  2204. } else {
  2205. $this->SetXY($this->original_lMargin, $this->header_margin);
  2206. }
  2207. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  2208. $this->Header();
  2209. //restore position
  2210. if ($this->rtl) {
  2211. $this->SetXY($this->original_rMargin, $this->tMargin);
  2212. } else {
  2213. $this->SetXY($this->original_lMargin, $this->tMargin);
  2214. }
  2215. $this->_out('Q');
  2216. $this->lasth = $lasth;
  2217. }
  2218. }
  2219. /**
  2220. * This method is used to render the page footer.
  2221. * @access protected
  2222. * @since 4.0.012 (2008-07-24)
  2223. */
  2224. protected function setFooter() {
  2225. //Page footer
  2226. // save current graphic settings
  2227. $gvars = $this->getGraphicVars();
  2228. // mark this point
  2229. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  2230. $this->_out("\n");
  2231. if ($this->print_footer) {
  2232. $lasth = $this->lasth;
  2233. $this->_out('q');
  2234. $this->rMargin = $this->original_rMargin;
  2235. $this->lMargin = $this->original_lMargin;
  2236. $this->cMargin = 0;
  2237. //set current position
  2238. $footer_y = $this->h - $this->footer_margin;
  2239. if ($this->rtl) {
  2240. $this->SetXY($this->original_rMargin, $footer_y);
  2241. } else {
  2242. $this->SetXY($this->original_lMargin, $footer_y);
  2243. }
  2244. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  2245. $this->Footer();
  2246. //restore position
  2247. if ($this->rtl) {
  2248. $this->SetXY($this->original_rMargin, $this->tMargin);
  2249. } else {
  2250. $this->SetXY($this->original_lMargin, $this->tMargin);
  2251. }
  2252. $this->_out('Q');
  2253. $this->lasth = $lasth;
  2254. }
  2255. // restore graphic settings
  2256. $this->setGraphicVars($gvars);
  2257. // calculate footer lenght
  2258. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  2259. }
  2260. /**
  2261. * This method is used to render the table header on new page (if any).
  2262. * @access protected
  2263. * @since 4.5.030 (2009-03-25)
  2264. */
  2265. protected function setTableHeader() {
  2266. if (!$this->empty_string($this->theadMargin)) {
  2267. // restore the original top-margin
  2268. $this->tMargin = $this->theadMargin;
  2269. $this->pagedim[$this->page]['tm'] = $this->theadMargin;
  2270. $this->y = $this->theadMargin;
  2271. }
  2272. if (!$this->empty_string($this->thead)) {
  2273. // print table header
  2274. $this->writeHTML($this->thead, false, false, false, false, '');
  2275. // set new top margin to skip the table headers
  2276. if (!isset($this->theadMargin) OR ($this->empty_string($this->theadMargin))) {
  2277. $this->theadMargin = $this->tMargin;
  2278. }
  2279. $this->tMargin = $this->y;
  2280. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2281. }
  2282. }
  2283. /**
  2284. * Returns the current page number.
  2285. * @return int page number
  2286. * @access public
  2287. * @since 1.0
  2288. * @see AliasNbPages(), getAliasNbPages()
  2289. */
  2290. public function PageNo() {
  2291. return $this->page;
  2292. }
  2293. /**
  2294. * Defines a new spot color.
  2295. * It can be expressed in RGB components or gray scale.
  2296. * The method can be called before the first page is created and the value is retained from page to page.
  2297. * @param int $c Cyan color for CMYK. Value between 0 and 255
  2298. * @param int $m Magenta color for CMYK. Value between 0 and 255
  2299. * @param int $y Yellow color for CMYK. Value between 0 and 255
  2300. * @param int $k Key (Black) color for CMYK. Value between 0 and 255
  2301. * @access public
  2302. * @since 4.0.024 (2008-09-12)
  2303. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  2304. */
  2305. public function AddSpotColor($name, $c, $m, $y, $k) {
  2306. if (!isset($this->spot_colors[$name])) {
  2307. $i = 1 + count($this->spot_colors);
  2308. $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
  2309. }
  2310. }
  2311. /**
  2312. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  2313. * It can be expressed in RGB components or gray scale.
  2314. * The method can be called before the first page is created and the value is retained from page to page.
  2315. * @param array $color array of colors
  2316. * @access public
  2317. * @since 3.1.000 (2008-06-11)
  2318. * @see SetDrawColor()
  2319. */
  2320. public function SetDrawColorArray($color) {
  2321. if (isset($color)) {
  2322. $color = array_values($color);
  2323. $r = isset($color[0]) ? $color[0] : -1;
  2324. $g = isset($color[1]) ? $color[1] : -1;
  2325. $b = isset($color[2]) ? $color[2] : -1;
  2326. $k = isset($color[3]) ? $color[3] : -1;
  2327. if ($r >= 0) {
  2328. $this->SetDrawColor($r, $g, $b, $k);
  2329. }
  2330. }
  2331. }
  2332. /**
  2333. * 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.
  2334. * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
  2335. * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
  2336. * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
  2337. * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
  2338. * @access public
  2339. * @since 1.3
  2340. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  2341. */
  2342. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
  2343. // set default values
  2344. if (!is_numeric($col1)) {
  2345. $col1 = 0;
  2346. }
  2347. if (!is_numeric($col2)) {
  2348. $col2 = -1;
  2349. }
  2350. if (!is_numeric($col3)) {
  2351. $col3 = -1;
  2352. }
  2353. if (!is_numeric($col4)) {
  2354. $col4 = -1;
  2355. }
  2356. //Set color for all stroking operations
  2357. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  2358. // Grey scale
  2359. $this->DrawColor = sprintf('%.3F G', $col1/255);
  2360. } elseif ($col4 == -1) {
  2361. // RGB
  2362. $this->DrawColor = sprintf('%.3F %.3F %.3F RG', $col1/255, $col2/255, $col3/255);
  2363. } else {
  2364. // CMYK
  2365. $this->DrawColor = sprintf('%.3F %.3F %.3F %.3F K', $col1/100, $col2/100, $col3/100, $col4/100);
  2366. }
  2367. if ($this->page > 0) {
  2368. $this->_out($this->DrawColor);
  2369. }
  2370. }
  2371. /**
  2372. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  2373. * @param string $name name of the spot color
  2374. * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  2375. * @access public
  2376. * @since 4.0.024 (2008-09-12)
  2377. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  2378. */
  2379. public function SetDrawSpotColor($name, $tint=100) {
  2380. if (!isset($this->spot_colors[$name])) {
  2381. $this->Error('Undefined spot color: '.$name);
  2382. }
  2383. $this->DrawColor = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$name]['i'], $tint/100);
  2384. if ($this->page > 0) {
  2385. $this->_out($this->DrawColor);
  2386. }
  2387. }
  2388. /**
  2389. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  2390. * It can be expressed in RGB components or gray scale.
  2391. * The method can be called before the first page is created and the value is retained from page to page.
  2392. * @param array $color array of colors
  2393. * @access public
  2394. * @since 3.1.000 (2008-6-11)
  2395. * @see SetFillColor()
  2396. */
  2397. public function SetFillColorArray($color) {
  2398. if (isset($color)) {
  2399. $color = array_values($color);
  2400. $r = isset($color[0]) ? $color[0] : -1;
  2401. $g = isset($color[1]) ? $color[1] : -1;
  2402. $b = isset($color[2]) ? $color[2] : -1;
  2403. $k = isset($color[3]) ? $color[3] : -1;
  2404. if ($r >= 0) {
  2405. $this->SetFillColor($r, $g, $b, $k);
  2406. }
  2407. }
  2408. }
  2409. /**
  2410. * 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.
  2411. * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
  2412. * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
  2413. * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
  2414. * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
  2415. * @access public
  2416. * @since 1.3
  2417. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  2418. */
  2419. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
  2420. // set default values
  2421. if (!is_numeric($col1)) {
  2422. $col1 = 0;
  2423. }
  2424. if (!is_numeric($col2)) {
  2425. $col2 = -1;
  2426. }
  2427. if (!is_numeric($col3)) {
  2428. $col3 = -1;
  2429. }
  2430. if (!is_numeric($col4)) {
  2431. $col4 = -1;
  2432. }
  2433. //Set color for all filling operations
  2434. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  2435. // Grey scale
  2436. $this->FillColor = sprintf('%.3F g', $col1/255);
  2437. $this->bgcolor = array('G' => $col1);
  2438. } elseif ($col4 == -1) {
  2439. // RGB
  2440. $this->FillColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255);
  2441. $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  2442. } else {
  2443. // CMYK
  2444. $this->FillColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100);
  2445. $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  2446. }
  2447. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  2448. if ($this->page > 0) {
  2449. $this->_out($this->FillColor);
  2450. }
  2451. }
  2452. /**
  2453. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  2454. * @param string $name name of the spot color
  2455. * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  2456. * @access public
  2457. * @since 4.0.024 (2008-09-12)
  2458. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  2459. */
  2460. public function SetFillSpotColor($name, $tint=100) {
  2461. if (!isset($this->spot_colors[$name])) {
  2462. $this->Error('Undefined spot color: '.$name);
  2463. }
  2464. $this->FillColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100);
  2465. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  2466. if ($this->page > 0) {
  2467. $this->_out($this->FillColor);
  2468. }
  2469. }
  2470. /**
  2471. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  2472. * The method can be called before the first page is created and the value is retained from page to page.
  2473. * @param array $color array of colors
  2474. * @access public
  2475. * @since 3.1.000 (2008-6-11)
  2476. * @see SetFillColor()
  2477. */
  2478. public function SetTextColorArray($color) {
  2479. if (isset($color)) {
  2480. $color = array_values($color);
  2481. $r = isset($color[0]) ? $color[0] : -1;
  2482. $g = isset($color[1]) ? $color[1] : -1;
  2483. $b = isset($color[2]) ? $color[2] : -1;
  2484. $k = isset($color[3]) ? $color[3] : -1;
  2485. if ($r >= 0) {
  2486. $this->SetTextColor($r, $g, $b, $k);
  2487. }
  2488. }
  2489. }
  2490. /**
  2491. * 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.
  2492. * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
  2493. * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
  2494. * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
  2495. * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
  2496. * @access public
  2497. * @since 1.3
  2498. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  2499. */
  2500. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
  2501. // set default values
  2502. if (!is_numeric($col1)) {
  2503. $col1 = 0;
  2504. }
  2505. if (!is_numeric($col2)) {
  2506. $col2 = -1;
  2507. }
  2508. if (!is_numeric($col3)) {
  2509. $col3 = -1;
  2510. }
  2511. if (!is_numeric($col4)) {
  2512. $col4 = -1;
  2513. }
  2514. //Set color for text
  2515. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  2516. // Grey scale
  2517. $this->TextColor = sprintf('%.3F g', $col1/255);
  2518. $this->fgcolor = array('G' => $col1);
  2519. } elseif ($col4 == -1) {
  2520. // RGB
  2521. $this->TextColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255);
  2522. $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  2523. } else {
  2524. // CMYK
  2525. $this->TextColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100);
  2526. $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  2527. }
  2528. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  2529. }
  2530. /**
  2531. * Defines the spot color used for text.
  2532. * @param string $name name of the spot color
  2533. * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  2534. * @access public
  2535. * @since 4.0.024 (2008-09-12)
  2536. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  2537. */
  2538. public function SetTextSpotColor($name, $tint=100) {
  2539. if (!isset($this->spot_colors[$name])) {
  2540. $this->Error('Undefined spot color: '.$name);
  2541. }
  2542. $this->TextColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100);
  2543. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  2544. if ($this->page > 0) {
  2545. $this->_out($this->TextColor);
  2546. }
  2547. }
  2548. /**
  2549. * Returns the length of a string in user unit. A font must be selected.<br>
  2550. * @param string $s The string whose length is to be computed
  2551. * @param string $fontname 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.
  2552. * @param string $fontstyle 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></ul> or any combination. The default value is regular.
  2553. * @param float $fontsize Font size in points. The default value is the current size.
  2554. * @return int string length
  2555. * @author Nicola Asuni
  2556. * @access public
  2557. * @since 1.2
  2558. */
  2559. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
  2560. return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize);
  2561. }
  2562. /**
  2563. * Returns the string length of an array of chars in user unit. A font must be selected.<br>
  2564. * @param string $arr The array of chars whose total length is to be computed
  2565. * @param string $fontname 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.
  2566. * @param string $fontstyle 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></ul> or any combination. The default value is regular.
  2567. * @param float $fontsize Font size in points. The default value is the current size.
  2568. * @return int string length
  2569. * @author Nicola Asuni
  2570. * @access public
  2571. * @since 2.4.000 (2008-03-06)
  2572. */
  2573. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
  2574. // store current values
  2575. if (!$this->empty_string($fontname)) {
  2576. $prev_FontFamily = $this->FontFamily;
  2577. $prev_FontStyle = $this->FontStyle;
  2578. $prev_FontSizePt = $this->FontSizePt;
  2579. $this->SetFont($fontname, $fontstyle, $fontsize);
  2580. }
  2581. $w = 0;
  2582. foreach ($sa as $char) {
  2583. $w += $this->GetCharWidth($char);
  2584. }
  2585. // restore previous values
  2586. if (!$this->empty_string($fontname)) {
  2587. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
  2588. }
  2589. return $w;
  2590. }
  2591. /**
  2592. * Returns the length of the char in user unit for the current font.<br>
  2593. * @param int $char The char code whose length is to be returned
  2594. * @return int char width
  2595. * @author Nicola Asuni
  2596. * @access public
  2597. * @since 2.4.000 (2008-03-06)
  2598. */
  2599. public function GetCharWidth($char) {
  2600. if ($char == 173) {
  2601. // SHY character will not be printed
  2602. return (0);
  2603. }
  2604. $cw = &$this->CurrentFont['cw'];
  2605. if (isset($cw[$char])) {
  2606. $w = $cw[$char];
  2607. } elseif (isset($this->CurrentFont['dw'])) {
  2608. // default width
  2609. $w = $this->CurrentFont['dw'];
  2610. } elseif (isset($cw[32])) {
  2611. // default width
  2612. $dw = $cw[32];
  2613. } else {
  2614. $w = 600;
  2615. }
  2616. return ($w * $this->FontSize / 1000);
  2617. }
  2618. /**
  2619. * Returns the numbero of characters in a string.
  2620. * @param string $s The input string.
  2621. * @return int number of characters
  2622. * @access public
  2623. * @since 2.0.0001 (2008-01-07)
  2624. */
  2625. public function GetNumChars($s) {
  2626. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  2627. return count($this->UTF8StringToArray($s));
  2628. }
  2629. return strlen($s);
  2630. }
  2631. /**
  2632. * Fill the list of available fonts ($this->fontlist).
  2633. * @access protected
  2634. * @since 4.0.013 (2008-07-28)
  2635. */
  2636. protected function getFontsList() {
  2637. $fontsdir = opendir($this->_getfontpath());
  2638. while (($file = readdir($fontsdir)) !== false) {
  2639. if (substr($file, -4) == '.php') {
  2640. array_push($this->fontlist, strtolower(basename($file, '.php')));
  2641. }
  2642. }
  2643. closedir($fontsdir);
  2644. }
  2645. /**
  2646. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  2647. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  2648. * 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.
  2649. * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  2650. * @param string $style 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>
  2651. * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  2652. * @return array containing the font data, or false in case of error.
  2653. * @access public
  2654. * @since 1.5
  2655. * @see SetFont()
  2656. */
  2657. public function AddFont($family, $style='', $fontfile='') {
  2658. if ($this->empty_string($family)) {
  2659. if (!$this->empty_string($this->FontFamily)) {
  2660. $family = $this->FontFamily;
  2661. } else {
  2662. $this->Error('Empty font family');
  2663. }
  2664. }
  2665. $family = strtolower($family);
  2666. if ((!$this->isunicode) AND ($family == 'arial')) {
  2667. $family = 'helvetica';
  2668. }
  2669. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  2670. $style = '';
  2671. }
  2672. $tempstyle = strtoupper($style);
  2673. $style = '';
  2674. // underline
  2675. if (strpos($tempstyle, 'U') !== false) {
  2676. $this->underline = true;
  2677. } else {
  2678. $this->underline = false;
  2679. }
  2680. // line through (deleted)
  2681. if (strpos($tempstyle, 'D') !== false) {
  2682. $this->linethrough = true;
  2683. } else {
  2684. $this->linethrough = false;
  2685. }
  2686. // bold
  2687. if (strpos($tempstyle, 'B') !== false) {
  2688. $style .= 'B';
  2689. }
  2690. // oblique
  2691. if (strpos($tempstyle, 'I') !== false) {
  2692. $style .= 'I';
  2693. }
  2694. $bistyle = $style;
  2695. $fontkey = $family.$style;
  2696. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
  2697. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  2698. // check if the font has been already added
  2699. if ($this->getFontBuffer($fontkey) !== false) {
  2700. return $fontdata;
  2701. }
  2702. if (isset($type)) {
  2703. unset($type);
  2704. }
  2705. if (isset($cw)) {
  2706. unset($cw);
  2707. }
  2708. // get specified font directory (if any)
  2709. $fontdir = '';
  2710. if (!$this->empty_string($fontfile)) {
  2711. $fontdir = dirname($fontfile);
  2712. if ($this->empty_string($fontdir) OR ($fontdir == '.')) {
  2713. $fontdir = '';
  2714. } else {
  2715. $fontdir .= '/';
  2716. }
  2717. }
  2718. // search and include font file
  2719. if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) {
  2720. // build a standard filenames for specified font
  2721. $fontfile1 = str_replace(' ', '', $family).strtolower($style).'.php';
  2722. $fontfile2 = str_replace(' ', '', $family).'.php';
  2723. // search files on various directories
  2724. if (file_exists($fontdir.$fontfile1)) {
  2725. $fontfile = $fontdir.$fontfile1;
  2726. } elseif (file_exists($this->_getfontpath().$fontfile1)) {
  2727. $fontfile = $this->_getfontpath().$fontfile1;
  2728. } elseif (file_exists($fontfile1)) {
  2729. $fontfile = $fontfile1;
  2730. } elseif (file_exists($fontdir.$fontfile2)) {
  2731. $fontfile = $fontdir.$fontfile2;
  2732. } elseif (file_exists($this->_getfontpath().$fontfile2)) {
  2733. $fontfile = $this->_getfontpath().$fontfile2;
  2734. } else {
  2735. $fontfile = $fontfile2;
  2736. }
  2737. }
  2738. // include font file
  2739. if (file_exists($fontfile)) {
  2740. include($fontfile);
  2741. } else {
  2742. $this->Error('Could not include font definition file: '.$family.'');
  2743. }
  2744. // check font parameters
  2745. if ((!isset($type)) OR (!isset($cw))) {
  2746. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  2747. }
  2748. if (!isset($file)) {
  2749. $file = '';
  2750. }
  2751. if (!isset($enc)) {
  2752. $enc = '';
  2753. }
  2754. if (!isset($dw) OR $this->empty_string($dw)) {
  2755. // set default width
  2756. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  2757. $dw = $desc['MissingWidth'];
  2758. } elseif (isset($cw[32])) {
  2759. $dw = $cw[32];
  2760. } else {
  2761. $dw = 600;
  2762. }
  2763. }
  2764. ++$this->numfonts;
  2765. // register CID font (all styles at once)
  2766. if ($type == 'cidfont0') {
  2767. $file = ''; // not embedded
  2768. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  2769. $sname = $name.$styles[$bistyle];
  2770. if ((strpos($bistyle, 'B') !== false) AND (isset($desc['StemV'])) AND ($desc['StemV'] == 70)) {
  2771. $desc['StemV'] = 120;
  2772. }
  2773. $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc));
  2774. } elseif ($type == 'core') {
  2775. $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $dw));
  2776. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  2777. $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'file' => $file, 'enc' => $enc, 'desc' => $desc));
  2778. } elseif ($type == 'TrueTypeUnicode') {
  2779. $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg));
  2780. } else {
  2781. $this->Error('Unknow font type: '.$type.'');
  2782. }
  2783. if (isset($diff) AND (!empty($diff))) {
  2784. //Search existing encodings
  2785. $d = 0;
  2786. $nb = count($this->diffs);
  2787. for ($i=1; $i <= $nb; ++$i) {
  2788. if ($this->diffs[$i] == $diff) {
  2789. $d = $i;
  2790. break;
  2791. }
  2792. }
  2793. if ($d == 0) {
  2794. $d = $nb + 1;
  2795. $this->diffs[$d] = $diff;
  2796. }
  2797. $this->setFontSubBuffer($fontkey, 'diff', $d);
  2798. }
  2799. if (!$this->empty_string($file)) {
  2800. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  2801. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir);
  2802. } elseif ($type != 'core') {
  2803. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir);
  2804. }
  2805. }
  2806. return $fontdata;
  2807. }
  2808. /**
  2809. * Sets the font used to print character strings.
  2810. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  2811. * The method can be called before the first page is created and the font is retained from page to page.
  2812. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  2813. * 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 />
  2814. * @param string $family 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.
  2815. * @param string $style 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></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.
  2816. * @param float $size 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
  2817. * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  2818. * @access public
  2819. * @since 1.0
  2820. * @see AddFont(), SetFontSize()
  2821. */
  2822. public function SetFont($family, $style='', $size=0, $fontfile='') {
  2823. //Select a font; size given in points
  2824. if ($size == 0) {
  2825. $size = $this->FontSizePt;
  2826. }
  2827. // try to add font (if not already added)
  2828. $fontdata = $this->AddFont($family, $style, $fontfile);
  2829. $this->FontFamily = $fontdata['family'];
  2830. $this->FontStyle = $fontdata['style'];
  2831. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  2832. $this->SetFontSize($size);
  2833. }
  2834. /**
  2835. * Defines the size of the current font.
  2836. * @param float $size The size (in points)
  2837. * @access public
  2838. * @since 1.0
  2839. * @see SetFont()
  2840. */
  2841. public function SetFontSize($size) {
  2842. //Set font size in points
  2843. $this->FontSizePt = $size;
  2844. $this->FontSize = $size / $this->k;
  2845. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  2846. $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
  2847. } else {
  2848. $this->FontAscent = 0.8 * $this->FontSize;
  2849. }
  2850. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
  2851. $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
  2852. } else {
  2853. $this->FontDescent = 0.2 * $this->FontSize;
  2854. }
  2855. if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
  2856. $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  2857. }
  2858. }
  2859. /**
  2860. * Defines the default monospaced font.
  2861. * @param string $font Font name.
  2862. * @access public
  2863. * @since 4.5.025
  2864. */
  2865. public function SetDefaultMonospacedFont($font) {
  2866. $this->default_monospaced_font = $font;
  2867. }
  2868. /**
  2869. * 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 />
  2870. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  2871. * @access public
  2872. * @since 1.5
  2873. * @see Cell(), Write(), Image(), Link(), SetLink()
  2874. */
  2875. public function AddLink() {
  2876. //Create a new internal link
  2877. $n = count($this->links) + 1;
  2878. $this->links[$n] = array(0, 0);
  2879. return $n;
  2880. }
  2881. /**
  2882. * Defines the page and position a link points to.
  2883. * @param int $link The link identifier returned by AddLink()
  2884. * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  2885. * @param int $page Number of target page; -1 indicates the current page. This is the default value
  2886. * @access public
  2887. * @since 1.5
  2888. * @see AddLink()
  2889. */
  2890. public function SetLink($link, $y=0, $page=-1) {
  2891. if ($y == -1) {
  2892. $y = $this->y;
  2893. }
  2894. if ($page == -1) {
  2895. $page = $this->page;
  2896. }
  2897. $this->links[$link] = array($page, $y);
  2898. }
  2899. /**
  2900. * Puts a link on a rectangular area of the page.
  2901. * 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.
  2902. * @param float $x Abscissa of the upper-left corner of the rectangle
  2903. * @param float $y Ordinate of the upper-left corner of the rectangle
  2904. * @param float $w Width of the rectangle
  2905. * @param float $h Height of the rectangle
  2906. * @param mixed $link URL or identifier returned by AddLink()
  2907. * @param int $spaces number of spaces on the text to link
  2908. * @access public
  2909. * @since 1.5
  2910. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  2911. */
  2912. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  2913. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  2914. }
  2915. /**
  2916. * Puts a markup annotation on a rectangular area of the page.
  2917. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  2918. * @param float $x Abscissa of the upper-left corner of the rectangle
  2919. * @param float $y Ordinate of the upper-left corner of the rectangle
  2920. * @param float $w Width of the rectangle
  2921. * @param float $h Height of the rectangle
  2922. * @param string $text annotation text or alternate content
  2923. * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
  2924. * @param int $spaces number of spaces on the text to link
  2925. * @access public
  2926. * @since 4.0.018 (2008-08-06)
  2927. */
  2928. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  2929. // recalculate coordinates to account for graphic transformations
  2930. if (isset($this->transfmatrix)) {
  2931. $maxid = count($this->transfmatrix) - 1;
  2932. for ($i=$maxid; $i >= 0; $i--) {
  2933. $ctm = $this->transfmatrix[$i];
  2934. if (isset($ctm['a'])) {
  2935. $x = $x * $this->k;
  2936. $y = ($this->h - $y) * $this->k;
  2937. $w = $w * $this->k;
  2938. $h = $h * $this->k;
  2939. // top left
  2940. $xt = $x;
  2941. $yt = $y;
  2942. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  2943. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  2944. // top right
  2945. $xt = $x + $w;
  2946. $yt = $y;
  2947. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  2948. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  2949. // bottom left
  2950. $xt = $x;
  2951. $yt = $y - $h;
  2952. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  2953. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  2954. // bottom right
  2955. $xt = $x + $w;
  2956. $yt = $y - $h;
  2957. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  2958. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  2959. // new coordinates (rectangle area)
  2960. $x = min($x1, $x2, $x3, $x4);
  2961. $y = max($y1, $y2, $y3, $y4);
  2962. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  2963. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  2964. $x = $x / $this->k;
  2965. $y = $this->h - ($y / $this->k);
  2966. }
  2967. }
  2968. }
  2969. $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  2970. if (($opt['Subtype'] == 'FileAttachment') AND (!$this->empty_string($opt['FS'])) AND file_exists($opt['FS']) AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  2971. $this->embeddedfiles[basename($opt['FS'])] = array('file' => $opt['FS'], 'n' => (count($this->embeddedfiles) + 100000));
  2972. }
  2973. }
  2974. /**
  2975. * Embedd the attached files.
  2976. * @since 4.4.000 (2008-12-07)
  2977. * @access protected
  2978. * @see Annotation()
  2979. */
  2980. protected function _putEmbeddedFiles() {
  2981. reset($this->embeddedfiles);
  2982. foreach ($this->embeddedfiles as $filename => $filedata) {
  2983. $data = file_get_contents($filedata['file']);
  2984. $filter = '';
  2985. if ($this->compress) {
  2986. $data = gzcompress($data);
  2987. $filter = ' /Filter /FlateDecode';
  2988. }
  2989. $this->offsets[$filedata['n']] = $this->bufferlen;
  2990. $this->_out($filedata['n'].' 0 obj');
  2991. $this->_out('<</Type /EmbeddedFile'.$filter.' /Length '.strlen($data).' >>');
  2992. $this->_putstream($data);
  2993. $this->_out('endobj');
  2994. }
  2995. }
  2996. /**
  2997. * Prints a character string.
  2998. * The origin is on the left of the first charcter, on the baseline.
  2999. * This method allows to place a string precisely on the page.
  3000. * @param float $x Abscissa of the origin
  3001. * @param float $y Ordinate of the origin
  3002. * @param string $txt String to print
  3003. * @param int $stroke outline size in points (0 = disable)
  3004. * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  3005. * @access public
  3006. * @since 1.0
  3007. * @deprecated deprecated since version 4.3.005 (2008-11-25)
  3008. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  3009. */
  3010. public function Text($x, $y, $txt, $stroke=0, $clip=false) {
  3011. //Output a string
  3012. if ($this->rtl) {
  3013. // bidirectional algorithm (some chars may be changed affecting the line length)
  3014. $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl);
  3015. $l = $this->GetArrStringWidth($s);
  3016. $xr = $this->w - $x - $this->GetArrStringWidth($s);
  3017. } else {
  3018. $xr = $x;
  3019. }
  3020. $opt = '';
  3021. if (($stroke > 0) AND (!$clip)) {
  3022. $opt .= '1 Tr '.intval($stroke).' w ';
  3023. } elseif (($stroke > 0) AND $clip) {
  3024. $opt .= '5 Tr '.intval($stroke).' w ';
  3025. } elseif ($clip) {
  3026. $opt .= '7 Tr ';
  3027. }
  3028. $s = sprintf('BT %.2F %.2F Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
  3029. if ($this->underline AND ($txt!='')) {
  3030. $s .= ' '.$this->_dounderline($xr, $y, $txt);
  3031. }
  3032. if ($this->linethrough AND ($txt!='')) {
  3033. $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
  3034. }
  3035. if ($this->ColorFlag AND (!$clip)) {
  3036. $s='q '.$this->TextColor.' '.$s.' Q';
  3037. }
  3038. $this->_out($s);
  3039. }
  3040. /**
  3041. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  3042. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  3043. * This method is called automatically and should not be called directly by the application.
  3044. * @return boolean
  3045. * @access public
  3046. * @since 1.4
  3047. * @see SetAutoPageBreak()
  3048. */
  3049. public function AcceptPageBreak() {
  3050. return $this->AutoPageBreak;
  3051. }
  3052. /**
  3053. * Add page if needed.
  3054. * @param float $h Cell height. Default value: 0.
  3055. * @param mixed $y starting y position, leave empty for current position.
  3056. * @return boolean true in case of page break, false otherwise.
  3057. * @since 3.2.000 (2008-07-01)
  3058. * @access protected
  3059. */
  3060. protected function checkPageBreak($h=0, $y='') {
  3061. if ($this->empty_string($y)) {
  3062. $y = $this->y;
  3063. }
  3064. if ((($y + $h) > $this->PageBreakTrigger) AND (!$this->InFooter) AND ($this->AcceptPageBreak())) {
  3065. //Automatic page break
  3066. $x = $this->x;
  3067. $this->AddPage($this->CurOrientation);
  3068. $this->y = $this->tMargin;
  3069. $oldpage = $this->page - 1;
  3070. if ($this->rtl) {
  3071. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  3072. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  3073. } else {
  3074. $this->x = $x;
  3075. }
  3076. } else {
  3077. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  3078. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  3079. } else {
  3080. $this->x = $x;
  3081. }
  3082. }
  3083. return true;
  3084. }
  3085. return false;
  3086. }
  3087. /**
  3088. * 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 />
  3089. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  3090. * @param float $w Cell width. If 0, the cell extends up to the right margin.
  3091. * @param float $h Cell height. Default value: 0.
  3092. * @param string $txt String to print. Default value: empty string.
  3093. * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either 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>
  3094. * @param int $ln 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>
  3095. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  3096. * @param string $align 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>
  3097. * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  3098. * @param mixed $link URL or identifier returned by AddLink().
  3099. * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
  3100. * @param boolean $ignore_min_height if true ignore automatic minimum height value.
  3101. * @access public
  3102. * @since 1.0
  3103. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  3104. */
  3105. public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false) {
  3106. //$min_cell_height = $this->FontAscent + $this->FontDescent;
  3107. $min_cell_height = $this->FontSize * $this->cell_height_ratio;
  3108. if ($h < $min_cell_height) {
  3109. $h = $min_cell_height;
  3110. }
  3111. $this->checkPageBreak($h);
  3112. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height));
  3113. }
  3114. /**
  3115. * Removes SHY characters from text.
  3116. * @param string $txt input string
  3117. * @return string without SHY characters.
  3118. * @access public
  3119. * @since (4.5.019) 2009-02-28
  3120. */
  3121. public function removeSHY($txt='') {
  3122. /*
  3123. * Unicode Data
  3124. * Name : SOFT HYPHEN, commonly abbreviated as SHY
  3125. * HTML Entity (decimal): &#173;
  3126. * HTML Entity (hex): &#xad;
  3127. * HTML Entity (named): &shy;
  3128. * How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]
  3129. * UTF-8 (hex): 0xC2 0xAD (c2ad)
  3130. * UTF-8 character: chr(194).chr(173)
  3131. */
  3132. $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
  3133. if (!$this->isunicode) {
  3134. $txt = preg_replace('/([\\xad]{1})/', '', $txt);
  3135. }
  3136. return $txt;
  3137. }
  3138. /**
  3139. * 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 />
  3140. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  3141. * @param float $w Cell width. If 0, the cell extends up to the right margin.
  3142. * @param float $h Cell height. Default value: 0.
  3143. * @param string $txt String to print. Default value: empty string.
  3144. * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either 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>
  3145. * @param int $ln 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.
  3146. * @param string $align 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>
  3147. * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  3148. * @param mixed $link URL or identifier returned by AddLink().
  3149. * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
  3150. * @param boolean $ignore_min_height if true ignore automatic minimum height value.
  3151. * @access protected
  3152. * @since 1.0
  3153. * @see Cell()
  3154. */
  3155. protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false) {
  3156. $txt = $this->removeSHY($txt);
  3157. $rs = ''; //string to be returned
  3158. if (!$ignore_min_height) {
  3159. $min_cell_height = $this->FontSize * $this->cell_height_ratio;
  3160. if ($h < $min_cell_height) {
  3161. $h = $min_cell_height;
  3162. }
  3163. }
  3164. $k = $this->k;
  3165. if ($this->empty_string($w) OR ($w <= 0)) {
  3166. if ($this->rtl) {
  3167. $w = $this->x - $this->lMargin;
  3168. } else {
  3169. $w = $this->w - $this->rMargin - $this->x;
  3170. }
  3171. }
  3172. $s = '';
  3173. if (($fill == 1) OR ($border == 1)) {
  3174. if ($fill == 1) {
  3175. $op = ($border == 1) ? 'B' : 'f';
  3176. } else {
  3177. $op = 'S';
  3178. }
  3179. if ($this->rtl) {
  3180. $xk = (($this->x - $w) * $k);
  3181. } else {
  3182. $xk = ($this->x * $k);
  3183. }
  3184. $s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
  3185. }
  3186. if (is_string($border)) {
  3187. $lm = ($this->LineWidth / 2);
  3188. $x = $this->x;
  3189. $y = $this->y;
  3190. if (strpos($border,'L') !== false) {
  3191. if ($this->rtl) {
  3192. $xk = ($x - $w) * $k;
  3193. } else {
  3194. $xk = $x * $k;
  3195. }
  3196. $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y + $lm) * $k), $xk, (($this->h - ($y + $h + $lm)) * $k));
  3197. }
  3198. if (strpos($border,'T') !== false) {
  3199. if ($this->rtl) {
  3200. $xk = ($x - $w + $lm) * $k;
  3201. $xwk = ($x - $lm) * $k;
  3202. } else {
  3203. $xk = ($x - $lm) * $k;
  3204. $xwk = ($x + $w + $lm) * $k;
  3205. }
  3206. $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
  3207. }
  3208. if (strpos($border,'R') !== false) {
  3209. if ($this->rtl) {
  3210. $xk = $x * $k;
  3211. } else {
  3212. $xk = ($x + $w) * $k;
  3213. }
  3214. $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y + $lm) * $k), $xk, (($this->h - ($y + $h + $lm))* $k));
  3215. }
  3216. if (strpos($border,'B') !== false) {
  3217. if ($this->rtl) {
  3218. $xk = ($x - $w + $lm) * $k;
  3219. $xwk = ($x - $lm) * $k;
  3220. } else {
  3221. $xk = ($x - $lm) * $k;
  3222. $xwk = ($x + $w + $lm) * $k;
  3223. }
  3224. $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
  3225. }
  3226. }
  3227. if ($txt != '') {
  3228. // text lenght
  3229. $width = $this->GetStringWidth($txt);
  3230. // ratio between cell lenght and text lenght
  3231. $ratio = ($w - (2 * $this->cMargin)) / $width;
  3232. // stretch text if required
  3233. if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
  3234. if ($stretch > 2) {
  3235. // spacing
  3236. //Calculate character spacing in points
  3237. $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
  3238. //Set character spacing
  3239. $rs .= sprintf('BT %.2F Tc ET ', $char_space);
  3240. } else {
  3241. // scaling
  3242. //Calculate horizontal scaling
  3243. $horiz_scale = $ratio * 100.0;
  3244. //Set horizontal scaling
  3245. $rs .= sprintf('BT %.2F Tz ET ', $horiz_scale);
  3246. }
  3247. $align = '';
  3248. $width = $w - (2 * $this->cMargin);
  3249. } else {
  3250. $stretch == 0;
  3251. }
  3252. if ($align == 'L') {
  3253. if ($this->rtl) {
  3254. $dx = $w - $width - $this->cMargin;
  3255. } else {
  3256. $dx = $this->cMargin;
  3257. }
  3258. } elseif ($align == 'R') {
  3259. if ($this->rtl) {
  3260. $dx = $this->cMargin;
  3261. } else {
  3262. $dx = $w - $width - $this->cMargin;
  3263. }
  3264. } elseif ($align == 'C') {
  3265. $dx = ($w - $width) / 2;
  3266. } elseif ($align == 'J') {
  3267. if ($this->rtl) {
  3268. $dx = $w - $width - $this->cMargin;
  3269. } else {
  3270. $dx = $this->cMargin;
  3271. }
  3272. } else {
  3273. $dx = $this->cMargin;
  3274. }
  3275. if ($this->ColorFlag) {
  3276. $s .= 'q '.$this->TextColor.' ';
  3277. }
  3278. $txt2 = $this->_escapetext($txt);
  3279. if ($this->rtl) {
  3280. $xdk = ($this->x - $dx - $width) * $k;
  3281. } else {
  3282. $xdk = ($this->x + $dx) * $k;
  3283. }
  3284. // Justification
  3285. if ($align == 'J') {
  3286. // count number of spaces
  3287. $ns = substr_count($txt, ' ');
  3288. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  3289. // get string width without spaces
  3290. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  3291. // calculate average space width
  3292. $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
  3293. // set word position to be used with TJ operator
  3294. $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
  3295. } else {
  3296. // get string width
  3297. $width = $this->GetStringWidth($txt);
  3298. $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
  3299. $rs .= sprintf('BT %.3F Tw ET ', $spacewidth);
  3300. }
  3301. }
  3302. // calculate approximate position of the font base line
  3303. //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
  3304. $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
  3305. // print text
  3306. $s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  3307. if ($this->rtl) {
  3308. $xdx = $this->x - $dx - $width;
  3309. } else {
  3310. $xdx = $this->x + $dx;
  3311. }
  3312. if ($this->underline) {
  3313. $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
  3314. }
  3315. if ($this->linethrough) {
  3316. $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
  3317. }
  3318. if ($this->ColorFlag) {
  3319. $s .= ' Q';
  3320. }
  3321. if ($link) {
  3322. $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link, substr_count($txt, chr(32)));
  3323. }
  3324. }
  3325. // output cell
  3326. if ($s) {
  3327. // output cell
  3328. $rs .= $s;
  3329. // reset text stretching
  3330. if ($stretch > 2) {
  3331. //Reset character horizontal spacing
  3332. $rs .= ' BT 0 Tc ET';
  3333. } elseif ($stretch > 0) {
  3334. //Reset character horizontal scaling
  3335. $rs .= ' BT 100 Tz ET';
  3336. }
  3337. }
  3338. // reset word spacing
  3339. if (!(($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($align == 'J')) {
  3340. $rs .= ' BT 0 Tw ET';
  3341. }
  3342. $this->lasth = $h;
  3343. if ($ln > 0) {
  3344. //Go to the beginning of the next line
  3345. $this->y += $h;
  3346. if ($ln == 1) {
  3347. if ($this->rtl) {
  3348. $this->x = $this->w - $this->rMargin;
  3349. } else {
  3350. $this->x = $this->lMargin;
  3351. }
  3352. }
  3353. } else {
  3354. // go left or right by case
  3355. if ($this->rtl) {
  3356. $this->x -= $w;
  3357. } else {
  3358. $this->x += $w;
  3359. }
  3360. }
  3361. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  3362. $rs = $gstyles.$rs;
  3363. return $rs;
  3364. }
  3365. /**
  3366. * This method allows printing text with line breaks.
  3367. * 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 />
  3368. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  3369. * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
  3370. * @param float $h Cell minimum height. The cell extends automatically if needed.
  3371. * @param string $txt String to print
  3372. * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either 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>
  3373. * @param string $align 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>
  3374. * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  3375. * @param int $ln 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>
  3376. * @param int $x x position in user units
  3377. * @param int $y y position in user units
  3378. * @param boolean $reseth if true reset the last cell height (default true).
  3379. * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
  3380. * @param boolean $ishtml set to true if $txt is HTML content (default = false).
  3381. * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
  3382. * @param float $maxh 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.
  3383. * @return int Return the number of cells or 1 for html mode.
  3384. * @access public
  3385. * @since 1.3
  3386. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  3387. */
  3388. public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $addpage=true) {
  3389. if ($this->empty_string($this->lasth) OR $reseth) {
  3390. //set row height
  3391. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  3392. }
  3393. if (!$this->empty_string($y)) {
  3394. $this->SetY($y);
  3395. } else {
  3396. $y = $this->GetY();
  3397. }
  3398. // should not add page for each cell
  3399. if ($addpage) {
  3400. // check for page break
  3401. $this->checkPageBreak($h);
  3402. }
  3403. $y = $this->GetY();
  3404. // get current page number
  3405. $startpage = $this->page;
  3406. if (!$this->empty_string($x)) {
  3407. $this->SetX($x);
  3408. } else {
  3409. $x = $this->GetX();
  3410. }
  3411. if ($this->empty_string($w) OR ($w <= 0)) {
  3412. if ($this->rtl) {
  3413. $w = $this->x - $this->lMargin;
  3414. } else {
  3415. $w = $this->w - $this->rMargin - $this->x;
  3416. }
  3417. }
  3418. // store original margin values
  3419. $lMargin = $this->lMargin;
  3420. $rMargin = $this->rMargin;
  3421. if ($this->rtl) {
  3422. $this->SetRightMargin($this->w - $this->x);
  3423. $this->SetLeftMargin($this->x - $w);
  3424. } else {
  3425. $this->SetLeftMargin($this->x);
  3426. $this->SetRightMargin($this->w - $this->x - $w);
  3427. }
  3428. $starty = $this->y;
  3429. if ($autopadding) {
  3430. // Adjust internal padding
  3431. if ($this->cMargin < ($this->LineWidth / 2)) {
  3432. $this->cMargin = ($this->LineWidth / 2);
  3433. }
  3434. // Add top space if needed
  3435. if (($this->lasth - $this->FontSize) < $this->LineWidth) {
  3436. $this->y += $this->LineWidth / 2;
  3437. }
  3438. // add top padding
  3439. $this->y += $this->cMargin;
  3440. }
  3441. if ($ishtml) {
  3442. // ******* Write HTML text
  3443. $this->writeHTML($txt, true, 0, $reseth, true, $align);
  3444. $nl = 1;
  3445. } else {
  3446. // ******* Write text
  3447. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, false, $maxh);
  3448. }
  3449. if ($autopadding) {
  3450. // add bottom padding
  3451. $this->y += $this->cMargin;
  3452. // Add bottom space if needed
  3453. if (($this->lasth - $this->FontSize) < $this->LineWidth) {
  3454. $this->y += $this->LineWidth / 2;
  3455. }
  3456. }
  3457. // Get end-of-text Y position
  3458. $currentY = $this->y;
  3459. // get latest page number
  3460. $endpage = $this->page;
  3461. // check if a new page has been created
  3462. if ($endpage > $startpage) {
  3463. // design borders around HTML cells.
  3464. for ($page=$startpage; $page <= $endpage; ++$page) {
  3465. $this->setPage($page);
  3466. if ($page == $startpage) {
  3467. $this->y = $starty; // put cursor at the beginning of cell on the first page
  3468. $h = $this->getPageHeight() - $starty - $this->getBreakMargin();
  3469. $cborder = $this->getBorderMode($border, $position='start');
  3470. } elseif ($page == $endpage) {
  3471. $this->y = $this->tMargin; // put cursor at the beginning of last page
  3472. $h = $currentY - $this->tMargin;
  3473. $cborder = $this->getBorderMode($border, $position='end');
  3474. } else {
  3475. $this->y = $this->tMargin; // put cursor at the beginning of the current page
  3476. $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
  3477. $cborder = $this->getBorderMode($border, $position='middle');
  3478. }
  3479. $nx = $x;
  3480. // account for margin changes
  3481. if ($page > $startpage) {
  3482. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  3483. $nx = $x + ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  3484. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  3485. $nx = $x + ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  3486. }
  3487. }
  3488. $this->SetX($nx);
  3489. $ccode = $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, false);
  3490. if ($cborder OR $fill) {
  3491. $pagebuff = $this->getPageBuffer($this->page);
  3492. $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
  3493. $pend = substr($pagebuff, $this->intmrk[$this->page]);
  3494. $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
  3495. $this->intmrk[$this->page] += strlen($ccode."\n");
  3496. }
  3497. }
  3498. } else {
  3499. $h = max($h, ($currentY - $y));
  3500. // put cursor at the beginning of text
  3501. $this->SetY($y);
  3502. $this->SetX($x);
  3503. // design a cell around the text
  3504. $ccode = $this->getCellCode($w, $h, '', $border, 1, '', $fill, '', 0, true);
  3505. if ($border OR $fill) {
  3506. if (end($this->transfmrk[$this->page]) !== false) {
  3507. $pagemarkkey = key($this->transfmrk[$this->page]);
  3508. $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
  3509. } elseif ($this->InFooter) {
  3510. $pagemark = &$this->footerpos[$this->page];
  3511. } else {
  3512. $pagemark = &$this->intmrk[$this->page];
  3513. }
  3514. $pagebuff = $this->getPageBuffer($this->page);
  3515. $pstart = substr($pagebuff, 0, $pagemark);
  3516. $pend = substr($pagebuff, $pagemark);
  3517. $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
  3518. $pagemark += strlen($ccode."\n");
  3519. }
  3520. }
  3521. // Get end-of-cell Y position
  3522. $currentY = $this->GetY();
  3523. // restore original margin values
  3524. $this->SetLeftMargin($lMargin);
  3525. $this->SetRightMargin($rMargin);
  3526. if ($ln > 0) {
  3527. //Go to the beginning of the next line
  3528. $this->SetY($currentY);
  3529. if ($ln == 2) {
  3530. $this->SetX($x + $w);
  3531. }
  3532. } else {
  3533. // go left or right by case
  3534. $this->setPage($startpage);
  3535. $this->y = $y;
  3536. $this->SetX($x + $w);
  3537. }
  3538. return $nl;
  3539. }
  3540. /**
  3541. * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
  3542. * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either 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>
  3543. * @param string multicell position: 'start', 'middle', 'end'
  3544. * @return border mode
  3545. * @access protected
  3546. * @since 4.4.002 (2008-12-09)
  3547. */
  3548. protected function getBorderMode($border, $position='start') {
  3549. if ((!$this->opencell) AND ($border == 1)) {
  3550. return 1;
  3551. }
  3552. $cborder = '';
  3553. switch ($position) {
  3554. case 'start': {
  3555. if ($border == 1) {
  3556. $cborder = 'LTR';
  3557. } else {
  3558. if (!(false === strpos($border, 'L'))) {
  3559. $cborder .= 'L';
  3560. }
  3561. if (!(false === strpos($border, 'T'))) {
  3562. $cborder .= 'T';
  3563. }
  3564. if (!(false === strpos($border, 'R'))) {
  3565. $cborder .= 'R';
  3566. }
  3567. if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
  3568. $cborder .= 'B';
  3569. }
  3570. }
  3571. break;
  3572. }
  3573. case 'middle': {
  3574. if ($border == 1) {
  3575. $cborder = 'LR';
  3576. } else {
  3577. if (!(false === strpos($border, 'L'))) {
  3578. $cborder .= 'L';
  3579. }
  3580. if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
  3581. $cborder .= 'T';
  3582. }
  3583. if (!(false === strpos($border, 'R'))) {
  3584. $cborder .= 'R';
  3585. }
  3586. if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
  3587. $cborder .= 'B';
  3588. }
  3589. }
  3590. break;
  3591. }
  3592. case 'end': {
  3593. if ($border == 1) {
  3594. $cborder = 'LRB';
  3595. } else {
  3596. if (!(false === strpos($border, 'L'))) {
  3597. $cborder .= 'L';
  3598. }
  3599. if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
  3600. $cborder .= 'T';
  3601. }
  3602. if (!(false === strpos($border, 'R'))) {
  3603. $cborder .= 'R';
  3604. }
  3605. if (!(false === strpos($border, 'B'))) {
  3606. $cborder .= 'B';
  3607. }
  3608. }
  3609. break;
  3610. }
  3611. default: {
  3612. $cborder = $border;
  3613. break;
  3614. }
  3615. }
  3616. return $cborder;
  3617. }
  3618. /**
  3619. * This method returns the estimated number of lines required to print the text.
  3620. * @param string $txt text to print
  3621. * @param float $w width of cell. If 0, they extend up to the right margin of the page.
  3622. * @return int Return the estimated number of lines.
  3623. * @access public
  3624. * @since 4.5.011
  3625. */
  3626. public function getNumLines($txt, $w=0) {
  3627. $lines = 0;
  3628. if ($this->empty_string($w) OR ($w <= 0)) {
  3629. if ($this->rtl) {
  3630. $w = $this->x - $this->lMargin;
  3631. } else {
  3632. $w = $this->w - $this->rMargin - $this->x;
  3633. }
  3634. }
  3635. // max column width
  3636. $wmax = $w - (2 * $this->cMargin);
  3637. // remove carriage returns
  3638. $txt = str_replace("\r", '', $txt);
  3639. // remove last newline (if any)
  3640. if (substr($txt,-1) == "\n") {
  3641. $txt = substr($txt, 0, -1);
  3642. }
  3643. // divide text in blocks
  3644. $txtblocks = explode("\n", $txt);
  3645. // for each block;
  3646. foreach ($txtblocks as $block) {
  3647. // estimate the number of lines
  3648. $lines += $this->empty_string($block) ? 1 : (ceil($this->GetStringWidth($block) / $wmax));
  3649. }
  3650. return $lines;
  3651. }
  3652. /**
  3653. * This method prints text from the current position.<br />
  3654. * @param float $h Line height
  3655. * @param string $txt String to print
  3656. * @param mixed $link URL or identifier returned by AddLink()
  3657. * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
  3658. * @param string $align 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>
  3659. * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  3660. * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
  3661. * @param boolean $firstline if true prints only the first line and return the remaining string.
  3662. * @param boolean $firstblock if true the string is the starting of a line.
  3663. * @param float $maxh 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.
  3664. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  3665. * @access public
  3666. * @since 1.5
  3667. */
  3668. public function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0) {
  3669. if (strlen($txt) == 0) {
  3670. $txt = ' ';
  3671. }
  3672. // remove carriage returns
  3673. $s = str_replace("\r", '', $txt);
  3674. // check if string contains arabic text
  3675. if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
  3676. $arabic = true;
  3677. } else {
  3678. $arabic = false;
  3679. }
  3680. // check if string contains RTL text
  3681. if ($arabic OR $this->tmprtl OR preg_match(K_RE_PATTERN_RTL, $txt)) {
  3682. $rtlmode = true;
  3683. } else {
  3684. $rtlmode = false;
  3685. }
  3686. // get a char width
  3687. $chrwidth = $this->GetCharWidth('.');
  3688. // get array of unicode values
  3689. $chars = $this->UTF8StringToArray($s);
  3690. // get array of chars
  3691. $uchars = $this->UTF8ArrayToUniArray($chars);
  3692. // get the number of characters
  3693. $nb = count($chars);
  3694. // replacement for SHY character (minus symbol)
  3695. $shy_replacement = 45;
  3696. $shy_replacement_char = $this->unichr($shy_replacement);
  3697. // widht for SHY replacement
  3698. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  3699. // store current position
  3700. $prevx = $this->x;
  3701. $prevy = $this->y;
  3702. // max Y
  3703. $maxy = $this->y + $maxh - $h - (2 * $this->cMargin);
  3704. // calculate remaining line width ($w)
  3705. if ($this->rtl) {
  3706. $w = $this->x - $this->lMargin;
  3707. } else {
  3708. $w = $this->w - $this->rMargin - $this->x;
  3709. }
  3710. // max column width
  3711. $wmax = $w - (2 * $this->cMargin);
  3712. if ($chrwidth > $wmax) {
  3713. // a single character do not fit on column
  3714. return '';
  3715. }
  3716. $i = 0; // character position
  3717. $j = 0; // current starting position
  3718. $sep = -1; // position of the last blank space
  3719. $shy = false; // true if the last blank is a soft hypen (SHY)
  3720. $l = 0; // current string lenght
  3721. $nl = 0; //number of lines
  3722. $linebreak = false;
  3723. // for each character
  3724. while ($i < $nb) {
  3725. if (($maxh > 0) AND ($this->y >= $maxy) ) {
  3726. $firstline = true;
  3727. }
  3728. //Get the current character
  3729. $c = $chars[$i];
  3730. if ($c == 10) { // 10 = "\n" = new line
  3731. //Explicit line break
  3732. if ($align == 'J') {
  3733. if ($this->rtl) {
  3734. $talign = 'R';
  3735. } else {
  3736. $talign = 'L';
  3737. }
  3738. } else {
  3739. $talign = $align;
  3740. }
  3741. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  3742. if ($firstline) {
  3743. $startx = $this->x;
  3744. $tmparr = array_slice($chars, $j, $i);
  3745. if ($rtlmode) {
  3746. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  3747. }
  3748. $linew = $this->GetArrStringWidth($tmparr);
  3749. unset($tmparr);
  3750. if ($this->rtl) {
  3751. $this->endlinex = $startx - $linew;
  3752. } else {
  3753. $this->endlinex = $startx + $linew;
  3754. }
  3755. $w = $linew;
  3756. $tmpcmargin = $this->cMargin;
  3757. if ($maxh == 0) {
  3758. $this->cMargin = 0;
  3759. }
  3760. }
  3761. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  3762. unset($tmpstr);
  3763. if ($firstline) {
  3764. $this->cMargin = $tmpcmargin;
  3765. return ($this->UniArrSubString($uchars, $i));
  3766. }
  3767. ++$nl;
  3768. $j = $i + 1;
  3769. $l = 0;
  3770. $sep = -1;
  3771. $shy = false;
  3772. // account for margin changes
  3773. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
  3774. // AcceptPageBreak() may be overriden on extended classed to include margin changes
  3775. $this->AcceptPageBreak();
  3776. }
  3777. $w = $this->getRemainingWidth();
  3778. $wmax = $w - (2 * $this->cMargin);
  3779. } else {
  3780. // 160 is the non-breaking space.
  3781. // 173 is SHY (Soft Hypen).
  3782. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  3783. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  3784. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  3785. if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
  3786. // update last blank space position
  3787. $sep = $i;
  3788. // check if is a SHY
  3789. if ($c == 173) {
  3790. $shy = true;
  3791. } else {
  3792. $shy = false;
  3793. }
  3794. }
  3795. // update string length
  3796. if ((($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($arabic)) {
  3797. // with bidirectional algorithm some chars may be changed affecting the line length
  3798. // *** very slow ***
  3799. $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), '', $this->tmprtl));
  3800. } else {
  3801. $l += $this->GetCharWidth($c);
  3802. }
  3803. if (!$stretch && (($l > $wmax) OR ($shy AND (($l + $shy_replacement_width) > $wmax))) ) {
  3804. // we have reached the end of column
  3805. if ($sep == -1) {
  3806. // check if the line was already started
  3807. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
  3808. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
  3809. // print a void cell and go to next line
  3810. $this->Cell($w, $h, '', 0, 1);
  3811. $linebreak = true;
  3812. if ($firstline) {
  3813. return ($this->UniArrSubString($uchars, $j));
  3814. }
  3815. } else {
  3816. // truncate the word because do not fit on column
  3817. $tmpstr = $this->UniArrSubString($uchars, $j, $i);
  3818. if ($firstline) {
  3819. $startx = $this->x;
  3820. $tmparr = array_slice($chars, $j, $i);
  3821. if ($rtlmode) {
  3822. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  3823. }
  3824. $linew = $this->GetArrStringWidth($tmparr);
  3825. unset($tmparr);
  3826. if ($this->rtl) {
  3827. $this->endlinex = $startx - $linew;
  3828. } else {
  3829. $this->endlinex = $startx + $linew;
  3830. }
  3831. $w = $linew;
  3832. $tmpcmargin = $this->cMargin;
  3833. if ($maxh == 0) {
  3834. $this->cMargin = 0;
  3835. }
  3836. }
  3837. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  3838. unset($tmpstr);
  3839. if ($firstline) {
  3840. $this->cMargin = $tmpcmargin;
  3841. return ($this->UniArrSubString($uchars, $i));
  3842. }
  3843. $j = $i;
  3844. --$i;
  3845. }
  3846. } else {
  3847. // word wrapping
  3848. if ($this->rtl AND (!$firstblock)) {
  3849. $endspace = 1;
  3850. } else {
  3851. $endspace = 0;
  3852. }
  3853. if ($shy) {
  3854. // add hypen (minus symbol) at the end of the line
  3855. $shy_width = $shy_replacement_width;
  3856. if ($this->rtl) {
  3857. $shy_char_left = $shy_replacement_char;
  3858. $shy_char_right = '';
  3859. } else {
  3860. $shy_char_left = '';
  3861. $shy_char_right = $shy_replacement_char;
  3862. }
  3863. } else {
  3864. $shy_width = 0;
  3865. $shy_char_left = '';
  3866. $shy_char_right = '';
  3867. }
  3868. $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
  3869. if ($firstline) {
  3870. $startx = $this->x;
  3871. $tmparr = array_slice($chars, $j, ($sep + $endspace));
  3872. if ($rtlmode) {
  3873. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  3874. }
  3875. $linew = $this->GetArrStringWidth($tmparr);
  3876. unset($tmparr);
  3877. if ($this->rtl) {
  3878. $this->endlinex = $startx - $linew - $shy_width;
  3879. } else {
  3880. $this->endlinex = $startx + $linew + $shy_width;
  3881. }
  3882. $w = $linew;
  3883. $tmpcmargin = $this->cMargin;
  3884. if ($maxh == 0) {
  3885. $this->cMargin = 0;
  3886. }
  3887. }
  3888. // print the line
  3889. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  3890. unset($tmpstr);
  3891. if ($firstline) {
  3892. // return the remaining text
  3893. $this->cMargin = $tmpcmargin;
  3894. return ($this->UniArrSubString($uchars, ($sep + $endspace)));
  3895. }
  3896. $i = $sep;
  3897. $sep = -1;
  3898. $shy = false;
  3899. $j = ($i+1);
  3900. }
  3901. // account for margin changes
  3902. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
  3903. // AcceptPageBreak() may be overriden on extended classed to include margin changes
  3904. $this->AcceptPageBreak();
  3905. }
  3906. $w = $this->getRemainingWidth();
  3907. $wmax = $w - (2 * $this->cMargin);
  3908. if ($linebreak) {
  3909. $linebreak = false;
  3910. } else {
  3911. ++$nl;
  3912. $l = 0;
  3913. }
  3914. }
  3915. }
  3916. ++$i;
  3917. } // end while i < nb
  3918. // print last substring (if any)
  3919. if ($l > 0) {
  3920. if (!$stretch)
  3921. {
  3922. switch ($align) {
  3923. case 'J':
  3924. case 'C': {
  3925. $w = $w;
  3926. break;
  3927. }
  3928. case 'L': {
  3929. if ($this->rtl) {
  3930. $w = $w;
  3931. } else {
  3932. $w = $l;
  3933. }
  3934. break;
  3935. }
  3936. case 'R': {
  3937. if ($this->rtl) {
  3938. $w = $l;
  3939. } else {
  3940. $w = $w;
  3941. }
  3942. break;
  3943. }
  3944. default: {
  3945. $w = $l;
  3946. break;
  3947. }
  3948. }
  3949. }
  3950. $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
  3951. if ($firstline) {
  3952. $startx = $this->x;
  3953. $tmparr = array_slice($chars, $j, $nb);
  3954. if ($rtlmode) {
  3955. $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
  3956. }
  3957. $linew = $this->GetArrStringWidth($tmparr);
  3958. unset($tmparr);
  3959. if ($this->rtl) {
  3960. $this->endlinex = $startx - $linew;
  3961. } else {
  3962. $this->endlinex = $startx + $linew;
  3963. }
  3964. if (!$stretch)
  3965. $w = $linew;
  3966. $tmpcmargin = $this->cMargin;
  3967. if ($maxh == 0) {
  3968. $this->cMargin = 0;
  3969. }
  3970. }
  3971. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  3972. unset($tmpstr);
  3973. if ($firstline) {
  3974. $this->cMargin = $tmpcmargin;
  3975. return ($this->UniArrSubString($uchars, $nb));
  3976. }
  3977. ++$nl;
  3978. }
  3979. if ($firstline) {
  3980. return '';
  3981. }
  3982. return $nl;
  3983. }
  3984. /**
  3985. * Returns the remaining width between the current position and margins.
  3986. * @return int Return the remaining width
  3987. * @access protected
  3988. */
  3989. protected function getRemainingWidth() {
  3990. if ($this->rtl) {
  3991. return ($this->x - $this->lMargin);
  3992. } else {
  3993. return ($this->w - $this->rMargin - $this->x);
  3994. }
  3995. }
  3996. /**
  3997. * Extract a slice of the $strarr array and return it as string.
  3998. * @param string $strarr The input array of characters.
  3999. * @param int $start the starting element of $strarr.
  4000. * @param int $end first element that will not be returned.
  4001. * @return Return part of a string
  4002. * @access public
  4003. */
  4004. public function UTF8ArrSubString($strarr, $start='', $end='') {
  4005. if (strlen($start) == 0) {
  4006. $start = 0;
  4007. }
  4008. if (strlen($end) == 0) {
  4009. $end = count($strarr);
  4010. }
  4011. $string = '';
  4012. for ($i=$start; $i < $end; ++$i) {
  4013. $string .= $this->unichr($strarr[$i]);
  4014. }
  4015. return $string;
  4016. }
  4017. /**
  4018. * Extract a slice of the $uniarr array and return it as string.
  4019. * @param string $uniarr The input array of characters.
  4020. * @param int $start the starting element of $strarr.
  4021. * @param int $end first element that will not be returned.
  4022. * @return Return part of a string
  4023. * @access public
  4024. * @since 4.5.037 (2009-04-07)
  4025. */
  4026. public function UniArrSubString($uniarr, $start='', $end='') {
  4027. if (strlen($start) == 0) {
  4028. $start = 0;
  4029. }
  4030. if (strlen($end) == 0) {
  4031. $end = count($uniarr);
  4032. }
  4033. $string = '';
  4034. for ($i=$start; $i < $end; ++$i) {
  4035. $string .= $uniarr[$i];
  4036. }
  4037. return $string;
  4038. }
  4039. /**
  4040. * Convert an array of UTF8 values to array of unicode characters
  4041. * @param string $ta The input array of UTF8 values.
  4042. * @return Return array of unicode characters
  4043. * @access public
  4044. * @since 4.5.037 (2009-04-07)
  4045. */
  4046. public function UTF8ArrayToUniArray($ta) {
  4047. return array_map(array($this, 'unichr'), $ta);
  4048. }
  4049. /**
  4050. * Returns the unicode caracter specified by UTF-8 code
  4051. * @param int $c UTF-8 code
  4052. * @return Returns the specified character.
  4053. * @author Miguel Perez, Nicola Asuni
  4054. * @access public
  4055. * @since 2.3.000 (2008-03-05)
  4056. */
  4057. public function unichr($c) {
  4058. if (!$this->isunicode) {
  4059. return chr($c);
  4060. } elseif ($c <= 0x7F) {
  4061. // one byte
  4062. return chr($c);
  4063. } elseif ($c <= 0x7FF) {
  4064. // two bytes
  4065. return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
  4066. } elseif ($c <= 0xFFFF) {
  4067. // three bytes
  4068. return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  4069. } elseif ($c <= 0x10FFFF) {
  4070. // four bytes
  4071. return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  4072. } else {
  4073. return '';
  4074. }
  4075. }
  4076. /**
  4077. * Puts an image in the page.
  4078. * The upper-left corner must be given.
  4079. * The dimensions can be specified in different ways:<ul>
  4080. * <li>explicit width and height (expressed in user unit)</li>
  4081. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  4082. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  4083. * 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;
  4084. * The format can be specified explicitly or inferred from the file extension.<br />
  4085. * It is possible to put a link on the image.<br />
  4086. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  4087. * @param string $file Name of the file containing the image.
  4088. * @param float $x Abscissa of the upper-left corner.
  4089. * @param float $y Ordinate of the upper-left corner.
  4090. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  4091. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  4092. * @param string $type 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.
  4093. * @param mixed $link URL or identifier returned by AddLink().
  4094. * @param string $align 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>
  4095. * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
  4096. * @param int $dpi dot-per-inch resolution used on resize
  4097. * @param string $palign 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>
  4098. * @param boolean $ismask true if this image is a mask, false otherwise
  4099. * @param mixed $imgmask image object returned by this function or false
  4100. * @param mixed $border Indicates if borders must be drawn around the image. The value can be either 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>
  4101. * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
  4102. * @return image information
  4103. * @access public
  4104. * @since 1.1
  4105. *
  4106. * peter d: Upgrading tcpdf to the latest version causes the whole thing to blow up since we have modifications to the original source as well as sugarpdf which
  4107. * also extend from this. The only option is to add a workaround for some of the bugs in this function.
  4108. */
  4109. 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) {
  4110. if ($x === '') {
  4111. $x = $this->x;
  4112. }
  4113. if ($y === '') {
  4114. $y = $this->y;
  4115. }
  4116. // get image dimensions
  4117. $imsize = @getimagesize($file);
  4118. if ($imsize === FALSE) {
  4119. // encode spaces on filename
  4120. $file = str_replace(' ', '%20', $file);
  4121. $imsize = @getimagesize($file);
  4122. if ($imsize === FALSE) {
  4123. $this->Error('[Image] No such file or directory in '.$file);
  4124. }
  4125. }
  4126. // get original image width and height in pixels
  4127. list($pixw, $pixh) = $imsize;
  4128. // calculate image width and height on document
  4129. if (($w <= 0) AND ($h <= 0)) {
  4130. // convert image size to document unit
  4131. $w = $this->pixelsToUnits($pixw);
  4132. $h = $this->pixelsToUnits($pixh);
  4133. } elseif ($w <= 0) {
  4134. $w = $h * $pixw / $pixh;
  4135. } elseif ($h <= 0) {
  4136. $h = $w * $pixh / $pixw;
  4137. } elseif ($fitbox AND ($w > 0) AND ($h > 0)) {
  4138. // scale image dimensions proportionally to fit within the ($w, $h) box
  4139. // NOTE: This section doesn't actually work very well, use the resize = true case I added.
  4140. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  4141. $h = $w * $pixh / $pixw;
  4142. } else {
  4143. $w = $h * $pixw / $pixh;
  4144. }
  4145. } else if ($resize) { // Added resize case
  4146. // Note: The issue here is that $w and $h represent abstract sizes, we pass it in as pixels,
  4147. // but tcpdf treats it as document units.
  4148. $wratio = $pixw / $w;
  4149. $hratio = $pixh / $h;
  4150. // Check if our image exceeds the boundaries of $w and $h
  4151. if ($wratio > 1 AND $hratio > 1) {
  4152. $favoredRatio = ($wratio > $hratio) ? $wratio : $hratio;
  4153. } else if ($wratio > 1) {
  4154. $favoredRatio = $wratio;
  4155. } else if ($hratio > 1) {
  4156. $favoredRatio = $hratio;
  4157. } else {
  4158. $favoredRatio = 1;
  4159. $resize = false;
  4160. }
  4161. // Calculate the new boundaries that also happen to fit the box..
  4162. // Dividing by the unit conversion $this->k seems to make the size not blow up
  4163. // later down in the code.
  4164. $w = $pixw / $favoredRatio / $this->k;
  4165. $h = $pixh / $favoredRatio / $this->k;
  4166. }
  4167. // calculate new minimum dimensions in pixels
  4168. $neww = round($w * $this->k * $dpi / $this->dpi);
  4169. $newh = round($h * $this->k * $dpi / $this->dpi);
  4170. // check if resize is necessary (resize is used only to reduce the image)
  4171. // - commmented out by pete d.
  4172. // this is not a good way of checking for resize. and it might overwrite resize if the flag is enabled.
  4173. // if (($neww * $newh) >= ($pixw * $pixh)) {
  4174. // $resize = false;
  4175. // }
  4176. // check if image has been already added on document
  4177. if (!in_array($file, $this->imagekeys)) {
  4178. //First use of image, get info
  4179. if ($type == '') {
  4180. $fileinfo = pathinfo($file);
  4181. if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
  4182. $type = $fileinfo['extension'];
  4183. } else {
  4184. $this->Error('Image file has no extension and no type was specified: '.$file);
  4185. }
  4186. }
  4187. $type = strtolower($type);
  4188. if ($type == 'jpg') {
  4189. $type = 'jpeg';
  4190. }
  4191. $mqr = get_magic_quotes_runtime();
  4192. //set_magic_quotes_runtime(0);
  4193. // Specific image handlers
  4194. $mtd = '_parse'.$type;
  4195. // GD image handler function
  4196. $gdfunction = 'imagecreatefrom'.$type;
  4197. $info = false;
  4198. if ((method_exists($this, $mtd)) AND (!($resize AND function_exists($gdfunction)))) {
  4199. // TCPDF image functions
  4200. $info = $this->$mtd($file);
  4201. if ($info == 'pngalpha') {
  4202. return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
  4203. }
  4204. }
  4205. if (!$info) {
  4206. if (function_exists($gdfunction)) {
  4207. // GD library
  4208. $img = $gdfunction($file);
  4209. if ($resize) {
  4210. $imgr = imagecreatetruecolor($neww, $newh);
  4211. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  4212. $info = $this->_toJPEG($imgr);
  4213. } else {
  4214. $info = $this->_toJPEG($img);
  4215. }
  4216. } elseif (extension_loaded('imagick')) {
  4217. // ImageMagick library
  4218. $img = new Imagick();
  4219. $img->readImage($file);
  4220. if ($resize) {
  4221. $img->resizeImage($neww, $newh, 10, 1, false);
  4222. }
  4223. $img->setCompressionQuality($this->jpeg_quality);
  4224. $img->setImageFormat('jpeg');
  4225. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  4226. $img->writeImage($tempname);
  4227. $info = $this->_parsejpeg($tempname);
  4228. unlink($tempname);
  4229. $img->destroy();
  4230. }
  4231. else if ($type == 'jpeg') {
  4232. $info = $this->_parsejpeg($file);
  4233. }
  4234. else {
  4235. return;
  4236. }
  4237. }
  4238. if ($info === false) {
  4239. //If false, we cannot process image
  4240. return;
  4241. }
  4242. //set_magic_quotes_runtime($mqr);
  4243. if ($ismask) {
  4244. // force grayscale
  4245. $info['cs'] = 'DeviceGray';
  4246. }
  4247. $info['i'] = $this->numimages + 1;
  4248. if ($imgmask !== false) {
  4249. $info['masked'] = $imgmask;
  4250. }
  4251. // add image to document
  4252. $this->setImageBuffer($file, $info);
  4253. } else {
  4254. $info = $this->getImageBuffer($file);
  4255. }
  4256. // Check whether we need a new page first as this does not fit
  4257. if ($this->checkPageBreak($h, $y)) {
  4258. $y = $this->GetY() + $this->cMargin;
  4259. }
  4260. // set bottomcoordinates
  4261. $this->img_rb_y = $y + $h;
  4262. // set alignment
  4263. if ($this->rtl) {
  4264. if ($palign == 'L') {
  4265. $ximg = $this->lMargin;
  4266. // set right side coordinate
  4267. $this->img_rb_x = $ximg + $w;
  4268. } elseif ($palign == 'C') {
  4269. $ximg = ($this->w - $x - $w) / 2;
  4270. // set right side coordinate
  4271. $this->img_rb_x = $ximg + $w;
  4272. } else {
  4273. $ximg = $this->w - $x - $w;
  4274. // set left side coordinate
  4275. $this->img_rb_x = $ximg;
  4276. }
  4277. } else {
  4278. if ($palign == 'R') {
  4279. $ximg = $this->w - $this->rMargin - $w;
  4280. // set left side coordinate
  4281. $this->img_rb_x = $ximg;
  4282. } elseif ($palign == 'C') {
  4283. $ximg = ($this->w - $x - $w) / 2;
  4284. // set right side coordinate
  4285. $this->img_rb_x = $ximg + $w;
  4286. } else {
  4287. $ximg = $x;
  4288. // set right side coordinate
  4289. $this->img_rb_x = $ximg + $w;
  4290. }
  4291. }
  4292. if ($ismask) {
  4293. // embed hidden, ouside the canvas
  4294. $xkimg = ($this->pagedim[$this->page]['w'] + 10);
  4295. } else {
  4296. $xkimg = $ximg * $this->k;
  4297. }
  4298. $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
  4299. if (!empty($border)) {
  4300. $bx = $x;
  4301. $by = $y;
  4302. $this->x = $ximg;
  4303. $this->y = $y;
  4304. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
  4305. $this->x = $bx;
  4306. $this->y = $by;
  4307. }
  4308. if ($link) {
  4309. $this->Link($ximg, $y, $w, $h, $link, 0);
  4310. }
  4311. // set pointer to align the successive text/objects
  4312. switch($align) {
  4313. case 'T': {
  4314. $this->y = $y;
  4315. $this->x = $this->img_rb_x;
  4316. break;
  4317. }
  4318. case 'M': {
  4319. $this->y = $y + round($h/2);
  4320. $this->x = $this->img_rb_x;
  4321. break;
  4322. }
  4323. case 'B': {
  4324. $this->y = $this->img_rb_y;
  4325. $this->x = $this->img_rb_x;
  4326. break;
  4327. }
  4328. case 'N': {
  4329. $this->SetY($this->img_rb_y);
  4330. break;
  4331. }
  4332. default:{
  4333. break;
  4334. }
  4335. }
  4336. $this->endlinex = $this->img_rb_x;
  4337. return $info['i'];
  4338. }
  4339. /**
  4340. * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
  4341. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
  4342. * @param string $file Image file name.
  4343. * @param image $image Image object.
  4344. * return image JPEG image object.
  4345. * @access protected
  4346. */
  4347. protected function _toJPEG($image) {
  4348. $tempname = tempnam(K_PATH_CACHE, 'jpg_');
  4349. imagejpeg($image, $tempname, $this->jpeg_quality);
  4350. imagedestroy($image);
  4351. $retvars = $this->_parsejpeg($tempname);
  4352. // tidy up by removing temporary image
  4353. unlink($tempname);
  4354. return $retvars;
  4355. }
  4356. /**
  4357. * Extract info from a JPEG file without using the GD library.
  4358. * @param string $file image file to parse
  4359. * @return array structure containing the image data
  4360. * @access protected
  4361. */
  4362. protected function _parsejpeg($file) {
  4363. $a = getimagesize($file);
  4364. if (empty($a)) {
  4365. $this->Error('Missing or incorrect image file: '.$file);
  4366. }
  4367. if ($a[2] != 2) {
  4368. $this->Error('Not a JPEG file: '.$file);
  4369. }
  4370. if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
  4371. $colspace = 'DeviceRGB';
  4372. } elseif ($a['channels'] == 4) {
  4373. $colspace = 'DeviceCMYK';
  4374. } else {
  4375. $colspace = 'DeviceGray';
  4376. }
  4377. $bpc = isset($a['bits']) ? $a['bits'] : 8;
  4378. $data = file_get_contents($file);
  4379. return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
  4380. }
  4381. /**
  4382. * Extract info from a PNG file without using the GD library.
  4383. * @param string $file image file to parse
  4384. * @return array structure containing the image data
  4385. * @access protected
  4386. */
  4387. protected function _parsepng($file) {
  4388. $f = fopen($file, 'rb');
  4389. if ($f === false) {
  4390. $this->Error('Can\'t open image file: '.$file);
  4391. }
  4392. //Check signature
  4393. if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
  4394. $this->Error('Not a PNG file: '.$file);
  4395. }
  4396. //Read header chunk
  4397. fread($f, 4);
  4398. if (fread($f, 4) != 'IHDR') {
  4399. $this->Error('Incorrect PNG file: '.$file);
  4400. }
  4401. $w = $this->_freadint($f);
  4402. $h = $this->_freadint($f);
  4403. $bpc = ord(fread($f, 1));
  4404. if ($bpc > 8) {
  4405. //$this->Error('16-bit depth not supported: '.$file);
  4406. fclose($f);
  4407. return false;
  4408. }
  4409. $ct = ord(fread($f, 1));
  4410. if ($ct == 0) {
  4411. $colspace = 'DeviceGray';
  4412. } elseif ($ct == 2) {
  4413. $colspace = 'DeviceRGB';
  4414. } elseif ($ct == 3) {
  4415. $colspace = 'Indexed';
  4416. } else {
  4417. // alpha channel
  4418. fclose($f);
  4419. return 'pngalpha';
  4420. }
  4421. if (ord(fread($f, 1)) != 0) {
  4422. //$this->Error('Unknown compression method: '.$file);
  4423. fclose($f);
  4424. return false;
  4425. }
  4426. if (ord(fread($f, 1)) != 0) {
  4427. //$this->Error('Unknown filter method: '.$file);
  4428. fclose($f);
  4429. return false;
  4430. }
  4431. if (ord(fread($f, 1)) != 0) {
  4432. //$this->Error('Interlacing not supported: '.$file);
  4433. fclose($f);
  4434. return false;
  4435. }
  4436. fread($f, 4);
  4437. $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
  4438. //Scan chunks looking for palette, transparency and image data
  4439. $pal = '';
  4440. $trns = '';
  4441. $data = '';
  4442. do {
  4443. $n = $this->_freadint($f);
  4444. $type = fread($f, 4);
  4445. if ($type == 'PLTE') {
  4446. //Read palette
  4447. $pal = $this->rfread($f, $n);
  4448. fread($f, 4);
  4449. } elseif ($type == 'tRNS') {
  4450. //Read transparency info
  4451. $t = $this->rfread($f, $n);
  4452. if ($ct == 0) {
  4453. $trns = array(ord(substr($t, 1, 1)));
  4454. } elseif ($ct == 2) {
  4455. $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1)));
  4456. } else {
  4457. $pos = strpos($t, chr(0));
  4458. if ($pos !== false) {
  4459. $trns = array($pos);
  4460. }
  4461. }
  4462. fread($f, 4);
  4463. } elseif ($type == 'IDAT') {
  4464. //Read image data block
  4465. $data .= $this->rfread($f, $n);
  4466. fread($f, 4);
  4467. } elseif ($type == 'IEND') {
  4468. break;
  4469. } else {
  4470. $this->rfread($f, $n + 4);
  4471. }
  4472. } while ($n);
  4473. if (($colspace == 'Indexed') AND (empty($pal))) {
  4474. //$this->Error('Missing palette in '.$file);
  4475. fclose($f);
  4476. return false;
  4477. }
  4478. fclose($f);
  4479. return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
  4480. }
  4481. /**
  4482. * Binary-safe and URL-safe file read.
  4483. * 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.
  4484. * @param resource $handle
  4485. * @param int $length
  4486. * @return Returns the read string or FALSE in case of error.
  4487. * @author Nicola Asuni
  4488. * @access protected
  4489. * @since 4.5.027 (2009-03-16)
  4490. */
  4491. protected function rfread($handle, $length) {
  4492. $data = fread($handle, $length);
  4493. if ($data === false) {
  4494. return false;
  4495. }
  4496. $rest = $length - strlen($data);
  4497. if ($rest > 0) {
  4498. $data .= $this->rfread($handle, $rest);
  4499. }
  4500. return $data;
  4501. }
  4502. /**
  4503. * Extract info from a PNG image with alpha channel using the GD library.
  4504. * @param string $file Name of the file containing the image.
  4505. * @param float $x Abscissa of the upper-left corner.
  4506. * @param float $y Ordinate of the upper-left corner.
  4507. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  4508. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  4509. * @param string $type 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.
  4510. * @param mixed $link URL or identifier returned by AddLink().
  4511. * @param string $align 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>
  4512. * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
  4513. * @param int $dpi dot-per-inch resolution used on resize
  4514. * @param string $palign 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>
  4515. * @author Valentin Schmidt, Nicola Asuni
  4516. * @access protected
  4517. * @since 4.3.007 (2008-12-04)
  4518. * @see Image()
  4519. */
  4520. protected function ImagePngAlpha($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
  4521. // get image size
  4522. list($wpx, $hpx) = getimagesize($file);
  4523. // generate images
  4524. $img = imagecreatefrompng($file);
  4525. $imgalpha = imagecreate($wpx, $hpx);
  4526. // generate gray scale pallete
  4527. for ($c = 0; $c < 256; ++$c) {
  4528. ImageColorAllocate($imgalpha, $c, $c, $c);
  4529. }
  4530. // extract alpha channel
  4531. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  4532. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  4533. $colorindex = imagecolorat($img, $xpx, $ypx);
  4534. $col = imagecolorsforindex($img, $colorindex);
  4535. imagesetpixel($imgalpha, $xpx, $ypx, $this->getGDgamma((127 - $col['alpha']) * 255 / 127));
  4536. }
  4537. }
  4538. // create temp alpha file
  4539. $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_');
  4540. imagepng($imgalpha, $tempfile_alpha);
  4541. imagedestroy($imgalpha);
  4542. // extract image without alpha channel
  4543. $imgplain = imagecreatetruecolor($wpx, $hpx);
  4544. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  4545. // create temp image file
  4546. $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_');
  4547. imagepng($imgplain, $tempfile_plain);
  4548. imagedestroy($imgplain);
  4549. // embed mask image
  4550. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  4551. // embed image, masked with previously embedded mask
  4552. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  4553. // remove temp files
  4554. unlink($tempfile_alpha);
  4555. unlink($tempfile_plain);
  4556. }
  4557. /**
  4558. * Correct the gamma value to be used with GD library
  4559. * @param float $v the gamma value to be corrected
  4560. * @access protected
  4561. * @since 4.3.007 (2008-12-04)
  4562. */
  4563. protected function getGDgamma($v) {
  4564. return (pow(($v / 255), 2.2) * 255);
  4565. }
  4566. /**
  4567. * Performs a line break.
  4568. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  4569. * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
  4570. * @param boolean $cell if true add a cMargin to the x coordinate
  4571. * @access public
  4572. * @since 1.0
  4573. * @see Cell()
  4574. */
  4575. public function Ln($h='', $cell=false) {
  4576. //Line feed; default value is last cell height
  4577. if ($cell) {
  4578. $cellmargin = $this->cMargin;
  4579. } else {
  4580. $cellmargin = 0;
  4581. }
  4582. if ($this->rtl) {
  4583. $this->x = $this->w - $this->rMargin - $cellmargin;
  4584. } else {
  4585. $this->x = $this->lMargin + $cellmargin;
  4586. }
  4587. if (is_string($h)) {
  4588. $this->y += $this->lasth;
  4589. } else {
  4590. $this->y += $h;
  4591. }
  4592. $this->newline = true;
  4593. }
  4594. /**
  4595. * Returns the relative X value of current position.
  4596. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  4597. * @return float
  4598. * @access public
  4599. * @since 1.2
  4600. * @see SetX(), GetY(), SetY()
  4601. */
  4602. public function GetX() {
  4603. //Get x position
  4604. if ($this->rtl) {
  4605. return ($this->w - $this->x);
  4606. } else {
  4607. return $this->x;
  4608. }
  4609. }
  4610. /**
  4611. * Returns the absolute X value of current position.
  4612. * @return float
  4613. * @access public
  4614. * @since 1.2
  4615. * @see SetX(), GetY(), SetY()
  4616. */
  4617. public function GetAbsX() {
  4618. return $this->x;
  4619. }
  4620. /**
  4621. * Returns the ordinate of the current position.
  4622. * @return float
  4623. * @access public
  4624. * @since 1.0
  4625. * @see SetY(), GetX(), SetX()
  4626. */
  4627. public function GetY() {
  4628. //Get y position
  4629. return $this->y;
  4630. }
  4631. /**
  4632. * Defines the abscissa of the current position.
  4633. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  4634. * @param float $x The value of the abscissa.
  4635. * @access public
  4636. * @since 1.2
  4637. * @see GetX(), GetY(), SetY(), SetXY()
  4638. */
  4639. public function SetX($x) {
  4640. //Set x position
  4641. if ($this->rtl) {
  4642. if ($x >= 0) {
  4643. $this->x = $this->w - $x;
  4644. } else {
  4645. $this->x = abs($x);
  4646. }
  4647. } else {
  4648. if ($x >= 0) {
  4649. $this->x = $x;
  4650. } else {
  4651. $this->x = $this->w + $x;
  4652. }
  4653. }
  4654. if ($this->x < 0) {
  4655. $this->x = 0;
  4656. }
  4657. if ($this->x > $this->w) {
  4658. $this->x = $this->w;
  4659. }
  4660. }
  4661. /**
  4662. * Moves the current abscissa back to the left margin and sets the ordinate.
  4663. * If the passed value is negative, it is relative to the bottom of the page.
  4664. * @param float $y The value of the ordinate.
  4665. * @param bool $resetx if true (default) reset the X position.
  4666. * @access public
  4667. * @since 1.0
  4668. * @see GetX(), GetY(), SetY(), SetXY()
  4669. */
  4670. public function SetY($y, $resetx=true) {
  4671. if ($resetx) {
  4672. //reset x
  4673. if ($this->rtl) {
  4674. $this->x = $this->w - $this->rMargin;
  4675. } else {
  4676. $this->x = $this->lMargin;
  4677. }
  4678. }
  4679. if ($y >= 0) {
  4680. $this->y = $y;
  4681. } else {
  4682. $this->y = $this->h + $y;
  4683. }
  4684. if ($this->y < 0) {
  4685. $this->y = 0;
  4686. }
  4687. if ($this->y > $this->h) {
  4688. $this->y = $this->h;
  4689. }
  4690. }
  4691. /**
  4692. * Defines the abscissa and ordinate of the current position.
  4693. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  4694. * @param float $x The value of the abscissa
  4695. * @param float $y The value of the ordinate
  4696. * @access public
  4697. * @since 1.2
  4698. * @see SetX(), SetY()
  4699. */
  4700. public function SetXY($x, $y) {
  4701. //Set x and y positions
  4702. $this->SetY($y);
  4703. $this->SetX($x);
  4704. }
  4705. /**
  4706. * Send the document to a given destination: string, local file or browser.
  4707. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  4708. * The method first calls Close() if necessary to terminate the document.
  4709. * @param string $name The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
  4710. * @param string $dest 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 file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>
  4711. * @access public
  4712. * @since 1.0
  4713. * @see Close()
  4714. */
  4715. public function Output($name='doc.pdf', $dest='I') {
  4716. //Output PDF to some destination
  4717. //Finish document if necessary
  4718. if ($this->state < 3) {
  4719. $this->Close();
  4720. }
  4721. //Normalize parameters
  4722. if (is_bool($dest)) {
  4723. $dest = $dest ? 'D' : 'F';
  4724. }
  4725. $dest = strtoupper($dest);
  4726. if ($dest != 'F') {
  4727. $name = preg_replace('/[\s]+/', '_', $name);
  4728. $name = preg_replace('/[^a-zA-Z0-9\._-\x{4e00}-\x{9fa5}]/u', '', $name);
  4729. }
  4730. if ($this->sign) {
  4731. // *** apply digital signature to the document ***
  4732. // get the document content
  4733. $pdfdoc = $this->getBuffer();
  4734. // remove last newline
  4735. $pdfdoc = substr($pdfdoc, 0, -1);
  4736. // Remove the original buffer
  4737. if (isset($this->diskcache) AND $this->diskcache) {
  4738. // remove buffer file from cache
  4739. unlink($this->buffer);
  4740. }
  4741. unset($this->buffer);
  4742. // remove filler space
  4743. $tmppos = strpos($pdfdoc, '/ByteRange[0 ********** ********** **********]') + 58;
  4744. $pdfdoc = substr($pdfdoc, 0, $tmppos).substr($pdfdoc, $tmppos + $this->signature_max_lenght);
  4745. // define the ByteRange
  4746. $byte_range = array();
  4747. $byte_range[0] = 0;
  4748. $byte_range[1] = $tmppos - 1;
  4749. $byte_range[2] = $byte_range[1] + $this->signature_max_lenght;
  4750. $byte_range[3] = strlen($pdfdoc) - $byte_range[1];
  4751. // replace the ByteRange
  4752. $byterange = sprintf('/ByteRange[0 %010u %010u %010u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  4753. $pdfdoc = str_replace('/ByteRange[0 ********** ********** **********]', $byterange, $pdfdoc);
  4754. // write the document to a temporary folder
  4755. $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
  4756. $f = fopen($tempdoc, 'wb');
  4757. if (!$f) {
  4758. $this->Error('Unable to create temporary file: '.$tempdoc);
  4759. }
  4760. $pdfdoc_lenght = strlen($pdfdoc);
  4761. fwrite($f, $pdfdoc, $pdfdoc_lenght);
  4762. fclose($f);
  4763. // get digital signature.
  4764. // IS THE FOLLOWING PROCEDURE CORRECT? THE SIGNED DOCUMENTS ARE NOT VALID!
  4765. $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
  4766. if (empty($this->signature_data['extracerts'])) {
  4767. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  4768. } else {
  4769. 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']);
  4770. }
  4771. unlink($tempdoc);
  4772. // read signature
  4773. $signature = file_get_contents($tempsign, false, null, $pdfdoc_lenght);
  4774. unlink($tempsign);
  4775. // extract signature
  4776. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  4777. $tmparr = explode("\n\n", $signature);
  4778. $signature = $tmparr[1];
  4779. unset($tmparr);
  4780. // decode signature
  4781. $signature = base64_decode(trim($signature));
  4782. // convert signature to hex
  4783. $signature = current(unpack('H*', $signature));
  4784. $signature = str_pad($signature, $this->signature_max_lenght, '0');
  4785. // Add signature to the document
  4786. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).$signature.substr($pdfdoc, (0 - $byte_range[3]));
  4787. $this->diskcache = false;
  4788. $this->buffer = &$pdfdoc;
  4789. $this->bufferlen = strlen($pdfdoc);
  4790. }
  4791. switch($dest) {
  4792. case 'I': {
  4793. // Send PDF to the standard output
  4794. if (ob_get_contents()) {
  4795. $this->Error('Some data has already been output, can\'t send PDF file');
  4796. }
  4797. if (php_sapi_name() != 'cli') {
  4798. //We send to a browser
  4799. header('Content-Type: application/pdf');
  4800. if (headers_sent()) {
  4801. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  4802. }
  4803. header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  4804. header('Pragma: public');
  4805. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  4806. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  4807. header('Content-Length: '.$this->bufferlen);
  4808. header('Content-Disposition: inline; filename="'.basename($name).'";');
  4809. }
  4810. echo $this->getBuffer();
  4811. break;
  4812. }
  4813. case 'D': {
  4814. // Download PDF as file
  4815. if (ob_get_contents()) {
  4816. $this->Error('Some data has already been output, can\'t send PDF file');
  4817. }
  4818. header('Content-Description: File Transfer');
  4819. if (headers_sent()) {
  4820. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  4821. }
  4822. header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  4823. header('Pragma: public');
  4824. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  4825. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  4826. // force download dialog
  4827. header('Content-Type: application/force-download');
  4828. header('Content-Type: application/octet-stream', false);
  4829. header('Content-Type: application/download', false);
  4830. header('Content-Type: application/pdf', false);
  4831. // use the Content-Disposition header to supply a recommended filename
  4832. header('Content-Disposition: attachment; filename="'.basename($name).'";');
  4833. header('Content-Transfer-Encoding: binary');
  4834. header('Content-Length: '.$this->bufferlen);
  4835. echo $this->getBuffer();
  4836. break;
  4837. }
  4838. case 'F': {
  4839. // Save PDF to a local file
  4840. if ($this->diskcache) {
  4841. copy($this->buffer, $name);
  4842. } else {
  4843. $f = fopen($name, 'wb');
  4844. if (!$f) {
  4845. $this->Error('Unable to create output file: '.$name);
  4846. }
  4847. fwrite($f, $this->getBuffer(), $this->bufferlen);
  4848. fclose($f);
  4849. }
  4850. break;
  4851. }
  4852. case 'S': {
  4853. // Returns PDF as a string
  4854. return $this->getBuffer();
  4855. }
  4856. default: {
  4857. $this->Error('Incorrect output destination: '.$dest);
  4858. }
  4859. }
  4860. return '';
  4861. }
  4862. /**
  4863. * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
  4864. * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables.
  4865. * @param boolean $preserve_objcopy if true preserves the objcopy variable
  4866. * @access public
  4867. * @since 4.5.016 (2009-02-24)
  4868. */
  4869. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  4870. if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
  4871. // remove buffer file from cache
  4872. unlink($this->buffer);
  4873. }
  4874. foreach (array_keys(get_object_vars($this)) as $val) {
  4875. if ($destroyall OR (
  4876. ($val != 'internal_encoding')
  4877. AND ($val != 'state')
  4878. AND ($val != 'bufferlen')
  4879. AND ($val != 'buffer')
  4880. AND ($val != 'diskcache')
  4881. AND ($val != 'sign')
  4882. AND ($val != 'signature_data')
  4883. AND ($val != 'signature_max_lenght')
  4884. )) {
  4885. if (!$preserve_objcopy OR ($val != 'objcopy')) {
  4886. unset($this->$val);
  4887. }
  4888. }
  4889. }
  4890. }
  4891. /**
  4892. * Check for locale-related bug
  4893. * @access protected
  4894. */
  4895. protected function _dochecks() {
  4896. //Check for locale-related bug
  4897. if (1.1 == 1) {
  4898. $this->Error('Don\'t alter the locale before including class file');
  4899. }
  4900. //Check for decimal separator
  4901. if (sprintf('%.1F', 1.0) != '1.0') {
  4902. setlocale(LC_NUMERIC, 'C');
  4903. }
  4904. }
  4905. /**
  4906. * Return fonts path
  4907. * @return string
  4908. * @access protected
  4909. */
  4910. protected function _getfontpath() {
  4911. if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
  4912. define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
  4913. }
  4914. return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
  4915. }
  4916. /**
  4917. * Output pages.
  4918. * @access protected
  4919. */
  4920. protected function _putpages() {
  4921. $nb = $this->numpages;
  4922. if (!empty($this->AliasNbPages)) {
  4923. $nbs = $this->formatPageNumber($nb);
  4924. $nbu = $this->UTF8ToUTF16BE($nbs, false); // replacement for unicode font
  4925. $alias_a = $this->_escape($this->AliasNbPages);
  4926. $alias_au = $this->_escape('{'.$this->AliasNbPages.'}');
  4927. if ($this->isunicode) {
  4928. $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
  4929. $alias_bu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNbPages.'}'));
  4930. $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
  4931. $alias_cu = $this->_escape($this->utf8StrRev('{'.$this->AliasNbPages.'}', false, $this->tmprtl));
  4932. }
  4933. }
  4934. if (!empty($this->AliasNumPage)) {
  4935. $alias_pa = $this->_escape($this->AliasNumPage);
  4936. $alias_pau = $this->_escape('{'.$this->AliasNumPage.'}');
  4937. if ($this->isunicode) {
  4938. $alias_pb = $this->_escape($this->UTF8ToLatin1($this->AliasNumPage));
  4939. $alias_pbu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNumPage.'}'));
  4940. $alias_pc = $this->_escape($this->utf8StrRev($this->AliasNumPage, false, $this->tmprtl));
  4941. $alias_pcu = $this->_escape($this->utf8StrRev('{'.$this->AliasNumPage.'}', false, $this->tmprtl));
  4942. }
  4943. }
  4944. $pagegroupnum = 0;
  4945. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  4946. for ($n=1; $n <= $nb; ++$n) {
  4947. $temppage = $this->getPageBuffer($n);
  4948. if (!empty($this->pagegroups)) {
  4949. if(isset($this->newpagegroup[$n])) {
  4950. $pagegroupnum = 0;
  4951. }
  4952. ++$pagegroupnum;
  4953. foreach ($this->pagegroups as $k => $v) {
  4954. // replace total pages group numbers
  4955. $vs = $this->formatPageNumber($v);
  4956. $vu = $this->UTF8ToUTF16BE($vs, false);
  4957. $alias_ga = $this->_escape($k);
  4958. $alias_gau = $this->_escape('{'.$k.'}');
  4959. if ($this->isunicode) {
  4960. $alias_gb = $this->_escape($this->UTF8ToLatin1($k));
  4961. $alias_gbu = $this->_escape($this->UTF8ToLatin1('{'.$k.'}'));
  4962. $alias_gc = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
  4963. $alias_gcu = $this->_escape($this->utf8StrRev('{'.$k.'}', false, $this->tmprtl));
  4964. }
  4965. $temppage = str_replace($alias_gau, $vu, $temppage);
  4966. if ($this->isunicode) {
  4967. $temppage = str_replace($alias_gbu, $vu, $temppage);
  4968. $temppage = str_replace($alias_gcu, $vu, $temppage);
  4969. $temppage = str_replace($alias_gb, $vs, $temppage);
  4970. $temppage = str_replace($alias_gc, $vs, $temppage);
  4971. }
  4972. $temppage = str_replace($alias_ga, $vs, $temppage);
  4973. // replace page group numbers
  4974. $pvs = $this->formatPageNumber($pagegroupnum);
  4975. $pvu = $this->UTF8ToUTF16BE($pvs, false);
  4976. $pk = str_replace('{nb', '{pnb', $k);
  4977. $alias_pga = $this->_escape($pk);
  4978. $alias_pgau = $this->_escape('{'.$pk.'}');
  4979. if ($this->isunicode) {
  4980. $alias_pgb = $this->_escape($this->UTF8ToLatin1($pk));
  4981. $alias_pgbu = $this->_escape($this->UTF8ToLatin1('{'.$pk.'}'));
  4982. $alias_pgc = $this->_escape($this->utf8StrRev($pk, false, $this->tmprtl));
  4983. $alias_pgcu = $this->_escape($this->utf8StrRev('{'.$pk.'}', false, $this->tmprtl));
  4984. }
  4985. $temppage = str_replace($alias_pgau, $pvu, $temppage);
  4986. if ($this->isunicode) {
  4987. $temppage = str_replace($alias_pgbu, $pvu, $temppage);
  4988. $temppage = str_replace($alias_pgcu, $pvu, $temppage);
  4989. $temppage = str_replace($alias_pgb, $pvs, $temppage);
  4990. $temppage = str_replace($alias_pgc, $pvs, $temppage);
  4991. }
  4992. $temppage = str_replace($alias_pga, $pvs, $temppage);
  4993. }
  4994. }
  4995. if (!empty($this->AliasNbPages)) {
  4996. // replace total pages number
  4997. $temppage = str_replace($alias_au, $nbu, $temppage);
  4998. if ($this->isunicode) {
  4999. $temppage = str_replace($alias_bu, $nbu, $temppage);
  5000. $temppage = str_replace($alias_cu, $nbu, $temppage);
  5001. $temppage = str_replace($alias_b, $nbs, $temppage);
  5002. $temppage = str_replace($alias_c, $nbs, $temppage);
  5003. }
  5004. $temppage = str_replace($alias_a, $nbs, $temppage);
  5005. }
  5006. if (!empty($this->AliasNumPage)) {
  5007. // replace page number
  5008. $pnbs = $this->formatPageNumber($n);
  5009. $pnbu = $this->UTF8ToUTF16BE($pnbs, false); // replacement for unicode font
  5010. $temppage = str_replace($alias_pau, $pnbu, $temppage);
  5011. if ($this->isunicode) {
  5012. $temppage = str_replace($alias_pbu, $pnbu, $temppage);
  5013. $temppage = str_replace($alias_pcu, $pnbu, $temppage);
  5014. $temppage = str_replace($alias_pb, $pnbs, $temppage);
  5015. $temppage = str_replace($alias_pc, $pnbs, $temppage);
  5016. }
  5017. $temppage = str_replace($alias_pa, $pnbs, $temppage);
  5018. }
  5019. $temppage = str_replace($this->epsmarker, '', $temppage);
  5020. //$this->setPageBuffer($n, $temppage);
  5021. //Page
  5022. $this->_newobj();
  5023. $this->_out('<</Type /Page');
  5024. $this->_out('/Parent 1 0 R');
  5025. $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
  5026. $this->_out('/Resources 2 0 R');
  5027. $this->_putannots($n);
  5028. $this->_out('/Contents '.($this->n + 1).' 0 R>>');
  5029. $this->_out('endobj');
  5030. //Page content
  5031. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  5032. $this->_newobj();
  5033. $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
  5034. $this->_putstream($p);
  5035. $this->_out('endobj');
  5036. if ($this->diskcache) {
  5037. // remove temporary files
  5038. unlink($this->pages[$n]);
  5039. }
  5040. }
  5041. //Pages root
  5042. $this->offsets[1] = $this->bufferlen;
  5043. $this->_out('1 0 obj');
  5044. $this->_out('<</Type /Pages');
  5045. $kids='/Kids [';
  5046. for ($i=0; $i < $nb; ++$i) {
  5047. $kids .= (3 + (2 * $i)).' 0 R ';
  5048. }
  5049. $this->_out($kids.']');
  5050. $this->_out('/Count '.$nb);
  5051. //$this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
  5052. $this->_out('>>');
  5053. $this->_out('endobj');
  5054. }
  5055. /**
  5056. * Output Page Annotations.
  5057. * !!! THIS FUNCTION IS NOT YET COMPLETED !!!
  5058. * See section 8.4 of PDF reference.
  5059. * @param int $n page number
  5060. * @access protected
  5061. * @author Nicola Asuni
  5062. * @since 4.0.018 (2008-08-06)
  5063. */
  5064. protected function _putannots($n) {
  5065. if (isset($this->PageAnnots[$n])) {
  5066. $annots = '/Annots [';
  5067. foreach ($this->PageAnnots[$n] as $key => $pl) {
  5068. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  5069. $a = $pl['x'] * $this->k;
  5070. $b = $this->pagedim[$n]['h'] - ($pl['y'] * $this->k);
  5071. $c = $pl['w'] * $this->k;
  5072. $d = $pl['h'] * $this->k;
  5073. $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b-$d);
  5074. $annots .= "\n";
  5075. $annots .= '<</Type /Annot';
  5076. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  5077. $annots .= ' /Rect ['.$rect.']';
  5078. $annots .= ' /Contents '.$this->_textstring($pl['txt']);
  5079. //$annots .= ' /P ';
  5080. $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
  5081. $annots .= ' /M '.$this->_datastring('D:'.date('YmdHis'));
  5082. if (isset($pl['opt']['f'])) {
  5083. $val = 0;
  5084. if (is_array($pl['opt']['f'])) {
  5085. foreach ($pl['opt']['f'] as $f) {
  5086. switch (strtolower($f)) {
  5087. case 'invisible': {
  5088. $val += 1 << 0;
  5089. break;
  5090. }
  5091. case 'hidden': {
  5092. $val += 1 << 1;
  5093. break;
  5094. }
  5095. case 'print': {
  5096. $val += 1 << 2;
  5097. break;
  5098. }
  5099. case 'nozoom': {
  5100. $val += 1 << 3;
  5101. break;
  5102. }
  5103. case 'norotate': {
  5104. $val += 1 << 4;
  5105. break;
  5106. }
  5107. case 'noview': {
  5108. $val += 1 << 5;
  5109. break;
  5110. }
  5111. case 'readonly': {
  5112. $val += 1 << 6;
  5113. break;
  5114. }
  5115. case 'locked': {
  5116. $val += 1 << 8;
  5117. break;
  5118. }
  5119. case 'togglenoview': {
  5120. $val += 1 << 9;
  5121. break;
  5122. }
  5123. case 'lockedcontents': {
  5124. $val += 1 << 10;
  5125. break;
  5126. }
  5127. default: {
  5128. break;
  5129. }
  5130. }
  5131. }
  5132. }
  5133. $annots .= ' /F '.intval($val);
  5134. }
  5135. //$annots .= ' /AP ';
  5136. //$annots .= ' /AS ';
  5137. $annots .= ' /Border [';
  5138. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  5139. $annots .= intval($pl['opt']['border'][0]).' ';
  5140. $annots .= intval($pl['opt']['border'][1]).' ';
  5141. $annots .= intval($pl['opt']['border'][2]);
  5142. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  5143. $annots .= ' [';
  5144. foreach ($pl['opt']['border'][3] as $dash) {
  5145. $annots .= intval($dash).' ';
  5146. }
  5147. $annots .= ']';
  5148. }
  5149. } else {
  5150. $annots .= '0 0 0';
  5151. }
  5152. $annots .= ']';
  5153. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  5154. $annots .= ' /BS <<Type /Border';
  5155. if (isset($pl['opt']['bs']['w'])) {
  5156. $annots .= ' /W '.sprintf("%.4F", floatval($pl['opt']['bs']['w']));
  5157. }
  5158. $bstyles = array('S', 'D', 'B', 'I', 'U');
  5159. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  5160. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  5161. }
  5162. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  5163. $annots .= ' /D [';
  5164. foreach ($pl['opt']['bs']['d'] as $cord) {
  5165. $cord = floatval($cord);
  5166. $annots .= sprintf(" %.4F", $cord);
  5167. }
  5168. $annots .= ']';
  5169. }
  5170. $annots .= '>> ';
  5171. }
  5172. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  5173. $annots .= ' /BE <<';
  5174. $bstyles = array('S', 'C');
  5175. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
  5176. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  5177. } else {
  5178. $annots .= ' /S /S';
  5179. }
  5180. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  5181. $annots .= ' /I '.sprintf(" %.4F", $pl['opt']['be']['i']);
  5182. }
  5183. $annots .= '>>';
  5184. }
  5185. $annots .= ' /C [';
  5186. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
  5187. foreach ($pl['opt']['c'] as $col) {
  5188. $col = intval($col);
  5189. $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
  5190. $annots .= sprintf(" %.4F", $color);
  5191. }
  5192. }
  5193. $annots .= ']';
  5194. //$annots .= ' /StructParent ';
  5195. //$annots .= ' /OC ';
  5196. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  5197. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  5198. // this is a markup type
  5199. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  5200. $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
  5201. }
  5202. //$annots .= ' /Popup ';
  5203. if (isset($pl['opt']['ca'])) {
  5204. $annots .= ' /CA '.sprintf("%.4F", floatval($pl['opt']['ca']));
  5205. }
  5206. if (isset($pl['opt']['rc'])) {
  5207. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
  5208. }
  5209. $annots .= ' /CreationDate '.$this->_datastring('D:'.date('YmdHis'));
  5210. //$annots .= ' /IRT ';
  5211. if (isset($pl['opt']['subj'])) {
  5212. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
  5213. }
  5214. //$annots .= ' /RT ';
  5215. //$annots .= ' /IT ';
  5216. //$annots .= ' /ExData ';
  5217. }
  5218. switch (strtolower($pl['opt']['subtype'])) {
  5219. case 'text': {
  5220. if (isset($pl['opt']['open'])) {
  5221. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  5222. }
  5223. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  5224. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  5225. $annots .= ' /Name /'.$pl['opt']['name'];
  5226. } else {
  5227. $annots .= ' /Name /Note';
  5228. }
  5229. $statemodels = array('Marked', 'Review');
  5230. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  5231. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  5232. } else {
  5233. $pl['opt']['statemodel'] = 'Marked';
  5234. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  5235. }
  5236. if ($pl['opt']['statemodel'] == 'Marked') {
  5237. $states = array('Accepted', 'Unmarked');
  5238. } else {
  5239. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  5240. }
  5241. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  5242. $annots .= ' /State /'.$pl['opt']['state'];
  5243. } else {
  5244. if ($pl['opt']['statemodel'] == 'Marked') {
  5245. $annots .= ' /State /Unmarked';
  5246. } else {
  5247. $annots .= ' /State /None';
  5248. }
  5249. }
  5250. break;
  5251. }
  5252. case 'link': {
  5253. if(is_string($pl['txt'])) {
  5254. // external URI link
  5255. $annots .= ' /A <</S /URI /URI '.$this->_datastring($pl['txt']).'>>';
  5256. } else {
  5257. // internal link
  5258. $l = $this->links[$pl['txt']];
  5259. $annots .= sprintf(' /Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $l[0])), ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
  5260. }
  5261. $hmodes = array('N', 'I', 'O', 'P');
  5262. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  5263. $annots .= ' /H /'.$pl['opt']['h'];
  5264. } else {
  5265. $annots .= ' /H /I';
  5266. }
  5267. //$annots .= ' /PA ';
  5268. //$annots .= ' /Quadpoints ';
  5269. break;
  5270. }
  5271. case 'freetext': {
  5272. $annots .= ' /DA '.$this->_textstring($pl['txt']);
  5273. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  5274. $annots .= ' /Q '.intval($pl['opt']['q']);
  5275. }
  5276. if (isset($pl['opt']['rc'])) {
  5277. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
  5278. }
  5279. if (isset($pl['opt']['ds'])) {
  5280. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
  5281. }
  5282. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  5283. $annots .= ' /CL [';
  5284. foreach ($pl['opt']['cl'] as $cl) {
  5285. $annots .= sprintf("%.4F ", $cl * $this->k);
  5286. }
  5287. $annots .= ']';
  5288. }
  5289. $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
  5290. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  5291. $annots .= ' /IT '.$pl['opt']['it'];
  5292. }
  5293. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  5294. $l = $pl['opt']['rd'][0] * $this->k;
  5295. $r = $pl['opt']['rd'][1] * $this->k;
  5296. $t = $pl['opt']['rd'][2] * $this->k;
  5297. $b = $pl['opt']['rd'][3] * $this->k;
  5298. $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
  5299. }
  5300. //$annots .= ' /LE ';
  5301. break;
  5302. }
  5303. // ... to be completed ...
  5304. case 'line': {
  5305. break;
  5306. }
  5307. case 'square': {
  5308. break;
  5309. }
  5310. case 'circle': {
  5311. break;
  5312. }
  5313. case 'polygon': {
  5314. break;
  5315. }
  5316. case 'polyline': {
  5317. break;
  5318. }
  5319. case 'highlight': {
  5320. break;
  5321. }
  5322. case 'underline': {
  5323. break;
  5324. }
  5325. case 'squiggly': {
  5326. break;
  5327. }
  5328. case 'strikeout': {
  5329. break;
  5330. }
  5331. case 'stamp': {
  5332. break;
  5333. }
  5334. case 'caret': {
  5335. break;
  5336. }
  5337. case 'ink': {
  5338. break;
  5339. }
  5340. case 'popup': {
  5341. break;
  5342. }
  5343. case 'fileattachment': {
  5344. if (!isset($pl['opt']['fs'])) {
  5345. break;
  5346. }
  5347. $filename = basename($pl['opt']['fs']);
  5348. if (isset($this->embeddedfiles[$filename]['n'])) {
  5349. $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
  5350. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  5351. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  5352. $annots .= ' /Name /'.$pl['opt']['name'];
  5353. } else {
  5354. $annots .= ' /Name /PushPin';
  5355. }
  5356. }
  5357. break;
  5358. }
  5359. case 'sound': {
  5360. if (!isset($pl['opt']['sound'])) {
  5361. break;
  5362. }
  5363. $filename = basename($pl['opt']['sound']);
  5364. if (isset($this->embeddedfiles[$filename]['n'])) {
  5365. // ... TO BE COMPLETED ...
  5366. $iconsapp = array('Speaker', 'Mic');
  5367. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  5368. $annots .= ' /Name /'.$pl['opt']['name'];
  5369. } else {
  5370. $annots .= ' /Name /Speaker';
  5371. }
  5372. }
  5373. break;
  5374. }
  5375. case 'movie': {
  5376. break;
  5377. }
  5378. case 'widget': {
  5379. if (isset($pl['opt']['h'])) {
  5380. $annots .= ' /H '.intval($pl['opt']['h']);
  5381. }
  5382. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk']))) {
  5383. $annots .= ' /MK <<';
  5384. // ... TO BE COMPLETED ...
  5385. $annots .= '>>';
  5386. }
  5387. break;
  5388. }
  5389. case 'screen': {
  5390. break;
  5391. }
  5392. case 'printermark': {
  5393. break;
  5394. }
  5395. case 'trapnet': {
  5396. break;
  5397. }
  5398. case 'watermark': {
  5399. break;
  5400. }
  5401. case '3d': {
  5402. break;
  5403. }
  5404. default: {
  5405. break;
  5406. }
  5407. }
  5408. $annots .= '>>';
  5409. }
  5410. $annots .= "\n]";
  5411. $this->_out($annots);
  5412. }
  5413. }
  5414. /**
  5415. * Output fonts.
  5416. * @access protected
  5417. */
  5418. protected function _putfonts() {
  5419. $nf = $this->n;
  5420. foreach ($this->diffs as $diff) {
  5421. //Encodings
  5422. $this->_newobj();
  5423. $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
  5424. $this->_out('endobj');
  5425. }
  5426. $mqr = get_magic_quotes_runtime();
  5427. //set_magic_quotes_runtime(0);
  5428. foreach ($this->FontFiles as $file => $info) {
  5429. // search and get font file to embedd
  5430. $fontdir = $info['fontdir'];
  5431. $file = strtolower($file);
  5432. $fontfile = '';
  5433. // search files on various directories
  5434. if (file_exists($fontdir.$file)) {
  5435. $fontfile = $fontdir.$file;
  5436. } elseif (file_exists($this->_getfontpath().$file)) {
  5437. $fontfile = $this->_getfontpath().$file;
  5438. } elseif (file_exists($file)) {
  5439. $fontfile = $file;
  5440. }
  5441. if (!$this->empty_string($fontfile)) {
  5442. $font = file_get_contents($fontfile);
  5443. $compressed = (substr($file, -2) == '.z');
  5444. if ((!$compressed) AND (isset($info['length2']))) {
  5445. $header = (ord($font{0}) == 128);
  5446. if ($header) {
  5447. //Strip first binary header
  5448. $font = substr($font, 6);
  5449. }
  5450. if ($header AND (ord($font{$info['length1']}) == 128)) {
  5451. //Strip second binary header
  5452. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  5453. }
  5454. }
  5455. $this->_newobj();
  5456. $this->FontFiles[$file]['n'] = $this->n;
  5457. $this->_out('<</Length '.strlen($font));
  5458. if ($compressed) {
  5459. $this->_out('/Filter /FlateDecode');
  5460. }
  5461. $this->_out('/Length1 '.$info['length1']);
  5462. if (isset($info['length2'])) {
  5463. $this->_out('/Length2 '.$info['length2'].' /Length3 0');
  5464. }
  5465. $this->_out('>>');
  5466. $this->_putstream($font);
  5467. $this->_out('endobj');
  5468. }
  5469. }
  5470. //set_magic_quotes_runtime($mqr);
  5471. foreach ($this->fontkeys as $k) {
  5472. //Font objects
  5473. $this->setFontSubBuffer($k, 'n', $this->n + 1);
  5474. $font = $this->getFontBuffer($k);
  5475. $type = $font['type'];
  5476. $name = $font['name'];
  5477. if ($type == 'core') {
  5478. //Standard font
  5479. $this->_newobj();
  5480. $this->_out('<</Type /Font');
  5481. $this->_out('/BaseFont /'.$name);
  5482. $this->_out('/Subtype /Type1');
  5483. if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
  5484. $this->_out('/Encoding /WinAnsiEncoding');
  5485. }
  5486. $this->_out('>>');
  5487. $this->_out('endobj');
  5488. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  5489. //Additional Type1 or TrueType font
  5490. $this->_newobj();
  5491. $this->_out('<</Type /Font');
  5492. $this->_out('/BaseFont /'.$name);
  5493. $this->_out('/Subtype /'.$type);
  5494. $this->_out('/FirstChar 32 /LastChar 255');
  5495. $this->_out('/Widths '.($this->n + 1).' 0 R');
  5496. $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
  5497. if ($font['enc']) {
  5498. if (isset($font['diff'])) {
  5499. $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
  5500. } else {
  5501. $this->_out('/Encoding /WinAnsiEncoding');
  5502. }
  5503. }
  5504. $this->_out('>>');
  5505. $this->_out('endobj');
  5506. // Widths
  5507. $this->_newobj();
  5508. $cw = &$font['cw'];
  5509. $s = '[';
  5510. for ($i = 32; $i < 256; ++$i) {
  5511. $s .= $cw[$i].' ';
  5512. }
  5513. $this->_out($s.']');
  5514. $this->_out('endobj');
  5515. //Descriptor
  5516. $this->_newobj();
  5517. $s = '<</Type /FontDescriptor /FontName /'.$name;
  5518. foreach ($font['desc'] as $k => $v) {
  5519. $s .= ' /'.$k.' '.$v.'';
  5520. }
  5521. if (!$this->empty_string($font['file'])) {
  5522. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  5523. }
  5524. $this->_out($s.'>>');
  5525. $this->_out('endobj');
  5526. } else {
  5527. //Allow for additional types
  5528. $mtd = '_put'.strtolower($type);
  5529. if (!method_exists($this, $mtd)) {
  5530. $this->Error('Unsupported font type: '.$type);
  5531. }
  5532. $this->$mtd($font);
  5533. }
  5534. }
  5535. }
  5536. /**
  5537. * Outputs font widths
  5538. * @parameter array $font font data
  5539. * @parameter int $cidoffset offset for CID values
  5540. * @author Nicola Asuni
  5541. * @access protected
  5542. * @since 4.4.000 (2008-12-07)
  5543. */
  5544. protected function _putfontwidths($font, $cidoffset=0) {
  5545. ksort($font['cw']);
  5546. $rangeid = 0;
  5547. $range = array();
  5548. $prevcid = -2;
  5549. $prevwidth = -1;
  5550. $interval = false;
  5551. // for each character
  5552. foreach ($font['cw'] as $cid => $width) {
  5553. $cid -= $cidoffset;
  5554. if ($width != $font['dw']) {
  5555. if ($cid == ($prevcid + 1)) {
  5556. // consecutive CID
  5557. if ($width == $prevwidth) {
  5558. if ($width == $range[$rangeid][0]) {
  5559. $range[$rangeid][] = $width;
  5560. } else {
  5561. array_pop($range[$rangeid]);
  5562. // new range
  5563. $rangeid = $prevcid;
  5564. $range[$rangeid] = array();
  5565. $range[$rangeid][] = $prevwidth;
  5566. $range[$rangeid][] = $width;
  5567. }
  5568. $interval = true;
  5569. $range[$rangeid]['interval'] = true;
  5570. } else {
  5571. if ($interval) {
  5572. // new range
  5573. $rangeid = $cid;
  5574. $range[$rangeid] = array();
  5575. $range[$rangeid][] = $width;
  5576. } else {
  5577. $range[$rangeid][] = $width;
  5578. }
  5579. $interval = false;
  5580. }
  5581. } else {
  5582. // new range
  5583. $rangeid = $cid;
  5584. $range[$rangeid] = array();
  5585. $range[$rangeid][] = $width;
  5586. $interval = false;
  5587. }
  5588. $prevcid = $cid;
  5589. $prevwidth = $width;
  5590. }
  5591. }
  5592. // optimize ranges
  5593. $prevk = -1;
  5594. $nextk = -1;
  5595. $prevint = false;
  5596. foreach ($range as $k => $ws) {
  5597. $cws = count($ws);
  5598. if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
  5599. if (isset($range[$k]['interval'])) {
  5600. unset($range[$k]['interval']);
  5601. }
  5602. $range[$prevk] = array_merge($range[$prevk], $range[$k]);
  5603. unset($range[$k]);
  5604. } else {
  5605. $prevk = $k;
  5606. }
  5607. $nextk = $k + $cws;
  5608. if (isset($ws['interval'])) {
  5609. if ($cws > 3) {
  5610. $prevint = true;
  5611. } else {
  5612. $prevint = false;
  5613. }
  5614. unset($range[$k]['interval']);
  5615. --$nextk;
  5616. } else {
  5617. $prevint = false;
  5618. }
  5619. }
  5620. // output data
  5621. $w = '';
  5622. foreach ($range as $k => $ws) {
  5623. if (count(array_count_values($ws)) == 1) {
  5624. // interval mode is more compact
  5625. $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
  5626. } else {
  5627. // range mode
  5628. $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
  5629. }
  5630. }
  5631. $this->_out('/W ['.$w.' ]');
  5632. }
  5633. /**
  5634. * Adds unicode fonts.<br>
  5635. * Based on PDF Reference 1.3 (section 5)
  5636. * @parameter array $font font data
  5637. * @access protected
  5638. * @author Nicola Asuni
  5639. * @since 1.52.0.TC005 (2005-01-05)
  5640. */
  5641. protected function _puttruetypeunicode($font) {
  5642. // Type0 Font
  5643. // A composite font composed of other fonts, organized hierarchically
  5644. $this->_newobj();
  5645. $this->_out('<</Type /Font');
  5646. $this->_out('/Subtype /Type0');
  5647. $this->_out('/BaseFont /'.$font['name'].'');
  5648. $this->_out('/Encoding /Identity-H'); //The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
  5649. $this->_out('/ToUnicode /Identity-H');
  5650. $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
  5651. $this->_out('>>');
  5652. $this->_out('endobj');
  5653. // CIDFontType2
  5654. // A CIDFont whose glyph descriptions are based on TrueType font technology
  5655. $this->_newobj();
  5656. $this->_out('<</Type /Font');
  5657. $this->_out('/Subtype /CIDFontType2');
  5658. $this->_out('/BaseFont /'.$font['name'].'');
  5659. // A dictionary containing entries that define the character collection of the CIDFont.
  5660. $cidinfo = '/Registry '.$this->_datastring('Adobe');
  5661. $cidinfo .= ' /Ordering '.$this->_datastring('Identity');
  5662. $cidinfo .= ' /Supplement 0';
  5663. $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
  5664. $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
  5665. $this->_out('/DW '.$font['dw'].''); // default width
  5666. $this->_putfontwidths($font, 0);
  5667. $this->_out('/CIDToGIDMap '.($this->n + 2).' 0 R');
  5668. $this->_out('>>');
  5669. $this->_out('endobj');
  5670. // Font descriptor
  5671. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  5672. $this->_newobj();
  5673. $this->_out('<</Type /FontDescriptor');
  5674. $this->_out('/FontName /'.$font['name']);
  5675. foreach ($font['desc'] as $key => $value) {
  5676. $this->_out('/'.$key.' '.$value);
  5677. }
  5678. $fontdir = '';
  5679. if (!$this->empty_string($font['file'])) {
  5680. // A stream containing a TrueType font
  5681. $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
  5682. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  5683. }
  5684. $this->_out('>>');
  5685. $this->_out('endobj');
  5686. $this->_newobj();
  5687. if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
  5688. // Embed CIDToGIDMap
  5689. // A specification of the mapping from CIDs to glyph indices
  5690. // search and get CTG font file to embedd
  5691. $ctgfile = strtolower($font['ctg']);
  5692. // search and get ctg font file to embedd
  5693. $fontfile = '';
  5694. // search files on various directories
  5695. if (file_exists($fontdir.$ctgfile)) {
  5696. $fontfile = $fontdir.$ctgfile;
  5697. } elseif (file_exists($this->_getfontpath().$ctgfile)) {
  5698. $fontfile = $this->_getfontpath().$ctgfile;
  5699. } elseif (file_exists($ctgfile)) {
  5700. $fontfile = $ctgfile;
  5701. }
  5702. if ($this->empty_string($fontfile)) {
  5703. $this->Error('Font file not found: '.$ctgfile);
  5704. }
  5705. $size = filesize($fontfile);
  5706. $this->_out('<</Length '.$size.'');
  5707. if (substr($fontfile, -2) == '.z') { // check file extension
  5708. // Decompresses data encoded using the public-domain
  5709. // zlib/deflate compression method, reproducing the
  5710. // original text or binary data
  5711. $this->_out('/Filter /FlateDecode');
  5712. }
  5713. $this->_out('>>');
  5714. $this->_putstream(file_get_contents($fontfile));
  5715. }
  5716. $this->_out('endobj');
  5717. }
  5718. /**
  5719. * Output CID-0 fonts.
  5720. * @param array $font font data
  5721. * @access protected
  5722. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  5723. * @since 3.2.000 (2008-06-23)
  5724. */
  5725. protected function _putcidfont0($font) {
  5726. $cidoffset = 31;
  5727. if (isset($font['cidinfo']['uni2cid'])) {
  5728. // convert unicode to cid.
  5729. $uni2cid = $font['cidinfo']['uni2cid'];
  5730. $cw = array();
  5731. foreach ($font['cw'] as $uni => $width) {
  5732. if (isset($uni2cid[$uni])) {
  5733. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  5734. } elseif ($uni < 256) {
  5735. $cw[$uni] = $width;
  5736. } // else unknown character
  5737. }
  5738. $font = array_merge($font, array('cw' => $cw));
  5739. }
  5740. $name = $font['name'];
  5741. $enc = $font['enc'];
  5742. if ($enc) {
  5743. $longname = $name.'-'.$enc;
  5744. } else {
  5745. $longname = $name;
  5746. }
  5747. $this->_newobj();
  5748. $this->_out('<</Type /Font');
  5749. $this->_out('/BaseFont /'.$longname);
  5750. $this->_out('/Subtype /Type0');
  5751. if ($enc) {
  5752. $this->_out('/Encoding /'.$enc);
  5753. }
  5754. $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
  5755. $this->_out('>>');
  5756. $this->_out('endobj');
  5757. $this->_newobj();
  5758. $this->_out('<</Type /Font');
  5759. $this->_out('/BaseFont /'.$name);
  5760. $this->_out('/Subtype /CIDFontType0');
  5761. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry']);
  5762. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering']);
  5763. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  5764. $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
  5765. $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
  5766. $this->_out('/DW '.$font['dw']);
  5767. $this->_putfontwidths($font, $cidoffset);
  5768. $this->_out('>>');
  5769. $this->_out('endobj');
  5770. $this->_newobj();
  5771. $s = '<</Type /FontDescriptor /FontName /'.$name;
  5772. foreach ($font['desc'] as $k => $v) {
  5773. if ($k != 'Style') {
  5774. $s .= ' /'.$k.' '.$v.'';
  5775. }
  5776. }
  5777. $this->_out($s.'>>');
  5778. $this->_out('endobj');
  5779. }
  5780. /**
  5781. * Output images.
  5782. * @access protected
  5783. */
  5784. protected function _putimages() {
  5785. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  5786. foreach ($this->imagekeys as $file) {
  5787. $info = $this->getImageBuffer($file);
  5788. $this->_newobj();
  5789. $this->setImageSubBuffer($file, 'n', $this->n);
  5790. $this->_out('<</Type /XObject');
  5791. $this->_out('/Subtype /Image');
  5792. $this->_out('/Width '.$info['w']);
  5793. $this->_out('/Height '.$info['h']);
  5794. if (isset($info['masked'])) {
  5795. $this->_out('/SMask '.($this->n - 1).' 0 R');
  5796. }
  5797. if ($info['cs'] == 'Indexed') {
  5798. $this->_out('/ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]');
  5799. } else {
  5800. $this->_out('/ColorSpace /'.$info['cs']);
  5801. if ($info['cs'] == 'DeviceCMYK') {
  5802. $this->_out('/Decode [1 0 1 0 1 0 1 0]');
  5803. }
  5804. }
  5805. $this->_out('/BitsPerComponent '.$info['bpc']);
  5806. if (isset($info['f'])) {
  5807. $this->_out('/Filter /'.$info['f']);
  5808. }
  5809. if (isset($info['parms'])) {
  5810. $this->_out($info['parms']);
  5811. }
  5812. if (isset($info['trns']) AND is_array($info['trns'])) {
  5813. $trns='';
  5814. $count_info = count($info['trns']);
  5815. for ($i=0; $i < $count_info; ++$i) {
  5816. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  5817. }
  5818. $this->_out('/Mask ['.$trns.']');
  5819. }
  5820. $this->_out('/Length '.strlen($info['data']).'>>');
  5821. $this->_putstream($info['data']);
  5822. $this->_out('endobj');
  5823. //Palette
  5824. if ($info['cs'] == 'Indexed') {
  5825. $this->_newobj();
  5826. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  5827. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
  5828. $this->_putstream($pal);
  5829. $this->_out('endobj');
  5830. }
  5831. }
  5832. }
  5833. /**
  5834. * Output Spot Colors Resources.
  5835. * @access protected
  5836. * @since 4.0.024 (2008-09-12)
  5837. */
  5838. protected function _putspotcolors() {
  5839. foreach ($this->spot_colors as $name => $color) {
  5840. $this->_newobj();
  5841. $this->spot_colors[$name]['n'] = $this->n;
  5842. $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
  5843. $this->_out('/DeviceCMYK <<');
  5844. $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
  5845. $this->_out(sprintf('/C1 [%.4F %.4F %.4F %.4F] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
  5846. $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
  5847. $this->_out('endobj');
  5848. }
  5849. }
  5850. /**
  5851. * Output object dictionary for images.
  5852. * @access protected
  5853. */
  5854. protected function _putxobjectdict() {
  5855. foreach ($this->imagekeys as $file) {
  5856. $info = $this->getImageBuffer($file);
  5857. $this->_out('/I'.$info['i'].' '.$info['n'].' 0 R');
  5858. }
  5859. }
  5860. /**
  5861. * Output Resources Dictionary.
  5862. * @access protected
  5863. */
  5864. protected function _putresourcedict() {
  5865. $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  5866. $this->_out('/Font <<');
  5867. foreach ($this->fontkeys as $fontkey) {
  5868. $font = $this->getFontBuffer($fontkey);
  5869. $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
  5870. }
  5871. $this->_out('>>');
  5872. $this->_out('/XObject <<');
  5873. $this->_putxobjectdict();
  5874. $this->_out('>>');
  5875. // visibility
  5876. $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
  5877. // transparency
  5878. $this->_out('/ExtGState <<');
  5879. foreach ($this->extgstates as $k => $extgstate) {
  5880. $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
  5881. }
  5882. $this->_out('>>');
  5883. // gradients
  5884. if (isset($this->gradients) AND (count($this->gradients) > 0)) {
  5885. $this->_out('/Shading <<');
  5886. foreach ($this->gradients as $id => $grad) {
  5887. $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
  5888. }
  5889. $this->_out('>>');
  5890. }
  5891. // spot colors
  5892. if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
  5893. $this->_out('/ColorSpace <<');
  5894. foreach ($this->spot_colors as $color) {
  5895. $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
  5896. }
  5897. $this->_out('>>');
  5898. }
  5899. }
  5900. /**
  5901. * Output Resources.
  5902. * @access protected
  5903. */
  5904. protected function _putresources() {
  5905. $this->_putextgstates();
  5906. $this->_putocg();
  5907. $this->_putfonts();
  5908. $this->_putimages();
  5909. $this->_putspotcolors();
  5910. $this->_putshaders();
  5911. //Resource dictionary
  5912. $this->offsets[2] = $this->bufferlen;
  5913. $this->_out('2 0 obj');
  5914. $this->_out('<<');
  5915. $this->_putresourcedict();
  5916. $this->_out('>>');
  5917. $this->_out('endobj');
  5918. $this->_putjavascript();
  5919. $this->_putbookmarks();
  5920. $this->_putEmbeddedFiles();
  5921. // encryption
  5922. if ($this->encrypted) {
  5923. $this->_newobj();
  5924. $this->enc_obj_id = $this->n;
  5925. $this->_out('<<');
  5926. $this->_putencryption();
  5927. $this->_out('>>');
  5928. $this->_out('endobj');
  5929. }
  5930. }
  5931. /**
  5932. * Adds some Metadata information
  5933. * (see Chapter 10.2 of PDF Reference)
  5934. * @access protected
  5935. */
  5936. protected function _putinfo() {
  5937. if (!$this->empty_string($this->title)) {
  5938. $this->_out('/Title '.$this->_textstring($this->title));
  5939. }
  5940. if (!$this->empty_string($this->author)) {
  5941. $this->_out('/Author '.$this->_textstring($this->author));
  5942. }
  5943. if (!$this->empty_string($this->subject)) {
  5944. $this->_out('/Subject '.$this->_textstring($this->subject));
  5945. }
  5946. if (!$this->empty_string($this->keywords)) {
  5947. $this->_out('/Keywords '.$this->_textstring($this->keywords));
  5948. }
  5949. if (!$this->empty_string($this->creator)) {
  5950. $this->_out('/Creator '.$this->_textstring($this->creator));
  5951. }
  5952. if (defined('PDF_PRODUCER')) {
  5953. $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
  5954. }
  5955. $this->_out('/CreationDate '.$this->_datastring('D:'.date('YmdHis')));
  5956. $this->_out('/ModDate '.$this->_datastring('D:'.date('YmdHis')));
  5957. }
  5958. /**
  5959. * Output Catalog.
  5960. * @access protected
  5961. */
  5962. protected function _putcatalog() {
  5963. $this->_out('/Type /Catalog');
  5964. $this->_out('/Pages 1 0 R');
  5965. if ($this->ZoomMode == 'fullpage') {
  5966. $this->_out('/OpenAction [3 0 R /Fit]');
  5967. } elseif ($this->ZoomMode == 'fullwidth') {
  5968. $this->_out('/OpenAction [3 0 R /FitH null]');
  5969. } elseif ($this->ZoomMode == 'real') {
  5970. $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
  5971. } elseif (!is_string($this->ZoomMode)) {
  5972. $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
  5973. }
  5974. if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
  5975. $this->_out('/PageLayout /'.$this->LayoutMode.'');
  5976. }
  5977. if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
  5978. $this->_out('/PageMode /'.$this->PageMode);
  5979. }
  5980. if (isset($this->l['a_meta_language'])) {
  5981. $this->_out('/Lang /'.$this->l['a_meta_language']);
  5982. }
  5983. $this->_out('/Names <<');
  5984. if (!$this->empty_string($this->javascript)) {
  5985. $this->_out('/JavaScript '.($this->n_js).' 0 R');
  5986. }
  5987. $this->_out('>>');
  5988. if (count($this->outlines) > 0) {
  5989. $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
  5990. $this->_out('/PageMode /UseOutlines');
  5991. }
  5992. $this->_putviewerpreferences();
  5993. $p = $this->n_ocg_print.' 0 R';
  5994. $v = $this->n_ocg_view.' 0 R';
  5995. $as = '<</Event /Print /OCGs ['.$p.' '.$v.'] /Category [/Print]>> <</Event /View /OCGs ['.$p.' '.$v.'] /Category [/View]>>';
  5996. $this->_out('/OCProperties <</OCGs ['.$p.' '.$v.'] /D <</ON ['.$p.'] /OFF ['.$v.'] /AS ['.$as.']>>>>');
  5997. }
  5998. /**
  5999. * Output viewer preferences.
  6000. * @author Nicola asuni
  6001. * @since 3.1.000 (2008-06-09)
  6002. * @access protected
  6003. */
  6004. protected function _putviewerpreferences() {
  6005. $this->_out('/ViewerPreferences<<');
  6006. if ($this->rtl) {
  6007. $this->_out('/Direction /R2L');
  6008. } else {
  6009. $this->_out('/Direction /L2R');
  6010. }
  6011. if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
  6012. $this->_out('/HideToolbar true');
  6013. }
  6014. if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
  6015. $this->_out('/HideMenubar true');
  6016. }
  6017. if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
  6018. $this->_out('/HideWindowUI true');
  6019. }
  6020. if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
  6021. $this->_out('/FitWindow true');
  6022. }
  6023. if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
  6024. $this->_out('/CenterWindow true');
  6025. }
  6026. if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
  6027. $this->_out('/DisplayDocTitle true');
  6028. }
  6029. if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
  6030. $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
  6031. }
  6032. if (isset($this->viewer_preferences['ViewArea'])) {
  6033. $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
  6034. }
  6035. if (isset($this->viewer_preferences['ViewClip'])) {
  6036. $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
  6037. }
  6038. if (isset($this->viewer_preferences['PrintArea'])) {
  6039. $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
  6040. }
  6041. if (isset($this->viewer_preferences['PrintClip'])) {
  6042. $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
  6043. }
  6044. if (isset($this->viewer_preferences['PrintScaling'])) {
  6045. $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
  6046. }
  6047. if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
  6048. $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
  6049. }
  6050. if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
  6051. if ($this->viewer_preferences['PickTrayByPDFSize']) {
  6052. $this->_out('/PickTrayByPDFSize true');
  6053. } else {
  6054. $this->_out('/PickTrayByPDFSize false');
  6055. }
  6056. }
  6057. if (isset($this->viewer_preferences['PrintPageRange'])) {
  6058. $PrintPageRangeNum = '';
  6059. foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
  6060. $PrintPageRangeNum .= ' '.($v - 1).'';
  6061. }
  6062. $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
  6063. }
  6064. if (isset($this->viewer_preferences['NumCopies'])) {
  6065. $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
  6066. }
  6067. $this->_out('>>');
  6068. }
  6069. /**
  6070. * Output trailer.
  6071. * @access protected
  6072. */
  6073. protected function _puttrailer() {
  6074. $this->_out('/Size '.($this->n + 1));
  6075. $this->_out('/Root '.$this->n.' 0 R');
  6076. $this->_out('/Info '.($this->n - 1).' 0 R');
  6077. if ($this->encrypted) {
  6078. $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
  6079. $this->_out('/ID [()()]');
  6080. }
  6081. }
  6082. /**
  6083. * Output PDF header.
  6084. * @access protected
  6085. */
  6086. protected function _putheader() {
  6087. $this->_out('%PDF-'.$this->PDFVersion);
  6088. }
  6089. /**
  6090. * Output end of document (EOF).
  6091. * @access protected
  6092. */
  6093. protected function _enddoc() {
  6094. $this->state = 1;
  6095. $this->_putheader();
  6096. $this->_putpages();
  6097. $this->_putresources();
  6098. //Info
  6099. $this->_newobj();
  6100. $this->_out('<<');
  6101. $this->_putinfo();
  6102. $this->_out('>>');
  6103. $this->_out('endobj');
  6104. //Catalog
  6105. $this->_newobj();
  6106. $this->_out('<<');
  6107. $this->_putcatalog();
  6108. $this->_putcertification();
  6109. $this->_putuserrights();
  6110. $this->_out('>>');
  6111. $this->_out('endobj');
  6112. //Cross-ref
  6113. $o = $this->bufferlen;
  6114. $this->_out('xref');
  6115. $this->_out('0 '.($this->n + 1));
  6116. $this->_out('0000000000 65535 f ');
  6117. for ($i=1; $i <= $this->n; ++$i) {
  6118. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  6119. }
  6120. if (isset($this->embeddedfiles) AND count($this->embeddedfiles) > 0) {
  6121. $this->_out('100000 '.count($this->embeddedfiles));
  6122. foreach ($this->embeddedfiles as $filename => $filedata) {
  6123. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$filedata['n']]));
  6124. }
  6125. }
  6126. //Trailer
  6127. $this->_out('trailer');
  6128. $this->_out('<<');
  6129. $this->_puttrailer();
  6130. $this->_out('>>');
  6131. $this->_out('startxref');
  6132. $this->_out($o);
  6133. $this->_out('%%EOF');
  6134. $this->state = 3; // end-of-doc
  6135. if ($this->diskcache) {
  6136. // remove temporary files used for images
  6137. foreach ($this->imagekeys as $key) {
  6138. // remove temporary files
  6139. unlink($this->images[$key]);
  6140. }
  6141. foreach ($this->fontkeys as $key) {
  6142. // remove temporary files
  6143. unlink($this->fonts[$key]);
  6144. }
  6145. }
  6146. }
  6147. /**
  6148. * Initialize a new page.
  6149. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  6150. * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
  6151. * @access protected
  6152. */
  6153. protected function _beginpage($orientation='', $format='') {
  6154. ++$this->page;
  6155. $this->setPageBuffer($this->page, '');
  6156. // initialize array for graphics tranformation positions inside a page buffer
  6157. $this->transfmrk[$this->page] = array();
  6158. $this->state = 2;
  6159. if ($this->empty_string($orientation)) {
  6160. if (isset($this->CurOrientation)) {
  6161. $orientation = $this->CurOrientation;
  6162. } else {
  6163. $orientation = 'P';
  6164. }
  6165. }
  6166. if ($this->empty_string($format)) {
  6167. $this->setPageOrientation($orientation);
  6168. } else {
  6169. $this->setPageFormat($format, $orientation);
  6170. }
  6171. if ($this->rtl) {
  6172. $this->x = $this->w - $this->rMargin;
  6173. } else {
  6174. $this->x = $this->lMargin;
  6175. }
  6176. $this->y = $this->tMargin;
  6177. if (isset($this->newpagegroup[$this->page])) {
  6178. // start a new group
  6179. $n = sizeof($this->pagegroups) + 1;
  6180. $alias = '{nb'.$n.'}';
  6181. $this->pagegroups[$alias] = 1;
  6182. $this->currpagegroup = $alias;
  6183. } elseif ($this->currpagegroup) {
  6184. ++$this->pagegroups[$this->currpagegroup];
  6185. }
  6186. }
  6187. /**
  6188. * Mark end of page.
  6189. * @access protected
  6190. */
  6191. protected function _endpage() {
  6192. $this->setVisibility('all');
  6193. $this->state = 1;
  6194. }
  6195. /**
  6196. * Begin a new object.
  6197. * @access protected
  6198. */
  6199. protected function _newobj() {
  6200. ++$this->n;
  6201. $this->offsets[$this->n] = $this->bufferlen;
  6202. $this->_out($this->n.' 0 obj');
  6203. }
  6204. /**
  6205. * Underline text.
  6206. * @param int $x X coordinate
  6207. * @param int $y Y coordinate
  6208. * @param string $txt text to underline
  6209. * @access protected
  6210. */
  6211. protected function _dounderline($x, $y, $txt) {
  6212. $up = $this->CurrentFont['up'];
  6213. $ut = $this->CurrentFont['ut'];
  6214. $w = $this->GetStringWidth($txt);
  6215. return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
  6216. }
  6217. /**
  6218. * Line through text.
  6219. * @param int $x X coordinate
  6220. * @param int $y Y coordinate
  6221. * @param string $txt text to linethrough
  6222. * @access protected
  6223. */
  6224. protected function _dolinethrough($x, $y, $txt) {
  6225. $up = $this->CurrentFont['up'];
  6226. $ut = $this->CurrentFont['ut'];
  6227. $w = $this->GetStringWidth($txt);
  6228. return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - ($this->FontSize/2) - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
  6229. }
  6230. /**
  6231. * Read a 4-byte integer from file.
  6232. * @param string $f file name.
  6233. * @return 4-byte integer
  6234. * @access protected
  6235. */
  6236. protected function _freadint($f) {
  6237. $a = unpack('Ni', fread($f, 4));
  6238. return $a['i'];
  6239. }
  6240. /**
  6241. * Add "\" before "\", "(" and ")"
  6242. * @param string $s string to escape.
  6243. * @return string escaped string.
  6244. * @access protected
  6245. */
  6246. protected function _escape($s) {
  6247. // the chr(13) substitution fixes the Bugs item #1421290.
  6248. return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
  6249. }
  6250. /**
  6251. * Format a date string for meta information
  6252. * @param string $s date string to escape.
  6253. * @return string escaped string.
  6254. * @access protected
  6255. */
  6256. protected function _datastring($s) {
  6257. if ($this->encrypted) {
  6258. $s = $this->_RC4($this->_objectkey($this->n), $s);
  6259. }
  6260. return '('. $this->_escape($s).')';
  6261. }
  6262. /**
  6263. * Format a text string for meta information
  6264. * @param string $s string to escape.
  6265. * @return string escaped string.
  6266. * @access protected
  6267. */
  6268. protected function _textstring($s) {
  6269. if ($this->isunicode) {
  6270. //Convert string to UTF-16BE
  6271. $s = $this->UTF8ToUTF16BE($s, true);
  6272. }
  6273. return $this->_datastring($s);
  6274. }
  6275. /**
  6276. * Format a text string
  6277. * @param string $s string to escape.
  6278. * @return string escaped string.
  6279. * @access protected
  6280. */
  6281. protected function _escapetext($s) {
  6282. if ($this->isunicode) {
  6283. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  6284. $s = $this->UTF8ToLatin1($s);
  6285. } else {
  6286. //Convert string to UTF-16BE and reverse RTL language
  6287. $s = $this->utf8StrRev($s, false, $this->tmprtl);
  6288. }
  6289. }
  6290. return $this->_escape($s);
  6291. }
  6292. /**
  6293. * Output a stream.
  6294. * @param string $s string to output.
  6295. * @access protected
  6296. */
  6297. protected function _putstream($s) {
  6298. if ($this->encrypted) {
  6299. $s = $this->_RC4($this->_objectkey($this->n), $s);
  6300. }
  6301. $this->_out('stream');
  6302. $this->_out($s);
  6303. $this->_out('endstream');
  6304. }
  6305. /**
  6306. * Output a string to the document.
  6307. * @param string $s string to output.
  6308. * @access protected
  6309. */
  6310. protected function _out($s) {
  6311. if ($this->state == 2) {
  6312. if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  6313. // puts data before page footer
  6314. $pagebuff = $this->getPageBuffer($this->page);
  6315. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  6316. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  6317. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  6318. // update footer position
  6319. $this->footerpos[$this->page] += strlen($s."\n");
  6320. } else {
  6321. $this->setPageBuffer($this->page, $s."\n", true);
  6322. }
  6323. } else {
  6324. $this->setBuffer($s."\n");
  6325. }
  6326. }
  6327. /**
  6328. * Converts UTF-8 strings to codepoints array.<br>
  6329. * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
  6330. * Based on: http://www.faqs.org/rfcs/rfc3629.html
  6331. * <pre>
  6332. * Char. number range | UTF-8 octet sequence
  6333. * (hexadecimal) | (binary)
  6334. * --------------------+-----------------------------------------------
  6335. * 0000 0000-0000 007F | 0xxxxxxx
  6336. * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
  6337. * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
  6338. * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6339. * ---------------------------------------------------------------------
  6340. *
  6341. * ABFN notation:
  6342. * ---------------------------------------------------------------------
  6343. * UTF8-octets = *( UTF8-char )
  6344. * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
  6345. * UTF8-1 = %x00-7F
  6346. * UTF8-2 = %xC2-DF UTF8-tail
  6347. *
  6348. * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
  6349. * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
  6350. * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
  6351. * %xF4 %x80-8F 2( UTF8-tail )
  6352. * UTF8-tail = %x80-BF
  6353. * ---------------------------------------------------------------------
  6354. * </pre>
  6355. * @param string $str string to process.
  6356. * @return array containing codepoints (UTF-8 characters values)
  6357. * @access protected
  6358. * @author Nicola Asuni
  6359. * @since 1.53.0.TC005 (2005-01-05)
  6360. */
  6361. protected function UTF8StringToArray($str) {
  6362. if (isset($this->cache_UTF8StringToArray['_'.$str])) {
  6363. // return cached value
  6364. return($this->cache_UTF8StringToArray['_'.$str]);
  6365. }
  6366. // check cache size
  6367. if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
  6368. // remove first element
  6369. array_shift($this->cache_UTF8StringToArray);
  6370. }
  6371. ++$this->cache_size_UTF8StringToArray;
  6372. if (!$this->isunicode) {
  6373. // split string into array of equivalent codes
  6374. $strarr = array();
  6375. $strlen = strlen($str);
  6376. for ($i=0; $i < $strlen; ++$i) {
  6377. $strarr[] = ord($str{$i});
  6378. }
  6379. // insert new value on cache
  6380. $this->cache_UTF8StringToArray['_'.$str] = $strarr;
  6381. return $strarr;
  6382. }
  6383. $unicode = array(); // array containing unicode values
  6384. $bytes = array(); // array containing single character byte sequences
  6385. $numbytes = 1; // number of octetc needed to represent the UTF-8 character
  6386. $str .= ''; // force $str to be a string
  6387. $length = strlen($str);
  6388. for ($i = 0; $i < $length; ++$i) {
  6389. $char = ord($str{$i}); // get one string character at time
  6390. if (count($bytes) == 0) { // get starting octect
  6391. if ($char <= 0x7F) {
  6392. $unicode[] = $char; // use the character "as is" because is ASCII
  6393. $numbytes = 1;
  6394. } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
  6395. $bytes[] = ($char - 0xC0) << 0x06;
  6396. $numbytes = 2;
  6397. } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
  6398. $bytes[] = ($char - 0xE0) << 0x0C;
  6399. $numbytes = 3;
  6400. } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
  6401. $bytes[] = ($char - 0xF0) << 0x12;
  6402. $numbytes = 4;
  6403. } else {
  6404. // use replacement character for other invalid sequences
  6405. $unicode[] = 0xFFFD;
  6406. $bytes = array();
  6407. $numbytes = 1;
  6408. }
  6409. } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  6410. $bytes[] = $char - 0x80;
  6411. if (count($bytes) == $numbytes) {
  6412. // compose UTF-8 bytes to a single unicode value
  6413. $char = $bytes[0];
  6414. for ($j = 1; $j < $numbytes; ++$j) {
  6415. $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
  6416. }
  6417. if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
  6418. /* The definition of UTF-8 prohibits encoding character numbers between
  6419. U+D800 and U+DFFF, which are reserved for use with the UTF-16
  6420. encoding form (as surrogate pairs) and do not directly represent
  6421. characters. */
  6422. $unicode[] = 0xFFFD; // use replacement character
  6423. } else {
  6424. $unicode[] = $char; // add char to array
  6425. }
  6426. // reset data for next char
  6427. $bytes = array();
  6428. $numbytes = 1;
  6429. }
  6430. } else {
  6431. // use replacement character for other invalid sequences
  6432. $unicode[] = 0xFFFD;
  6433. $bytes = array();
  6434. $numbytes = 1;
  6435. }
  6436. }
  6437. // insert new value on cache
  6438. $this->cache_UTF8StringToArray['_'.$str] = $unicode;
  6439. return $unicode;
  6440. }
  6441. /**
  6442. * Converts UTF-8 strings to UTF16-BE.<br>
  6443. * @param string $str string to process.
  6444. * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
  6445. * @return string
  6446. * @access protected
  6447. * @author Nicola Asuni
  6448. * @since 1.53.0.TC005 (2005-01-05)
  6449. * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
  6450. */
  6451. protected function UTF8ToUTF16BE($str, $setbom=true) {
  6452. if (!$this->isunicode) {
  6453. return $str; // string is not in unicode
  6454. }
  6455. $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
  6456. return $this->arrUTF8ToUTF16BE($unicode, $setbom);
  6457. }
  6458. /**
  6459. * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
  6460. * @param string $str string to process.
  6461. * @return string
  6462. * @author Andrew Whitehead, Nicola Asuni
  6463. * @access protected
  6464. * @since 3.2.000 (2008-06-23)
  6465. */
  6466. protected function UTF8ToLatin1($str) {
  6467. global $utf8tolatin;
  6468. if (!$this->isunicode) {
  6469. return $str; // string is not in unicode
  6470. }
  6471. $outstr = ''; // string to be returned
  6472. $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
  6473. foreach ($unicode as $char) {
  6474. if ($char < 256) {
  6475. $outstr .= chr($char);
  6476. } elseif (array_key_exists($char, $utf8tolatin)) {
  6477. // map from UTF-8
  6478. $outstr .= chr($utf8tolatin[$char]);
  6479. } elseif ($char == 0xFFFD) {
  6480. // skip
  6481. } else {
  6482. $outstr .= '?';
  6483. }
  6484. }
  6485. return $outstr;
  6486. }
  6487. /**
  6488. * Converts array of UTF-8 characters to UTF16-BE string.<br>
  6489. * Based on: http://www.faqs.org/rfcs/rfc2781.html
  6490. * <pre>
  6491. * Encoding UTF-16:
  6492. *
  6493. * Encoding of a single character from an ISO 10646 character value to
  6494. * UTF-16 proceeds as follows. Let U be the character number, no greater
  6495. * than 0x10FFFF.
  6496. *
  6497. * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
  6498. * terminate.
  6499. *
  6500. * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
  6501. * U' must be less than or equal to 0xFFFFF. That is, U' can be
  6502. * represented in 20 bits.
  6503. *
  6504. * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
  6505. * 0xDC00, respectively. These integers each have 10 bits free to
  6506. * encode the character value, for a total of 20 bits.
  6507. *
  6508. * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
  6509. * bits of W1 and the 10 low-order bits of U' to the 10 low-order
  6510. * bits of W2. Terminate.
  6511. *
  6512. * Graphically, steps 2 through 4 look like:
  6513. * U' = yyyyyyyyyyxxxxxxxxxx
  6514. * W1 = 110110yyyyyyyyyy
  6515. * W2 = 110111xxxxxxxxxx
  6516. * </pre>
  6517. * @param array $unicode array containing UTF-8 unicode values
  6518. * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
  6519. * @return string
  6520. * @access protected
  6521. * @author Nicola Asuni
  6522. * @since 2.1.000 (2008-01-08)
  6523. * @see UTF8ToUTF16BE()
  6524. */
  6525. protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
  6526. $outstr = ''; // string to be returned
  6527. if ($setbom) {
  6528. $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
  6529. }
  6530. foreach ($unicode as $char) {
  6531. if ($char == 0xFFFD) {
  6532. $outstr .= "\xFF\xFD"; // replacement character
  6533. } elseif ($char < 0x10000) {
  6534. $outstr .= chr($char >> 0x08);
  6535. $outstr .= chr($char & 0xFF);
  6536. } else {
  6537. $char -= 0x10000;
  6538. $w1 = 0xD800 | ($char >> 0x10);
  6539. $w2 = 0xDC00 | ($char & 0x3FF);
  6540. $outstr .= chr($w1 >> 0x08);
  6541. $outstr .= chr($w1 & 0xFF);
  6542. $outstr .= chr($w2 >> 0x08);
  6543. $outstr .= chr($w2 & 0xFF);
  6544. }
  6545. }
  6546. return $outstr;
  6547. }
  6548. // ====================================================
  6549. /**
  6550. * Set header font.
  6551. * @param array $font font
  6552. * @access public
  6553. * @since 1.1
  6554. */
  6555. public function setHeaderFont($font) {
  6556. $this->header_font = $font;
  6557. }
  6558. /**
  6559. * Get header font.
  6560. * @return array()
  6561. * @access public
  6562. * @since 4.0.012 (2008-07-24)
  6563. */
  6564. public function getHeaderFont() {
  6565. return $this->header_font;
  6566. }
  6567. /**
  6568. * Set footer font.
  6569. * @param array $font font
  6570. * @access public
  6571. * @since 1.1
  6572. */
  6573. public function setFooterFont($font) {
  6574. $this->footer_font = $font;
  6575. }
  6576. /**
  6577. * Get Footer font.
  6578. * @return array()
  6579. * @access public
  6580. * @since 4.0.012 (2008-07-24)
  6581. */
  6582. public function getFooterFont() {
  6583. return $this->footer_font;
  6584. }
  6585. /**
  6586. * Set language array.
  6587. * @param array $language
  6588. * @access public
  6589. * @since 1.1
  6590. */
  6591. public function setLanguageArray($language) {
  6592. $this->l = $language;
  6593. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  6594. }
  6595. /**
  6596. * Returns the PDF data.
  6597. * @access public
  6598. */
  6599. public function getPDFData() {
  6600. if ($this->state < 3) {
  6601. $this->Close();
  6602. }
  6603. return $this->buffer;
  6604. }
  6605. /**
  6606. * Output anchor link.
  6607. * @param string $url link URL or internal link (i.e.: &lt;a href="#23"&gt;link to page 23&lt;/a&gt;)
  6608. * @param string $name link name
  6609. * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  6610. * @param boolean $firstline if true prints only the first line and return the remaining string.
  6611. * @param array $color array of RGB text color
  6612. * @param string $style font style (U, D, B, I)
  6613. * @return the number of cells used or the remaining text if $firstline = true;
  6614. * @access public
  6615. */
  6616. public function addHtmlLink($url, $name, $fill=0, $firstline=false, $color='', $style=-1) {
  6617. if (!$this->empty_string($url) AND ($url{0} == '#')) {
  6618. // convert url to internal link
  6619. $page = intval(substr($url, 1));
  6620. $url = $this->AddLink();
  6621. $this->SetLink($url, 0, $page);
  6622. }
  6623. // store current settings
  6624. $prevcolor = $this->fgcolor;
  6625. $prevstyle = $this->FontStyle;
  6626. if (empty($color)) {
  6627. $this->SetTextColorArray($this->htmlLinkColorArray);
  6628. } else {
  6629. $this->SetTextColorArray($color);
  6630. }
  6631. if ($style == -1) {
  6632. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  6633. } else {
  6634. $this->SetFont('', $this->FontStyle.$style);
  6635. }
  6636. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
  6637. // restore settings
  6638. $this->SetFont('', $prevstyle);
  6639. $this->SetTextColorArray($prevcolor);
  6640. return $ret;
  6641. }
  6642. /**
  6643. * Returns an associative array (keys: R,G,B) from an html color name or a six-digit or three-digit hexadecimal color representation (i.e. #3FE5AA or #7FF).
  6644. * @param string $color html color
  6645. * @return array RGB color or false in case of error.
  6646. * @access public
  6647. */
  6648. public function convertHTMLColorToDec($color='#FFFFFF') {
  6649. global $webcolor;
  6650. $returncolor = false;
  6651. $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
  6652. $color = strtolower($color);
  6653. if (strlen($color) == 0) {
  6654. return false;
  6655. }
  6656. if (substr($color, 0, 3) == 'rgb') {
  6657. $codes = substr($color, 4);
  6658. $codes = str_replace(')', '', $codes);
  6659. $returncolor = explode(',', $codes, 3);
  6660. return $returncolor;
  6661. }
  6662. if (substr($color, 0, 1) != '#') {
  6663. // decode color name
  6664. if (isset($webcolor[$color])) {
  6665. $color_code = $webcolor[$color];
  6666. } else {
  6667. return false;
  6668. }
  6669. } else {
  6670. $color_code = substr($color, 1);
  6671. }
  6672. switch (strlen($color_code)) {
  6673. case 3: {
  6674. // three-digit hexadecimal representation
  6675. $r = substr($color_code, 0, 1);
  6676. $g = substr($color_code, 1, 1);
  6677. $b = substr($color_code, 2, 1);
  6678. $returncolor['R'] = hexdec($r.$r);
  6679. $returncolor['G'] = hexdec($g.$g);
  6680. $returncolor['B'] = hexdec($b.$b);
  6681. break;
  6682. }
  6683. case 6: {
  6684. // six-digit hexadecimal representation
  6685. $returncolor['R'] = hexdec(substr($color_code, 0, 2));
  6686. $returncolor['G'] = hexdec(substr($color_code, 2, 2));
  6687. $returncolor['B'] = hexdec(substr($color_code, 4, 2));
  6688. break;
  6689. }
  6690. }
  6691. return $returncolor;
  6692. }
  6693. /**
  6694. * Converts pixels to User's Units.
  6695. * @param int $px pixels
  6696. * @return float value in user's unit
  6697. * @access public
  6698. * @see setImageScale(), getImageScale()
  6699. */
  6700. public function pixelsToUnits($px) {
  6701. return ($px / ($this->imgscale * $this->k));
  6702. }
  6703. /**
  6704. * Reverse function for htmlentities.
  6705. * Convert entities in UTF-8.
  6706. * @param $text_to_convert Text to convert.
  6707. * @return string converted
  6708. * @access public
  6709. */
  6710. public function unhtmlentities($text_to_convert) {
  6711. return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  6712. }
  6713. // ENCRYPTION METHODS ----------------------------------
  6714. // SINCE 2.0.000 (2008-01-02)
  6715. /**
  6716. * Compute encryption key depending on object number where the encrypted data is stored
  6717. * @param int $n object number
  6718. * @access protected
  6719. * @since 2.0.000 (2008-01-02)
  6720. */
  6721. protected function _objectkey($n) {
  6722. return substr($this->_md5_16($this->encryption_key.pack('VXxx', $n)), 0, 10);
  6723. }
  6724. /**
  6725. * Put encryption on PDF document.
  6726. * @access protected
  6727. * @since 2.0.000 (2008-01-02)
  6728. */
  6729. protected function _putencryption() {
  6730. $this->_out('/Filter /Standard');
  6731. $this->_out('/V 1');
  6732. $this->_out('/R 2');
  6733. $this->_out('/O ('.$this->_escape($this->Ovalue).')');
  6734. $this->_out('/U ('.$this->_escape($this->Uvalue).')');
  6735. $this->_out('/P '.$this->Pvalue);
  6736. }
  6737. /**
  6738. * Returns the input text exrypted using RC4 algorithm and the specified key.
  6739. * RC4 is the standard encryption algorithm used in PDF format
  6740. * @param string $key encryption key
  6741. * @param String $text input text to be encrypted
  6742. * @return String encrypted text
  6743. * @access protected
  6744. * @since 2.0.000 (2008-01-02)
  6745. * @author Klemen Vodopivec
  6746. */
  6747. protected function _RC4($key, $text) {
  6748. if ($this->last_rc4_key != $key) {
  6749. $k = str_repeat($key, ((256 / strlen($key)) + 1));
  6750. $rc4 = range(0, 255);
  6751. $j = 0;
  6752. for ($i = 0; $i < 256; ++$i) {
  6753. $t = $rc4[$i];
  6754. $j = ($j + $t + ord($k{$i})) % 256;
  6755. $rc4[$i] = $rc4[$j];
  6756. $rc4[$j] = $t;
  6757. }
  6758. $this->last_rc4_key = $key;
  6759. $this->last_rc4_key_c = $rc4;
  6760. } else {
  6761. $rc4 = $this->last_rc4_key_c;
  6762. }
  6763. $len = strlen($text);
  6764. $a = 0;
  6765. $b = 0;
  6766. $out = '';
  6767. for ($i = 0; $i < $len; ++$i) {
  6768. $a = ($a + 1) % 256;
  6769. $t = $rc4[$a];
  6770. $b = ($b + $t) % 256;
  6771. $rc4[$a] = $rc4[$b];
  6772. $rc4[$b] = $t;
  6773. $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
  6774. $out .= chr(ord($text{$i}) ^ $k);
  6775. }
  6776. return $out;
  6777. }
  6778. /**
  6779. * Encrypts a string using MD5 and returns it's value as a binary string.
  6780. * @param string $str input string
  6781. * @return String MD5 encrypted binary string
  6782. * @access protected
  6783. * @since 2.0.000 (2008-01-02)
  6784. * @author Klemen Vodopivec
  6785. */
  6786. protected function _md5_16($str) {
  6787. return pack('H*', md5($str));
  6788. }
  6789. /**
  6790. * Compute O value (used for RC4 encryption)
  6791. * @param String $user_pass user password
  6792. * @param String $owner_pass user password
  6793. * @return String O value
  6794. * @access protected
  6795. * @since 2.0.000 (2008-01-02)
  6796. * @author Klemen Vodopivec
  6797. */
  6798. protected function _Ovalue($user_pass, $owner_pass) {
  6799. $tmp = $this->_md5_16($owner_pass);
  6800. $owner_RC4_key = substr($tmp, 0, 5);
  6801. return $this->_RC4($owner_RC4_key, $user_pass);
  6802. }
  6803. /**
  6804. * Compute U value (used for RC4 encryption)
  6805. * @return String U value
  6806. * @access protected
  6807. * @since 2.0.000 (2008-01-02)
  6808. * @author Klemen Vodopivec
  6809. */
  6810. protected function _Uvalue() {
  6811. return $this->_RC4($this->encryption_key, $this->padding);
  6812. }
  6813. /**
  6814. * Compute encryption key
  6815. * @param String $user_pass user password
  6816. * @param String $owner_pass user password
  6817. * @param String $protection protection type
  6818. * @access protected
  6819. * @since 2.0.000 (2008-01-02)
  6820. * @author Klemen Vodopivec
  6821. */
  6822. protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
  6823. // Pad passwords
  6824. $user_pass = substr($user_pass.$this->padding, 0, 32);
  6825. $owner_pass = substr($owner_pass.$this->padding, 0, 32);
  6826. // Compute O value
  6827. $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
  6828. // Compute encyption key
  6829. $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
  6830. $this->encryption_key = substr($tmp, 0, 5);
  6831. // Compute U value
  6832. $this->Uvalue = $this->_Uvalue();
  6833. // Compute P value
  6834. $this->Pvalue = -(($protection^255) + 1);
  6835. }
  6836. /**
  6837. * Set document protection
  6838. * The permission array is composed of values taken from the following ones:
  6839. * - copy: copy text and images to the clipboard
  6840. * - print: print the document
  6841. * - modify: modify it (except for annotations and forms)
  6842. * - annot-forms: add annotations and forms
  6843. * Remark: the protection against modification is for people who have the full Acrobat product.
  6844. * 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.
  6845. * 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.
  6846. * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
  6847. * @param String $user_pass user password. Empty by default.
  6848. * @param String $owner_pass owner password. If not specified, a random value is used.
  6849. * @access public
  6850. * @since 2.0.000 (2008-01-02)
  6851. * @author Klemen Vodopivec
  6852. */
  6853. public function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
  6854. $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
  6855. $protection = 192;
  6856. foreach ($permissions as $permission) {
  6857. if (!isset($options[$permission])) {
  6858. $this->Error('Incorrect permission: '.$permission);
  6859. }
  6860. $protection += $options[$permission];
  6861. }
  6862. if ($owner_pass === null) {
  6863. $owner_pass = uniqid(rand());
  6864. }
  6865. $this->encrypted = true;
  6866. $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
  6867. }
  6868. // END OF ENCRYPTION FUNCTIONS -------------------------
  6869. // START TRANSFORMATIONS SECTION -----------------------
  6870. /**
  6871. * Starts a 2D tranformation saving current graphic state.
  6872. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  6873. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  6874. * @access public
  6875. * @since 2.1.000 (2008-01-07)
  6876. * @see StartTransform(), StopTransform()
  6877. */
  6878. public function StartTransform() {
  6879. $this->_out('q');
  6880. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  6881. }
  6882. /**
  6883. * Stops a 2D tranformation restoring previous graphic state.
  6884. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  6885. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  6886. * @access public
  6887. * @since 2.1.000 (2008-01-07)
  6888. * @see StartTransform(), StopTransform()
  6889. */
  6890. public function StopTransform() {
  6891. $this->_out('Q');
  6892. if (isset($this->transfmatrix)) {
  6893. array_pop($this->transfmatrix);
  6894. }
  6895. array_pop($this->transfmrk[$this->page]);
  6896. }
  6897. /**
  6898. * Horizontal Scaling.
  6899. * @param float $s_x scaling factor for width as percent. 0 is not allowed.
  6900. * @param int $x abscissa of the scaling center. Default is current x position
  6901. * @param int $y ordinate of the scaling center. Default is current y position
  6902. * @access public
  6903. * @since 2.1.000 (2008-01-07)
  6904. * @see StartTransform(), StopTransform()
  6905. */
  6906. public function ScaleX($s_x, $x='', $y='') {
  6907. $this->Scale($s_x, 100, $x, $y);
  6908. }
  6909. /**
  6910. * Vertical Scaling.
  6911. * @param float $s_y scaling factor for height as percent. 0 is not allowed.
  6912. * @param int $x abscissa of the scaling center. Default is current x position
  6913. * @param int $y ordinate of the scaling center. Default is current y position
  6914. * @access public
  6915. * @since 2.1.000 (2008-01-07)
  6916. * @see StartTransform(), StopTransform()
  6917. */
  6918. public function ScaleY($s_y, $x='', $y='') {
  6919. $this->Scale(100, $s_y, $x, $y);
  6920. }
  6921. /**
  6922. * Vertical and horizontal proportional Scaling.
  6923. * @param float $s scaling factor for width and height as percent. 0 is not allowed.
  6924. * @param int $x abscissa of the scaling center. Default is current x position
  6925. * @param int $y ordinate of the scaling center. Default is current y position
  6926. * @access public
  6927. * @since 2.1.000 (2008-01-07)
  6928. * @see StartTransform(), StopTransform()
  6929. */
  6930. public function ScaleXY($s, $x='', $y='') {
  6931. $this->Scale($s, $s, $x, $y);
  6932. }
  6933. /**
  6934. * Vertical and horizontal non-proportional Scaling.
  6935. * @param float $s_x scaling factor for width as percent. 0 is not allowed.
  6936. * @param float $s_y scaling factor for height as percent. 0 is not allowed.
  6937. * @param int $x abscissa of the scaling center. Default is current x position
  6938. * @param int $y ordinate of the scaling center. Default is current y position
  6939. * @access public
  6940. * @since 2.1.000 (2008-01-07)
  6941. * @see StartTransform(), StopTransform()
  6942. */
  6943. public function Scale($s_x, $s_y, $x='', $y='') {
  6944. if ($x === '') {
  6945. $x = $this->x;
  6946. }
  6947. if ($y === '') {
  6948. $y = $this->y;
  6949. }
  6950. if ($this->rtl) {
  6951. $x = $this->w - $x;
  6952. }
  6953. if (($s_x == 0) OR ($s_y == 0)) {
  6954. $this->Error('Please do not use values equal to zero for scaling');
  6955. }
  6956. $y = ($this->h - $y) * $this->k;
  6957. $x *= $this->k;
  6958. //calculate elements of transformation matrix
  6959. $s_x /= 100;
  6960. $s_y /= 100;
  6961. $tm[0] = $s_x;
  6962. $tm[1] = 0;
  6963. $tm[2] = 0;
  6964. $tm[3] = $s_y;
  6965. $tm[4] = $x * (1 - $s_x);
  6966. $tm[5] = $y * (1 - $s_y);
  6967. //scale the coordinate system
  6968. $this->Transform($tm);
  6969. }
  6970. /**
  6971. * Horizontal Mirroring.
  6972. * @param int $x abscissa of the point. Default is current x position
  6973. * @access public
  6974. * @since 2.1.000 (2008-01-07)
  6975. * @see StartTransform(), StopTransform()
  6976. */
  6977. public function MirrorH($x='') {
  6978. $this->Scale(-100, 100, $x);
  6979. }
  6980. /**
  6981. * Verical Mirroring.
  6982. * @param int $y ordinate of the point. Default is current y position
  6983. * @access public
  6984. * @since 2.1.000 (2008-01-07)
  6985. * @see StartTransform(), StopTransform()
  6986. */
  6987. public function MirrorV($y='') {
  6988. $this->Scale(100, -100, '', $y);
  6989. }
  6990. /**
  6991. * Point reflection mirroring.
  6992. * @param int $x abscissa of the point. Default is current x position
  6993. * @param int $y ordinate of the point. Default is current y position
  6994. * @access public
  6995. * @since 2.1.000 (2008-01-07)
  6996. * @see StartTransform(), StopTransform()
  6997. */
  6998. public function MirrorP($x='',$y='') {
  6999. $this->Scale(-100, -100, $x, $y);
  7000. }
  7001. /**
  7002. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  7003. * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
  7004. * @param int $x abscissa of the point. Default is current x position
  7005. * @param int $y ordinate of the point. Default is current y position
  7006. * @access public
  7007. * @since 2.1.000 (2008-01-07)
  7008. * @see StartTransform(), StopTransform()
  7009. */
  7010. public function MirrorL($angle=0, $x='',$y='') {
  7011. $this->Scale(-100, 100, $x, $y);
  7012. $this->Rotate(-2*($angle-90), $x, $y);
  7013. }
  7014. /**
  7015. * Translate graphic object horizontally.
  7016. * @param int $t_x movement to the right (or left for RTL)
  7017. * @access public
  7018. * @since 2.1.000 (2008-01-07)
  7019. * @see StartTransform(), StopTransform()
  7020. */
  7021. public function TranslateX($t_x) {
  7022. $this->Translate($t_x, 0);
  7023. }
  7024. /**
  7025. * Translate graphic object vertically.
  7026. * @param int $t_y movement to the bottom
  7027. * @access public
  7028. * @since 2.1.000 (2008-01-07)
  7029. * @see StartTransform(), StopTransform()
  7030. */
  7031. public function TranslateY($t_y) {
  7032. $this->Translate(0, $t_y);
  7033. }
  7034. /**
  7035. * Translate graphic object horizontally and vertically.
  7036. * @param int $t_x movement to the right
  7037. * @param int $t_y movement to the bottom
  7038. * @access public
  7039. * @since 2.1.000 (2008-01-07)
  7040. * @see StartTransform(), StopTransform()
  7041. */
  7042. public function Translate($t_x, $t_y) {
  7043. if ($this->rtl) {
  7044. $t_x = -$t_x;
  7045. }
  7046. //calculate elements of transformation matrix
  7047. $tm[0] = 1;
  7048. $tm[1] = 0;
  7049. $tm[2] = 0;
  7050. $tm[3] = 1;
  7051. $tm[4] = $t_x * $this->k;
  7052. $tm[5] = -$t_y * $this->k;
  7053. //translate the coordinate system
  7054. $this->Transform($tm);
  7055. }
  7056. /**
  7057. * Rotate object.
  7058. * @param float $angle angle in degrees for counter-clockwise rotation
  7059. * @param int $x abscissa of the rotation center. Default is current x position
  7060. * @param int $y ordinate of the rotation center. Default is current y position
  7061. * @access public
  7062. * @since 2.1.000 (2008-01-07)
  7063. * @see StartTransform(), StopTransform()
  7064. */
  7065. public function Rotate($angle, $x='', $y='') {
  7066. if ($x === '') {
  7067. $x = $this->x;
  7068. }
  7069. if ($y === '') {
  7070. $y = $this->y;
  7071. }
  7072. if ($this->rtl) {
  7073. $x = $this->w - $x;
  7074. $angle = -$angle;
  7075. }
  7076. $y = ($this->h - $y) * $this->k;
  7077. $x *= $this->k;
  7078. //calculate elements of transformation matrix
  7079. $tm[0] = cos(deg2rad($angle));
  7080. $tm[1] = sin(deg2rad($angle));
  7081. $tm[2] = -$tm[1];
  7082. $tm[3] = $tm[0];
  7083. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  7084. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  7085. //rotate the coordinate system around ($x,$y)
  7086. $this->Transform($tm);
  7087. }
  7088. /**
  7089. * Skew horizontally.
  7090. * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  7091. * @param int $x abscissa of the skewing center. default is current x position
  7092. * @param int $y ordinate of the skewing center. default is current y position
  7093. * @access public
  7094. * @since 2.1.000 (2008-01-07)
  7095. * @see StartTransform(), StopTransform()
  7096. */
  7097. public function SkewX($angle_x, $x='', $y='') {
  7098. $this->Skew($angle_x, 0, $x, $y);
  7099. }
  7100. /**
  7101. * Skew vertically.
  7102. * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  7103. * @param int $x abscissa of the skewing center. default is current x position
  7104. * @param int $y ordinate of the skewing center. default is current y position
  7105. * @access public
  7106. * @since 2.1.000 (2008-01-07)
  7107. * @see StartTransform(), StopTransform()
  7108. */
  7109. public function SkewY($angle_y, $x='', $y='') {
  7110. $this->Skew(0, $angle_y, $x, $y);
  7111. }
  7112. /**
  7113. * Skew.
  7114. * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  7115. * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  7116. * @param int $x abscissa of the skewing center. default is current x position
  7117. * @param int $y ordinate of the skewing center. default is current y position
  7118. * @access public
  7119. * @since 2.1.000 (2008-01-07)
  7120. * @see StartTransform(), StopTransform()
  7121. */
  7122. public function Skew($angle_x, $angle_y, $x='', $y='') {
  7123. if ($x === '') {
  7124. $x = $this->x;
  7125. }
  7126. if ($y === '') {
  7127. $y = $this->y;
  7128. }
  7129. if ($this->rtl) {
  7130. $x = $this->w - $x;
  7131. $angle_x = -$angle_x;
  7132. }
  7133. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  7134. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  7135. }
  7136. $x *= $this->k;
  7137. $y = ($this->h - $y) * $this->k;
  7138. //calculate elements of transformation matrix
  7139. $tm[0] = 1;
  7140. $tm[1] = tan(deg2rad($angle_y));
  7141. $tm[2] = tan(deg2rad($angle_x));
  7142. $tm[3] = 1;
  7143. $tm[4] = -$tm[2] * $y;
  7144. $tm[5] = -$tm[1] * $x;
  7145. //skew the coordinate system
  7146. $this->Transform($tm);
  7147. }
  7148. /**
  7149. * Apply graphic transformations.
  7150. * @access protected
  7151. * @since 2.1.000 (2008-01-07)
  7152. * @see StartTransform(), StopTransform()
  7153. */
  7154. protected function Transform($tm) {
  7155. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  7156. // store transformation matrix
  7157. $this->transfmatrix[] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  7158. // update tranformation mark
  7159. if (end($this->transfmrk[$this->page]) !== false) {
  7160. $key = key($this->transfmrk[$this->page]);
  7161. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  7162. }
  7163. }
  7164. // END TRANSFORMATIONS SECTION -------------------------
  7165. // START GRAPHIC FUNCTIONS SECTION ---------------------
  7166. // The following section is based on the code provided by David Hernandez Sanz
  7167. /**
  7168. * 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.
  7169. * @param float $width The width.
  7170. * @access public
  7171. * @since 1.0
  7172. * @see Line(), Rect(), Cell(), MultiCell()
  7173. */
  7174. public function SetLineWidth($width) {
  7175. //Set line width
  7176. $this->LineWidth = $width;
  7177. $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
  7178. $this->_out($this->linestyleWidth);
  7179. }
  7180. /**
  7181. * Returns the current the line width.
  7182. * @return int Line width
  7183. * @access public
  7184. * @since 2.1.000 (2008-01-07)
  7185. * @see Line(), SetLineWidth()
  7186. */
  7187. public function GetLineWidth() {
  7188. return $this->LineWidth;
  7189. }
  7190. /**
  7191. * Set line style.
  7192. * @param array $style Line style. Array with keys among the following:
  7193. * <ul>
  7194. * <li>width (float): Width of the line in user units.</li>
  7195. * <li>cap (string): Type of cap to put on the line. Possible values are:
  7196. * butt, round, square. The difference between "square" and "butt" is that
  7197. * "square" projects a flat end past the end of the line.</li>
  7198. * <li>join (string): Type of join. Possible values are: miter, round,
  7199. * bevel.</li>
  7200. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  7201. * series of length values, which are the lengths of the on and off dashes.
  7202. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  7203. * 1 off, 2 on, 1 off, ...</li>
  7204. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  7205. * the point at which the pattern starts.</li>
  7206. * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
  7207. * </ul>
  7208. * @access public
  7209. * @since 2.1.000 (2008-01-08)
  7210. */
  7211. public function SetLineStyle($style) {
  7212. extract($style);
  7213. if (isset($width)) {
  7214. $width_prev = $this->LineWidth;
  7215. $this->SetLineWidth($width);
  7216. $this->LineWidth = $width_prev;
  7217. }
  7218. if (isset($cap)) {
  7219. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  7220. if (isset($ca[$cap])) {
  7221. $this->linestyleCap = $ca[$cap].' J';
  7222. $this->_out($this->linestyleCap);
  7223. }
  7224. }
  7225. if (isset($join)) {
  7226. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  7227. if (isset($ja[$join])) {
  7228. $this->linestyleJoin = $ja[$join].' j';
  7229. $this->_out($this->linestyleJoin);
  7230. }
  7231. }
  7232. if (isset($dash)) {
  7233. $dash_string = '';
  7234. if ($dash) {
  7235. if (preg_match('/^.+,/', $dash)) {
  7236. $tab = explode(',', $dash);
  7237. } else {
  7238. $tab = array($dash);
  7239. }
  7240. $dash_string = '';
  7241. foreach ($tab as $i => $v) {
  7242. if ($i) {
  7243. $dash_string .= ' ';
  7244. }
  7245. $dash_string .= sprintf("%.2F", $v);
  7246. }
  7247. }
  7248. if (!isset($phase) OR !$dash) {
  7249. $phase = 0;
  7250. }
  7251. $this->linestyleDash = sprintf("[%s] %.2F d", $dash_string, $phase);
  7252. $this->_out($this->linestyleDash);
  7253. }
  7254. if (isset($color)) {
  7255. $this->SetDrawColorArray($color);
  7256. }
  7257. }
  7258. /*
  7259. * Set a draw point.
  7260. * @param float $x Abscissa of point.
  7261. * @param float $y Ordinate of point.
  7262. * @access protected
  7263. * @since 2.1.000 (2008-01-08)
  7264. */
  7265. protected function _outPoint($x, $y) {
  7266. if ($this->rtl) {
  7267. $x = $this->w - $x;
  7268. }
  7269. $this->_out(sprintf("%.2F %.2F m", $x * $this->k, ($this->h - $y) * $this->k));
  7270. }
  7271. /*
  7272. * Draws a line from last draw point.
  7273. * @param float $x Abscissa of end point.
  7274. * @param float $y Ordinate of end point.
  7275. * @access protected
  7276. * @since 2.1.000 (2008-01-08)
  7277. */
  7278. protected function _outLine($x, $y) {
  7279. if ($this->rtl) {
  7280. $x = $this->w - $x;
  7281. }
  7282. $this->_out(sprintf("%.2F %.2F l", $x * $this->k, ($this->h - $y) * $this->k));
  7283. }
  7284. /**
  7285. * Draws a rectangle.
  7286. * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
  7287. * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
  7288. * @param float $w Width.
  7289. * @param float $h Height.
  7290. * @param string $op options
  7291. * @access protected
  7292. * @since 2.1.000 (2008-01-08)
  7293. */
  7294. protected function _outRect($x, $y, $w, $h, $op) {
  7295. if ($this->rtl) {
  7296. $x = $this->w - $x - $w;
  7297. }
  7298. $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
  7299. }
  7300. /*
  7301. * Draws a Bezier curve from last draw point.
  7302. * The Bezier curve is a tangent to the line between the control points at either end of the curve.
  7303. * @param float $x1 Abscissa of control point 1.
  7304. * @param float $y1 Ordinate of control point 1.
  7305. * @param float $x2 Abscissa of control point 2.
  7306. * @param float $y2 Ordinate of control point 2.
  7307. * @param float $x3 Abscissa of end point.
  7308. * @param float $y3 Ordinate of end point.
  7309. * @access protected
  7310. * @since 2.1.000 (2008-01-08)
  7311. */
  7312. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  7313. if ($this->rtl) {
  7314. $x1 = $this->w - $x1;
  7315. $x2 = $this->w - $x2;
  7316. $x3 = $this->w - $x3;
  7317. }
  7318. $this->_out(sprintf("%.2F %.2F %.2F %.2F %.2F %.2F c", $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
  7319. }
  7320. /**
  7321. * Draws a line between two points.
  7322. * @param float $x1 Abscissa of first point.
  7323. * @param float $y1 Ordinate of first point.
  7324. * @param float $x2 Abscissa of second point.
  7325. * @param float $y2 Ordinate of second point.
  7326. * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7327. * @access public
  7328. * @since 1.0
  7329. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  7330. */
  7331. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  7332. if ($style) {
  7333. $this->SetLineStyle($style);
  7334. }
  7335. $this->_outPoint($x1, $y1);
  7336. $this->_outLine($x2, $y2);
  7337. $this->_out(' S');
  7338. }
  7339. /**
  7340. * Draws a rectangle.
  7341. * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
  7342. * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
  7343. * @param float $w Width.
  7344. * @param float $h Height.
  7345. * @param string $style Style of rendering. Possible values are:
  7346. * <ul>
  7347. * <li>D or empty string: Draw (default).</li>
  7348. * <li>F: Fill.</li>
  7349. * <li>DF or FD: Draw and fill.</li>
  7350. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7351. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7352. * </ul>
  7353. * @param array $border_style Border style of rectangle. Array with keys among the following:
  7354. * <ul>
  7355. * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7356. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7357. * </ul>
  7358. * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
  7359. * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7360. * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  7361. * @access public
  7362. * @since 1.0
  7363. * @see SetLineStyle()
  7364. */
  7365. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  7366. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  7367. $this->SetFillColorArray($fill_color);
  7368. }
  7369. switch ($style) {
  7370. case 'F': {
  7371. $op = 'f';
  7372. $border_style = array();
  7373. $this->_outRect($x, $y, $w, $h, $op);
  7374. break;
  7375. }
  7376. case 'DF':
  7377. case 'FD': {
  7378. if ((!$border_style) OR (isset($border_style['all']))) {
  7379. $op = 'B';
  7380. if (isset($border_style['all'])) {
  7381. $this->SetLineStyle($border_style['all']);
  7382. $border_style = array();
  7383. }
  7384. } else {
  7385. $op = 'f';
  7386. }
  7387. $this->_outRect($x, $y, $w, $h, $op);
  7388. break;
  7389. }
  7390. case 'CNZ': {
  7391. $op = 'W n';
  7392. $this->_outRect($x, $y, $w, $h, $op);
  7393. break;
  7394. }
  7395. case 'CEO': {
  7396. $op = 'W* n';
  7397. $this->_outRect($x, $y, $w, $h, $op);
  7398. break;
  7399. }
  7400. default: {
  7401. $op = 'S';
  7402. if ((!$border_style) OR (isset($border_style['all']))) {
  7403. if (isset($border_style['all']) AND $border_style['all']) {
  7404. $this->SetLineStyle($border_style['all']);
  7405. $border_style = array();
  7406. }
  7407. $this->_outRect($x, $y, $w, $h, $op);
  7408. }
  7409. break;
  7410. }
  7411. }
  7412. if ($border_style) {
  7413. $border_style2 = array();
  7414. foreach ($border_style as $line => $value) {
  7415. $lenght = strlen($line);
  7416. for ($i = 0; $i < $lenght; ++$i) {
  7417. $border_style2[$line[$i]] = $value;
  7418. }
  7419. }
  7420. $border_style = $border_style2;
  7421. if (isset($border_style['L']) AND $border_style['L']) {
  7422. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  7423. }
  7424. if (isset($border_style['T']) AND $border_style['T']) {
  7425. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  7426. }
  7427. if (isset($border_style['R']) AND $border_style['R']) {
  7428. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  7429. }
  7430. if (isset($border_style['B']) AND $border_style['B']) {
  7431. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  7432. }
  7433. }
  7434. }
  7435. /**
  7436. * Draws a Bezier curve.
  7437. * The Bezier curve is a tangent to the line between the control points at
  7438. * either end of the curve.
  7439. * @param float $x0 Abscissa of start point.
  7440. * @param float $y0 Ordinate of start point.
  7441. * @param float $x1 Abscissa of control point 1.
  7442. * @param float $y1 Ordinate of control point 1.
  7443. * @param float $x2 Abscissa of control point 2.
  7444. * @param float $y2 Ordinate of control point 2.
  7445. * @param float $x3 Abscissa of end point.
  7446. * @param float $y3 Ordinate of end point.
  7447. * @param string $style Style of rendering. Possible values are:
  7448. * <ul>
  7449. * <li>D or empty string: Draw (default).</li>
  7450. * <li>F: Fill.</li>
  7451. * <li>DF or FD: Draw and fill.</li>
  7452. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7453. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7454. * </ul>
  7455. * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7456. * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  7457. * @access public
  7458. * @see SetLineStyle()
  7459. * @since 2.1.000 (2008-01-08)
  7460. */
  7461. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  7462. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  7463. $this->SetFillColorArray($fill_color);
  7464. }
  7465. switch ($style) {
  7466. case 'F': {
  7467. $op = 'f';
  7468. $line_style = array();
  7469. break;
  7470. }
  7471. case 'FD':
  7472. case 'DF': {
  7473. $op = 'B';
  7474. break;
  7475. }
  7476. case 'CNZ': {
  7477. $op = 'W n';
  7478. break;
  7479. }
  7480. case 'CEO': {
  7481. $op = 'W* n';
  7482. break;
  7483. }
  7484. default: {
  7485. $op = 'S';
  7486. break;
  7487. }
  7488. }
  7489. if ($line_style) {
  7490. $this->SetLineStyle($line_style);
  7491. }
  7492. $this->_outPoint($x0, $y0);
  7493. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  7494. $this->_out($op);
  7495. }
  7496. /**
  7497. * Draws a poly-Bezier curve.
  7498. * Each Bezier curve segment is a tangent to the line between the control points at
  7499. * either end of the curve.
  7500. * @param float $x0 Abscissa of start point.
  7501. * @param float $y0 Ordinate of start point.
  7502. * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  7503. * @param string $style Style of rendering. Possible values are:
  7504. * <ul>
  7505. * <li>D or empty string: Draw (default).</li>
  7506. * <li>F: Fill.</li>
  7507. * <li>DF or FD: Draw and fill.</li>
  7508. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7509. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7510. * </ul>
  7511. * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7512. * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  7513. * @access public
  7514. * @see SetLineStyle()
  7515. * @since 3.0008 (2008-05-12)
  7516. */
  7517. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  7518. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  7519. $this->SetFillColorArray($fill_color);
  7520. }
  7521. switch ($style) {
  7522. case 'F': {
  7523. $op = 'f';
  7524. $line_style = array();
  7525. break;
  7526. }
  7527. case 'FD':
  7528. case 'DF': {
  7529. $op = 'B';
  7530. break;
  7531. }
  7532. case 'CNZ': {
  7533. $op = 'W n';
  7534. break;
  7535. }
  7536. case 'CEO': {
  7537. $op = 'W* n';
  7538. break;
  7539. }
  7540. default: {
  7541. $op = 'S';
  7542. break;
  7543. }
  7544. }
  7545. if ($line_style) {
  7546. $this->SetLineStyle($line_style);
  7547. }
  7548. $this->_outPoint($x0, $y0);
  7549. foreach ($segments as $segment) {
  7550. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  7551. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  7552. }
  7553. $this->_out($op);
  7554. }
  7555. /**
  7556. * Draws an ellipse.
  7557. * An ellipse is formed from n Bezier curves.
  7558. * @param float $x0 Abscissa of center point.
  7559. * @param float $y0 Ordinate of center point.
  7560. * @param float $rx Horizontal radius.
  7561. * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
  7562. * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
  7563. * @param float $astart: Angle start of draw line. Default value: 0.
  7564. * @param float $afinish: Angle finish of draw line. Default value: 360.
  7565. * @param string $style Style of rendering. Possible values are:
  7566. * <ul>
  7567. * <li>D or empty string: Draw (default).</li>
  7568. * <li>F: Fill.</li>
  7569. * <li>DF or FD: Draw and fill.</li>
  7570. * <li>C: Draw close.</li>
  7571. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7572. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7573. * </ul>
  7574. * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7575. * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  7576. * @param integer $nc Number of curves used in ellipse. Default value: 8.
  7577. * @access public
  7578. * @since 2.1.000 (2008-01-08)
  7579. */
  7580. public function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
  7581. if ($angle) {
  7582. $this->StartTransform();
  7583. $this->Rotate($angle, $x0, $y0);
  7584. $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
  7585. $this->StopTransform();
  7586. return;
  7587. }
  7588. if ($rx) {
  7589. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  7590. $this->SetFillColorArray($fill_color);
  7591. }
  7592. switch ($style) {
  7593. case 'F': {
  7594. $op = 'f';
  7595. $line_style = array();
  7596. break;
  7597. }
  7598. case 'FD':
  7599. case 'DF': {
  7600. $op = 'B';
  7601. break;
  7602. }
  7603. case 'C': {
  7604. $op = 's'; // Small 's' signifies closing the path as well
  7605. break;
  7606. }
  7607. case 'CNZ': {
  7608. $op = 'W n';
  7609. break;
  7610. }
  7611. case 'CEO': {
  7612. $op = 'W* n';
  7613. break;
  7614. }
  7615. default: {
  7616. $op = 'S';
  7617. break;
  7618. }
  7619. }
  7620. if ($line_style) {
  7621. $this->SetLineStyle($line_style);
  7622. }
  7623. if (!$ry) {
  7624. $ry = $rx;
  7625. }
  7626. $rx *= $this->k;
  7627. $ry *= $this->k;
  7628. if ($nc < 2) {
  7629. $nc = 2;
  7630. }
  7631. $astart = deg2rad((float) $astart);
  7632. $afinish = deg2rad((float) $afinish);
  7633. $total_angle = $afinish - $astart;
  7634. $dt = $total_angle / $nc;
  7635. $dtm = $dt / 3;
  7636. $x0 *= $this->k;
  7637. $y0 = ($this->h - $y0) * $this->k;
  7638. $t1 = $astart;
  7639. $a0 = $x0 + ($rx * cos($t1));
  7640. $b0 = $y0 + ($ry * sin($t1));
  7641. $c0 = -$rx * sin($t1);
  7642. $d0 = $ry * cos($t1);
  7643. $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
  7644. for ($i = 1; $i <= $nc; ++$i) {
  7645. // Draw this bit of the total curve
  7646. $t1 = ($i * $dt) + $astart;
  7647. $a1 = $x0 + ($rx * cos($t1));
  7648. $b1 = $y0 + ($ry * sin($t1));
  7649. $c1 = -$rx * sin($t1);
  7650. $d1 = $ry * cos($t1);
  7651. $this->_outCurve(($a0 + ($c0 * $dtm)) / $this->k, $this->h - (($b0 + ($d0 * $dtm)) / $this->k), ($a1 - ($c1 * $dtm)) / $this->k, $this->h - (($b1 - ($d1 * $dtm)) / $this->k), $a1 / $this->k, $this->h - ($b1 / $this->k));
  7652. $a0 = $a1;
  7653. $b0 = $b1;
  7654. $c0 = $c1;
  7655. $d0 = $d1;
  7656. }
  7657. $this->_out($op);
  7658. }
  7659. }
  7660. /**
  7661. * Draws a circle.
  7662. * A circle is formed from n Bezier curves.
  7663. * @param float $x0 Abscissa of center point.
  7664. * @param float $y0 Ordinate of center point.
  7665. * @param float $r Radius.
  7666. * @param float $astart: Angle start of draw line. Default value: 0.
  7667. * @param float $afinish: Angle finish of draw line. Default value: 360.
  7668. * @param string $style Style of rendering. Possible values are:
  7669. * <ul>
  7670. * <li>D or empty string: Draw (default).</li>
  7671. * <li>F: Fill.</li>
  7672. * <li>DF or FD: Draw and fill.</li>
  7673. * <li>C: Draw close.</li>
  7674. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7675. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7676. * </ul>
  7677. * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7678. * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  7679. * @param integer $nc Number of curves used in circle. Default value: 8.
  7680. * @access public
  7681. * @since 2.1.000 (2008-01-08)
  7682. */
  7683. public function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
  7684. $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
  7685. }
  7686. /**
  7687. * Draws a polygon.
  7688. * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  7689. * @param string $style Style of rendering. Possible values are:
  7690. * <ul>
  7691. * <li>D or empty string: Draw (default).</li>
  7692. * <li>F: Fill.</li>
  7693. * <li>DF or FD: Draw and fill.</li>
  7694. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7695. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7696. * </ul>
  7697. * @param array $line_style Line style of polygon. Array with keys among the following:
  7698. * <ul>
  7699. * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7700. * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7701. * </ul>
  7702. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  7703. * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  7704. * @access public
  7705. * @since 2.1.000 (2008-01-08)
  7706. */
  7707. public function Polygon($p, $style='', $line_style=array(), $fill_color=array()) {
  7708. $np = count($p) / 2;
  7709. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  7710. $this->SetFillColorArray($fill_color);
  7711. }
  7712. switch ($style) {
  7713. case 'F': {
  7714. $line_style = array();
  7715. $op = 'f';
  7716. break;
  7717. }
  7718. case 'FD':
  7719. case 'DF': {
  7720. $op = 'B';
  7721. break;
  7722. }
  7723. case 'CNZ': {
  7724. $op = 'W n';
  7725. break;
  7726. }
  7727. case 'CEO': {
  7728. $op = 'W* n';
  7729. break;
  7730. }
  7731. default: {
  7732. $op = 'S';
  7733. break;
  7734. }
  7735. }
  7736. $draw = true;
  7737. if ($line_style) {
  7738. if (isset($line_style['all'])) {
  7739. $this->SetLineStyle($line_style['all']);
  7740. } else { // 0 .. (np - 1), op = {B, S}
  7741. $draw = false;
  7742. if ('B' == $op) {
  7743. $op = 'f';
  7744. $this->_outPoint($p[0], $p[1]);
  7745. for ($i = 2; $i < ($np * 2); $i = $i + 2) {
  7746. $this->_outLine($p[$i], $p[$i + 1]);
  7747. }
  7748. $this->_outLine($p[0], $p[1]);
  7749. $this->_out($op);
  7750. }
  7751. $p[($np * 2)] = $p[0];
  7752. $p[(($np * 2) + 1)] = $p[1];
  7753. for ($i = 0; $i < $np; ++$i) {
  7754. if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
  7755. $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
  7756. }
  7757. }
  7758. }
  7759. }
  7760. if ($draw) {
  7761. $this->_outPoint($p[0], $p[1]);
  7762. for ($i = 2; $i < ($np * 2); $i = $i + 2) {
  7763. $this->_outLine($p[$i], $p[$i + 1]);
  7764. }
  7765. $this->_outLine($p[0], $p[1]);
  7766. $this->_out($op);
  7767. }
  7768. }
  7769. /**
  7770. * Draws a regular polygon.
  7771. * @param float $x0 Abscissa of center point.
  7772. * @param float $y0 Ordinate of center point.
  7773. * @param float $r: Radius of inscribed circle.
  7774. * @param integer $ns Number of sides.
  7775. * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
  7776. * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
  7777. * @param string $style Style of rendering. Possible values are:
  7778. * <ul>
  7779. * <li>D or empty string: Draw (default).</li>
  7780. * <li>F: Fill.</li>
  7781. * <li>DF or FD: Draw and fill.</li>
  7782. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7783. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7784. * </ul>
  7785. * @param array $line_style Line style of polygon sides. Array with keys among the following:
  7786. * <ul>
  7787. * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7788. * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7789. * </ul>
  7790. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  7791. * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  7792. * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
  7793. * <ul>
  7794. * <li>D or empty string: Draw (default).</li>
  7795. * <li>F: Fill.</li>
  7796. * <li>DF or FD: Draw and fill.</li>
  7797. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7798. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7799. * </ul>
  7800. * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7801. * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  7802. * @access public
  7803. * @since 2.1.000 (2008-01-08)
  7804. */
  7805. 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()) {
  7806. if (3 > $ns) {
  7807. $ns = 3;
  7808. }
  7809. if ($draw_circle) {
  7810. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  7811. }
  7812. $p = array();
  7813. for ($i = 0; $i < $ns; ++$i) {
  7814. $a = $angle + ($i * 360 / $ns);
  7815. $a_rad = deg2rad((float) $a);
  7816. $p[] = $x0 + ($r * sin($a_rad));
  7817. $p[] = $y0 + ($r * cos($a_rad));
  7818. }
  7819. $this->Polygon($p, $style, $line_style, $fill_color);
  7820. }
  7821. /**
  7822. * Draws a star polygon
  7823. * @param float $x0 Abscissa of center point.
  7824. * @param float $y0 Ordinate of center point.
  7825. * @param float $r Radius of inscribed circle.
  7826. * @param integer $nv Number of vertices.
  7827. * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  7828. * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
  7829. * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
  7830. * @param string $style Style of rendering. Possible values are:
  7831. * <ul>
  7832. * <li>D or empty string: Draw (default).</li>
  7833. * <li>F: Fill.</li>
  7834. * <li>DF or FD: Draw and fill.</li>
  7835. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7836. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7837. * </ul>
  7838. * @param array $line_style Line style of polygon sides. Array with keys among the following:
  7839. * <ul>
  7840. * <li>all: Line style of all sides. Array like for
  7841. * {@link SetLineStyle SetLineStyle}.</li>
  7842. * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
  7843. * </ul>
  7844. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  7845. * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  7846. * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
  7847. * <ul>
  7848. * <li>D or empty string: Draw (default).</li>
  7849. * <li>F: Fill.</li>
  7850. * <li>DF or FD: Draw and fill.</li>
  7851. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7852. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7853. * </ul>
  7854. * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7855. * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  7856. * @access public
  7857. * @since 2.1.000 (2008-01-08)
  7858. */
  7859. 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()) {
  7860. if (2 > $nv) {
  7861. $nv = 2;
  7862. }
  7863. if ($draw_circle) {
  7864. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  7865. }
  7866. $p2 = array();
  7867. $visited = array();
  7868. for ($i = 0; $i < $nv; ++$i) {
  7869. $a = $angle + ($i * 360 / $nv);
  7870. $a_rad = deg2rad((float) $a);
  7871. $p2[] = $x0 + ($r * sin($a_rad));
  7872. $p2[] = $y0 + ($r * cos($a_rad));
  7873. $visited[] = false;
  7874. }
  7875. $p = array();
  7876. $i = 0;
  7877. do {
  7878. $p[] = $p2[$i * 2];
  7879. $p[] = $p2[($i * 2) + 1];
  7880. $visited[$i] = true;
  7881. $i += $ng;
  7882. $i %= $nv;
  7883. } while (!$visited[$i]);
  7884. $this->Polygon($p, $style, $line_style, $fill_color);
  7885. }
  7886. /**
  7887. * Draws a rounded rectangle.
  7888. * @param float $x Abscissa of upper-left corner.
  7889. * @param float $y Ordinate of upper-left corner.
  7890. * @param float $w Width.
  7891. * @param float $h Height.
  7892. * @param float $r Radius of the rounded corners.
  7893. * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
  7894. * @param string $style Style of rendering. Possible values are:
  7895. * <ul>
  7896. * <li>D or empty string: Draw (default).</li>
  7897. * <li>F: Fill.</li>
  7898. * <li>DF or FD: Draw and fill.</li>
  7899. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  7900. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  7901. * </ul>
  7902. * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
  7903. * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
  7904. * @access public
  7905. * @since 2.1.000 (2008-01-08)
  7906. */
  7907. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  7908. if ('0000' == $round_corner) { // Not rounded
  7909. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  7910. } else { // Rounded
  7911. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  7912. $this->SetFillColorArray($fill_color);
  7913. }
  7914. switch ($style) {
  7915. case 'F': {
  7916. $border_style = array();
  7917. $op = 'f';
  7918. break;
  7919. }
  7920. case 'FD':
  7921. case 'DF': {
  7922. $op = 'B';
  7923. break;
  7924. }
  7925. case 'CNZ': {
  7926. $op = 'W n';
  7927. break;
  7928. }
  7929. case 'CEO': {
  7930. $op = 'W* n';
  7931. break;
  7932. }
  7933. default: {
  7934. $op = 'S';
  7935. break;
  7936. }
  7937. }
  7938. if ($border_style) {
  7939. $this->SetLineStyle($border_style);
  7940. }
  7941. $MyArc = 4 / 3 * (sqrt(2) - 1);
  7942. $this->_outPoint($x + $r, $y);
  7943. $xc = $x + $w - $r;
  7944. $yc = $y + $r;
  7945. $this->_outLine($xc, $y);
  7946. if ($round_corner[0]) {
  7947. $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
  7948. } else {
  7949. $this->_outLine($x + $w, $y);
  7950. }
  7951. $xc = $x + $w - $r;
  7952. $yc = $y + $h - $r;
  7953. $this->_outLine($x + $w, $yc);
  7954. if ($round_corner[1]) {
  7955. $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
  7956. } else {
  7957. $this->_outLine($x + $w, $y + $h);
  7958. }
  7959. $xc = $x + $r;
  7960. $yc = $y + $h - $r;
  7961. $this->_outLine($xc, $y + $h);
  7962. if ($round_corner[2]) {
  7963. $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
  7964. } else {
  7965. $this->_outLine($x, $y + $h);
  7966. }
  7967. $xc = $x + $r;
  7968. $yc = $y + $r;
  7969. $this->_outLine($x, $yc);
  7970. if ($round_corner[3]) {
  7971. $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
  7972. } else {
  7973. $this->_outLine($x, $y);
  7974. $this->_outLine($x + $r, $y);
  7975. }
  7976. $this->_out($op);
  7977. }
  7978. }
  7979. // END GRAPHIC FUNCTIONS SECTION -----------------------
  7980. // BIDIRECTIONAL TEXT SECTION --------------------------
  7981. /**
  7982. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  7983. * @param string $str string to manipulate.
  7984. * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
  7985. * @return string
  7986. * @access protected
  7987. * @author Nicola Asuni
  7988. * @since 2.1.000 (2008-01-08)
  7989. */
  7990. protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
  7991. return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $str, $forcertl), $setbom);
  7992. }
  7993. /**
  7994. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  7995. * @param array $ta array of characters composing the string.
  7996. * @param string $str string to process
  7997. * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
  7998. * @return string
  7999. * @author Nicola Asuni
  8000. * @access protected
  8001. * @since 2.4.000 (2008-03-06)
  8002. */
  8003. protected function utf8Bidi($ta, $str='', $forcertl=false) {
  8004. global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
  8005. // paragraph embedding level
  8006. $pel = 0;
  8007. // max level
  8008. $maxlevel = 0;
  8009. if ($this->empty_string($str)) {
  8010. // create string from array
  8011. $str = $this->UTF8ArrSubString($ta);
  8012. }
  8013. // check if string contains arabic text
  8014. if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
  8015. $arabic = true;
  8016. } else {
  8017. $arabic = false;
  8018. }
  8019. // check if string contains RTL text
  8020. if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
  8021. return $ta;
  8022. }
  8023. // get number of chars
  8024. $numchars = count($ta);
  8025. if ($forcertl == 'R') {
  8026. $pel = 1;
  8027. } elseif ($forcertl == 'L') {
  8028. $pel = 0;
  8029. } else {
  8030. // P2. In each paragraph, find the first character of type L, AL, or R.
  8031. // 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.
  8032. for ($i=0; $i < $numchars; ++$i) {
  8033. $type = $unicode[$ta[$i]];
  8034. if ($type == 'L') {
  8035. $pel = 0;
  8036. break;
  8037. } elseif (($type == 'AL') OR ($type == 'R')) {
  8038. $pel = 1;
  8039. break;
  8040. }
  8041. }
  8042. }
  8043. // Current Embedding Level
  8044. $cel = $pel;
  8045. // directional override status
  8046. $dos = 'N';
  8047. $remember = array();
  8048. // start-of-level-run
  8049. $sor = $pel % 2 ? 'R' : 'L';
  8050. $eor = $sor;
  8051. // Array of characters data
  8052. $chardata = Array();
  8053. // 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.
  8054. // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
  8055. for ($i=0; $i < $numchars; ++$i) {
  8056. if ($ta[$i] == K_RLE) {
  8057. // X2. With each RLE, compute the least greater odd embedding level.
  8058. // 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.
  8059. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  8060. $next_level = $cel + ($cel % 2) + 1;
  8061. if ($next_level < 62) {
  8062. $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
  8063. $cel = $next_level;
  8064. $dos = 'N';
  8065. $sor = $eor;
  8066. $eor = $cel % 2 ? 'R' : 'L';
  8067. }
  8068. } elseif ($ta[$i] == K_LRE) {
  8069. // X3. With each LRE, compute the least greater even embedding level.
  8070. // 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.
  8071. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  8072. $next_level = $cel + 2 - ($cel % 2);
  8073. if ( $next_level < 62 ) {
  8074. $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
  8075. $cel = $next_level;
  8076. $dos = 'N';
  8077. $sor = $eor;
  8078. $eor = $cel % 2 ? 'R' : 'L';
  8079. }
  8080. } elseif ($ta[$i] == K_RLO) {
  8081. // X4. With each RLO, compute the least greater odd embedding level.
  8082. // 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.
  8083. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  8084. $next_level = $cel + ($cel % 2) + 1;
  8085. if ($next_level < 62) {
  8086. $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
  8087. $cel = $next_level;
  8088. $dos = 'R';
  8089. $sor = $eor;
  8090. $eor = $cel % 2 ? 'R' : 'L';
  8091. }
  8092. } elseif ($ta[$i] == K_LRO) {
  8093. // X5. With each LRO, compute the least greater even embedding level.
  8094. // 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.
  8095. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  8096. $next_level = $cel + 2 - ($cel % 2);
  8097. if ( $next_level < 62 ) {
  8098. $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
  8099. $cel = $next_level;
  8100. $dos = 'L';
  8101. $sor = $eor;
  8102. $eor = $cel % 2 ? 'R' : 'L';
  8103. }
  8104. } elseif ($ta[$i] == K_PDF) {
  8105. // 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.
  8106. if (count($remember)) {
  8107. $last = count($remember ) - 1;
  8108. if (($remember[$last]['num'] == K_RLE) OR
  8109. ($remember[$last]['num'] == K_LRE) OR
  8110. ($remember[$last]['num'] == K_RLO) OR
  8111. ($remember[$last]['num'] == K_LRO)) {
  8112. $match = array_pop($remember);
  8113. $cel = $match['cel'];
  8114. $dos = $match['dos'];
  8115. $sor = $eor;
  8116. $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
  8117. }
  8118. }
  8119. } elseif (($ta[$i] != K_RLE) AND
  8120. ($ta[$i] != K_LRE) AND
  8121. ($ta[$i] != K_RLO) AND
  8122. ($ta[$i] != K_LRO) AND
  8123. ($ta[$i] != K_PDF)) {
  8124. // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
  8125. // a. Set the level of the current character to the current embedding level.
  8126. // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
  8127. if ($dos != 'N') {
  8128. $chardir = $dos;
  8129. } else {
  8130. $chardir = $unicode[$ta[$i]];
  8131. }
  8132. // stores string characters and other information
  8133. $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
  8134. }
  8135. } // end for each char
  8136. // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
  8137. // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
  8138. // 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.
  8139. // 3.3.3 Resolving Weak Types
  8140. // 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.
  8141. // Nonspacing marks are now resolved based on the previous characters.
  8142. $numchars = count($chardata);
  8143. // 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.
  8144. $prevlevel = -1; // track level changes
  8145. $levcount = 0; // counts consecutive chars at the same level
  8146. for ($i=0; $i < $numchars; ++$i) {
  8147. if ($chardata[$i]['type'] == 'NSM') {
  8148. if ($levcount) {
  8149. $chardata[$i]['type'] = $chardata[$i]['sor'];
  8150. } elseif ($i > 0) {
  8151. $chardata[$i]['type'] = $chardata[($i-1)]['type'];
  8152. }
  8153. }
  8154. if ($chardata[$i]['level'] != $prevlevel) {
  8155. $levcount = 0;
  8156. } else {
  8157. ++$levcount;
  8158. }
  8159. $prevlevel = $chardata[$i]['level'];
  8160. }
  8161. // 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.
  8162. $prevlevel = -1;
  8163. $levcount = 0;
  8164. for ($i=0; $i < $numchars; ++$i) {
  8165. if ($chardata[$i]['char'] == 'EN') {
  8166. for ($j=$levcount; $j >= 0; $j--) {
  8167. if ($chardata[$j]['type'] == 'AL') {
  8168. $chardata[$i]['type'] = 'AN';
  8169. } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
  8170. break;
  8171. }
  8172. }
  8173. }
  8174. if ($chardata[$i]['level'] != $prevlevel) {
  8175. $levcount = 0;
  8176. } else {
  8177. ++$levcount;
  8178. }
  8179. $prevlevel = $chardata[$i]['level'];
  8180. }
  8181. // W3. Change all ALs to R.
  8182. for ($i=0; $i < $numchars; ++$i) {
  8183. if ($chardata[$i]['type'] == 'AL') {
  8184. $chardata[$i]['type'] = 'R';
  8185. }
  8186. }
  8187. // 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.
  8188. $prevlevel = -1;
  8189. $levcount = 0;
  8190. for ($i=0; $i < $numchars; ++$i) {
  8191. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  8192. if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  8193. $chardata[$i]['type'] = 'EN';
  8194. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  8195. $chardata[$i]['type'] = 'EN';
  8196. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
  8197. $chardata[$i]['type'] = 'AN';
  8198. }
  8199. }
  8200. if ($chardata[$i]['level'] != $prevlevel) {
  8201. $levcount = 0;
  8202. } else {
  8203. ++$levcount;
  8204. }
  8205. $prevlevel = $chardata[$i]['level'];
  8206. }
  8207. // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
  8208. $prevlevel = -1;
  8209. $levcount = 0;
  8210. for ($i=0; $i < $numchars; ++$i) {
  8211. if ($chardata[$i]['type'] == 'ET') {
  8212. if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
  8213. $chardata[$i]['type'] = 'EN';
  8214. } else {
  8215. $j = $i+1;
  8216. while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
  8217. if ($chardata[$j]['type'] == 'EN') {
  8218. $chardata[$i]['type'] = 'EN';
  8219. break;
  8220. } elseif ($chardata[$j]['type'] != 'ET') {
  8221. break;
  8222. }
  8223. ++$j;
  8224. }
  8225. }
  8226. }
  8227. if ($chardata[$i]['level'] != $prevlevel) {
  8228. $levcount = 0;
  8229. } else {
  8230. ++$levcount;
  8231. }
  8232. $prevlevel = $chardata[$i]['level'];
  8233. }
  8234. // W6. Otherwise, separators and terminators change to Other Neutral.
  8235. $prevlevel = -1;
  8236. $levcount = 0;
  8237. for ($i=0; $i < $numchars; ++$i) {
  8238. if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
  8239. $chardata[$i]['type'] = 'ON';
  8240. }
  8241. if ($chardata[$i]['level'] != $prevlevel) {
  8242. $levcount = 0;
  8243. } else {
  8244. ++$levcount;
  8245. }
  8246. $prevlevel = $chardata[$i]['level'];
  8247. }
  8248. //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.
  8249. $prevlevel = -1;
  8250. $levcount = 0;
  8251. for ($i=0; $i < $numchars; ++$i) {
  8252. if ($chardata[$i]['char'] == 'EN') {
  8253. for ($j=$levcount; $j >= 0; $j--) {
  8254. if ($chardata[$j]['type'] == 'L') {
  8255. $chardata[$i]['type'] = 'L';
  8256. } elseif ($chardata[$j]['type'] == 'R') {
  8257. break;
  8258. }
  8259. }
  8260. }
  8261. if ($chardata[$i]['level'] != $prevlevel) {
  8262. $levcount = 0;
  8263. } else {
  8264. ++$levcount;
  8265. }
  8266. $prevlevel = $chardata[$i]['level'];
  8267. }
  8268. // 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.
  8269. $prevlevel = -1;
  8270. $levcount = 0;
  8271. for ($i=0; $i < $numchars; ++$i) {
  8272. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  8273. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  8274. $chardata[$i]['type'] = 'L';
  8275. } elseif (($chardata[$i]['type'] == 'N') AND
  8276. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  8277. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  8278. $chardata[$i]['type'] = 'R';
  8279. } elseif ($chardata[$i]['type'] == 'N') {
  8280. // N2. Any remaining neutrals take the embedding direction
  8281. $chardata[$i]['type'] = $chardata[$i]['sor'];
  8282. }
  8283. } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  8284. // first char
  8285. if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  8286. $chardata[$i]['type'] = 'L';
  8287. } elseif (($chardata[$i]['type'] == 'N') AND
  8288. (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
  8289. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  8290. $chardata[$i]['type'] = 'R';
  8291. } elseif ($chardata[$i]['type'] == 'N') {
  8292. // N2. Any remaining neutrals take the embedding direction
  8293. $chardata[$i]['type'] = $chardata[$i]['sor'];
  8294. }
  8295. } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
  8296. //last char
  8297. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
  8298. $chardata[$i]['type'] = 'L';
  8299. } elseif (($chardata[$i]['type'] == 'N') AND
  8300. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  8301. (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
  8302. $chardata[$i]['type'] = 'R';
  8303. } elseif ($chardata[$i]['type'] == 'N') {
  8304. // N2. Any remaining neutrals take the embedding direction
  8305. $chardata[$i]['type'] = $chardata[$i]['sor'];
  8306. }
  8307. } elseif ($chardata[$i]['type'] == 'N') {
  8308. // N2. Any remaining neutrals take the embedding direction
  8309. $chardata[$i]['type'] = $chardata[$i]['sor'];
  8310. }
  8311. if ($chardata[$i]['level'] != $prevlevel) {
  8312. $levcount = 0;
  8313. } else {
  8314. ++$levcount;
  8315. }
  8316. $prevlevel = $chardata[$i]['level'];
  8317. }
  8318. // 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.
  8319. // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
  8320. for ($i=0; $i < $numchars; ++$i) {
  8321. $odd = $chardata[$i]['level'] % 2;
  8322. if ($odd) {
  8323. if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  8324. $chardata[$i]['level'] += 1;
  8325. }
  8326. } else {
  8327. if ($chardata[$i]['type'] == 'R') {
  8328. $chardata[$i]['level'] += 1;
  8329. } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  8330. $chardata[$i]['level'] += 2;
  8331. }
  8332. }
  8333. $maxlevel = max($chardata[$i]['level'],$maxlevel);
  8334. }
  8335. // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
  8336. // 1. Segment separators,
  8337. // 2. Paragraph separators,
  8338. // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
  8339. // 4. Any sequence of white space characters at the end of the line.
  8340. for ($i=0; $i < $numchars; ++$i) {
  8341. if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
  8342. $chardata[$i]['level'] = $pel;
  8343. } elseif ($chardata[$i]['type'] == 'WS') {
  8344. $j = $i+1;
  8345. while ($j < $numchars) {
  8346. if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
  8347. (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
  8348. $chardata[$i]['level'] = $pel;
  8349. break;
  8350. } elseif ($chardata[$j]['type'] != 'WS') {
  8351. break;
  8352. }
  8353. ++$j;
  8354. }
  8355. }
  8356. }
  8357. // Arabic Shaping
  8358. // 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.
  8359. if ($arabic) {
  8360. $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
  8361. $alfletter = array(1570,1571,1573,1575);
  8362. $chardata2 = $chardata;
  8363. $laaletter = false;
  8364. $charAL = array();
  8365. $x = 0;
  8366. for ($i=0; $i < $numchars; ++$i) {
  8367. if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
  8368. $charAL[$x] = $chardata[$i];
  8369. $charAL[$x]['i'] = $i;
  8370. $chardata[$i]['x'] = $x;
  8371. ++$x;
  8372. }
  8373. }
  8374. $numAL = $x;
  8375. for ($i=0; $i < $numchars; ++$i) {
  8376. $thischar = $chardata[$i];
  8377. if ($i > 0) {
  8378. $prevchar = $chardata[($i-1)];
  8379. } else {
  8380. $prevchar = false;
  8381. }
  8382. if (($i+1) < $numchars) {
  8383. $nextchar = $chardata[($i+1)];
  8384. } else {
  8385. $nextchar = false;
  8386. }
  8387. if ($unicode[$thischar['char']] == 'AL') {
  8388. $x = $thischar['x'];
  8389. if ($x > 0) {
  8390. $prevchar = $charAL[($x-1)];
  8391. } else {
  8392. $prevchar = false;
  8393. }
  8394. if (($x+1) < $numAL) {
  8395. $nextchar = $charAL[($x+1)];
  8396. } else {
  8397. $nextchar = false;
  8398. }
  8399. // if laa letter
  8400. if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
  8401. $arabicarr = $laa_array;
  8402. $laaletter = true;
  8403. if ($x > 1) {
  8404. $prevchar = $charAL[($x-2)];
  8405. } else {
  8406. $prevchar = false;
  8407. }
  8408. } else {
  8409. $arabicarr = $unicode_arlet;
  8410. $laaletter = false;
  8411. }
  8412. if (($prevchar !== false) AND ($nextchar !== false) AND
  8413. (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
  8414. (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
  8415. ($prevchar['type'] == $thischar['type']) AND
  8416. ($nextchar['type'] == $thischar['type']) AND
  8417. ($nextchar['char'] != 1567)) {
  8418. if (in_array($prevchar['char'], $endedletter)) {
  8419. if (isset($arabicarr[$thischar['char']][2])) {
  8420. // initial
  8421. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  8422. }
  8423. } else {
  8424. if (isset($arabicarr[$thischar['char']][3])) {
  8425. // medial
  8426. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
  8427. }
  8428. }
  8429. } elseif (($nextchar !== false) AND
  8430. (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
  8431. ($nextchar['type'] == $thischar['type']) AND
  8432. ($nextchar['char'] != 1567)) {
  8433. if (isset($arabicarr[$chardata[$i]['char']][2])) {
  8434. // initial
  8435. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  8436. }
  8437. } elseif ((($prevchar !== false) AND
  8438. (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
  8439. ($prevchar['type'] == $thischar['type'])) OR
  8440. (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
  8441. // final
  8442. if (($i > 1) AND ($thischar['char'] == 1607) AND
  8443. ($chardata[$i-1]['char'] == 1604) AND
  8444. ($chardata[$i-2]['char'] == 1604)) {
  8445. //Allah Word
  8446. // mark characters to delete with false
  8447. $chardata2[$i-2]['char'] = false;
  8448. $chardata2[$i-1]['char'] = false;
  8449. $chardata2[$i]['char'] = 65010;
  8450. } else {
  8451. if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
  8452. if (isset($arabicarr[$thischar['char']][0])) {
  8453. // isolated
  8454. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  8455. }
  8456. } else {
  8457. if (isset($arabicarr[$thischar['char']][1])) {
  8458. // final
  8459. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
  8460. }
  8461. }
  8462. }
  8463. } elseif (isset($arabicarr[$thischar['char']][0])) {
  8464. // isolated
  8465. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  8466. }
  8467. // if laa letter
  8468. if ($laaletter) {
  8469. // mark characters to delete with false
  8470. $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
  8471. }
  8472. } // end if AL (Arabic Letter)
  8473. } // end for each char
  8474. /*
  8475. * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
  8476. * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
  8477. */
  8478. $cw = &$this->CurrentFont['cw'];
  8479. for ($i = 0; $i < ($numchars-1); ++$i) {
  8480. if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
  8481. // check if the subtitution font is defined on current font
  8482. if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
  8483. $chardata2[$i]['char'] = false;
  8484. $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
  8485. }
  8486. }
  8487. }
  8488. // remove marked characters
  8489. foreach ($chardata2 as $key => $value) {
  8490. if ($value['char'] === false) {
  8491. unset($chardata2[$key]);
  8492. }
  8493. }
  8494. $chardata = array_values($chardata2);
  8495. $numchars = count($chardata);
  8496. unset($chardata2);
  8497. unset($arabicarr);
  8498. unset($laaletter);
  8499. unset($charAL);
  8500. }
  8501. // 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.
  8502. for ($j=$maxlevel; $j > 0; $j--) {
  8503. $ordarray = Array();
  8504. $revarr = Array();
  8505. $onlevel = false;
  8506. for ($i=0; $i < $numchars; ++$i) {
  8507. if ($chardata[$i]['level'] >= $j) {
  8508. $onlevel = true;
  8509. if (isset($unicode_mirror[$chardata[$i]['char']])) {
  8510. // 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.
  8511. $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
  8512. }
  8513. $revarr[] = $chardata[$i];
  8514. } else {
  8515. if ($onlevel) {
  8516. $revarr = array_reverse($revarr);
  8517. $ordarray = array_merge($ordarray, $revarr);
  8518. $revarr = Array();
  8519. $onlevel = false;
  8520. }
  8521. $ordarray[] = $chardata[$i];
  8522. }
  8523. }
  8524. if ($onlevel) {
  8525. $revarr = array_reverse($revarr);
  8526. $ordarray = array_merge($ordarray, $revarr);
  8527. }
  8528. $chardata = $ordarray;
  8529. }
  8530. $ordarray = array();
  8531. for ($i=0; $i < $numchars; ++$i) {
  8532. $ordarray[] = $chardata[$i]['char'];
  8533. }
  8534. return $ordarray;
  8535. }
  8536. // END OF BIDIRECTIONAL TEXT SECTION -------------------
  8537. /*
  8538. * Adds a bookmark.
  8539. * @param string $txt bookmark description.
  8540. * @param int $level bookmark level (minimum value is 0).
  8541. * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
  8542. * @param int $page target page number (leave empty for current page).
  8543. * @access public
  8544. * @author Olivier Plathey, Nicola Asuni
  8545. * @since 2.1.002 (2008-02-12)
  8546. */
  8547. public function Bookmark($txt, $level=0, $y=-1, $page='') {
  8548. if ($level < 0) {
  8549. $level = 0;
  8550. }
  8551. if (isset($this->outlines[0])) {
  8552. $lastoutline = end($this->outlines);
  8553. $maxlevel = $lastoutline['l'] + 1;
  8554. } else {
  8555. $maxlevel = 0;
  8556. }
  8557. if ($level > $maxlevel) {
  8558. $level = $maxlevel;
  8559. }
  8560. if ($y == -1) {
  8561. $y = $this->GetY();
  8562. }
  8563. if (empty($page)) {
  8564. $page = $this->PageNo();
  8565. }
  8566. $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page);
  8567. }
  8568. /*
  8569. * Create a bookmark PDF string.
  8570. * @access protected
  8571. * @author Olivier Plathey, Nicola Asuni
  8572. * @since 2.1.002 (2008-02-12)
  8573. */
  8574. protected function _putbookmarks() {
  8575. $nb = count($this->outlines);
  8576. if ($nb == 0) {
  8577. return;
  8578. }
  8579. $lru = array();
  8580. $level = 0;
  8581. foreach ($this->outlines as $i => $o) {
  8582. if ($o['l'] > 0) {
  8583. $parent = $lru[($o['l'] - 1)];
  8584. //Set parent and last pointers
  8585. $this->outlines[$i]['parent'] = $parent;
  8586. $this->outlines[$parent]['last'] = $i;
  8587. if ($o['l'] > $level) {
  8588. //Level increasing: set first pointer
  8589. $this->outlines[$parent]['first'] = $i;
  8590. }
  8591. } else {
  8592. $this->outlines[$i]['parent'] = $nb;
  8593. }
  8594. if (($o['l'] <= $level) AND ($i > 0)) {
  8595. //Set prev and next pointers
  8596. $prev = $lru[$o['l']];
  8597. $this->outlines[$prev]['next'] = $i;
  8598. $this->outlines[$i]['prev'] = $prev;
  8599. }
  8600. $lru[$o['l']] = $i;
  8601. $level = $o['l'];
  8602. }
  8603. //Outline items
  8604. $n = $this->n + 1;
  8605. foreach ($this->outlines as $i => $o) {
  8606. $this->_newobj();
  8607. $this->_out('<</Title '.$this->_textstring($o['t']));
  8608. $this->_out('/Parent '.($n + $o['parent']).' 0 R');
  8609. if (isset($o['prev']))
  8610. $this->_out('/Prev '.($n + $o['prev']).' 0 R');
  8611. if (isset($o['next']))
  8612. $this->_out('/Next '.($n + $o['next']).' 0 R');
  8613. if (isset($o['first']))
  8614. $this->_out('/First '.($n + $o['first']).' 0 R');
  8615. if (isset($o['last']))
  8616. $this->_out('/Last '.($n + $o['last']).' 0 R');
  8617. $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $o['p'])), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k))));
  8618. $this->_out('/Count 0>>');
  8619. $this->_out('endobj');
  8620. }
  8621. //Outline root
  8622. $this->_newobj();
  8623. $this->OutlineRoot = $this->n;
  8624. $this->_out('<</Type /Outlines /First '.$n.' 0 R');
  8625. $this->_out('/Last '.($n + $lru[0]).' 0 R>>');
  8626. $this->_out('endobj');
  8627. }
  8628. // --- JAVASCRIPT - FORMS ------------------------------
  8629. /*
  8630. * Adds a javascript
  8631. * @access public
  8632. * @author Johannes G�ntert, Nicola Asuni
  8633. * @since 2.1.002 (2008-02-12)
  8634. */
  8635. public function IncludeJS($script) {
  8636. $this->javascript .= $script;
  8637. }
  8638. /*
  8639. * Create a javascript PDF string.
  8640. * @access protected
  8641. * @author Johannes G�ntert, Nicola Asuni
  8642. * @since 2.1.002 (2008-02-12)
  8643. */
  8644. protected function _putjavascript() {
  8645. if (empty($this->javascript)) {
  8646. return;
  8647. }
  8648. // the following two lines are uded to avoid form fields duplication after saving
  8649. $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  8650. $js2 = "getField('tcpdfdocsaved').value = 'saved';";
  8651. $this->_newobj();
  8652. $this->n_js = $this->n;
  8653. $this->_out('<<');
  8654. $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
  8655. $this->_out('>>');
  8656. $this->_out('endobj');
  8657. $this->_newobj();
  8658. $this->_out('<<');
  8659. $this->_out('/S /JavaScript');
  8660. $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
  8661. $this->_out('>>');
  8662. $this->_out('endobj');
  8663. }
  8664. /*
  8665. * Convert color to javascript color.
  8666. * @param string $color color name or #RRGGBB
  8667. * @access protected
  8668. * @author Denis Van Nuffelen, Nicola Asuni
  8669. * @since 2.1.002 (2008-02-12)
  8670. */
  8671. protected function _JScolor($color) {
  8672. static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
  8673. if (substr($color,0,1) == '#') {
  8674. return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
  8675. }
  8676. if (!in_array($color,$aColors)) {
  8677. $this->Error('Invalid color: '.$color);
  8678. }
  8679. return 'color.'.$color;
  8680. }
  8681. /*
  8682. * Adds a javascript form field.
  8683. * @param string $type field type
  8684. * @param string $name field name
  8685. * @param int $x horizontal position
  8686. * @param int $y vertical position
  8687. * @param int $w width
  8688. * @param int $h height
  8689. * @param array $prop array of properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8690. * @access protected
  8691. * @author Denis Van Nuffelen, Nicola Asuni
  8692. * @since 2.1.002 (2008-02-12)
  8693. */
  8694. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  8695. if ($this->rtl) {
  8696. $x = $x - $w;
  8697. }
  8698. // the followind avoid fields duplication after saving the document
  8699. $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
  8700. $k = $this->k;
  8701. $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
  8702. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  8703. while (list($key, $val) = each($prop)) {
  8704. if (strcmp(substr($key, -5), 'Color') == 0) {
  8705. $val = $this->_JScolor($val);
  8706. } else {
  8707. $val = "'".$val."'";
  8708. }
  8709. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  8710. }
  8711. if ($this->rtl) {
  8712. $this->x -= $w;
  8713. } else {
  8714. $this->x += $w;
  8715. }
  8716. $this->javascript .= '}';
  8717. }
  8718. /*
  8719. * Creates a text field
  8720. * @param string $name field name
  8721. * @param int $w width
  8722. * @param int $h height
  8723. * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8724. * @access public
  8725. * @author Denis Van Nuffelen, Nicola Asuni
  8726. * @since 2.1.002 (2008-02-12)
  8727. */
  8728. public function TextField($name, $w, $h, $prop=array()) {
  8729. $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
  8730. }
  8731. /*
  8732. * Creates a RadioButton field
  8733. * @param string $name field name
  8734. * @param int $w width
  8735. * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8736. * @access public
  8737. * @author Nicola Asuni
  8738. * @since 2.2.003 (2008-03-03)
  8739. */
  8740. public function RadioButton($name, $w, $prop=array()) {
  8741. if (!isset($prop['strokeColor'])) {
  8742. $prop['strokeColor']='black';
  8743. }
  8744. $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
  8745. }
  8746. /*
  8747. * Creates a List-box field
  8748. * @param string $name field name
  8749. * @param int $w width
  8750. * @param int $h height
  8751. * @param array $values array containing the list of values.
  8752. * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8753. * @access public
  8754. * @author Nicola Asuni
  8755. * @since 2.2.003 (2008-03-03)
  8756. */
  8757. public function ListBox($name, $w, $h, $values, $prop=array()) {
  8758. if (!isset($prop['strokeColor'])) {
  8759. $prop['strokeColor'] = 'ltGray';
  8760. }
  8761. $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
  8762. $s = '';
  8763. foreach ($values as $value) {
  8764. $s .= "'".addslashes($value)."',";
  8765. }
  8766. $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
  8767. }
  8768. /*
  8769. * Creates a Combo-box field
  8770. * @param string $name field name
  8771. * @param int $w width
  8772. * @param int $h height
  8773. * @param array $values array containing the list of values.
  8774. * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8775. * @access public
  8776. * @author Denis Van Nuffelen, Nicola Asuni
  8777. * @since 2.1.002 (2008-02-12)
  8778. */
  8779. public function ComboBox($name, $w, $h, $values, $prop=array()) {
  8780. $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
  8781. $s = '';
  8782. foreach ($values as $value) {
  8783. $s .= "'".addslashes($value)."',";
  8784. }
  8785. $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
  8786. }
  8787. /*
  8788. * Creates a CheckBox field
  8789. * @param string $name field name
  8790. * @param int $w width
  8791. * @param boolean $checked define the initial state (default = false).
  8792. * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8793. * @access public
  8794. * @author Denis Van Nuffelen, Nicola Asuni
  8795. * @since 2.1.002 (2008-02-12)
  8796. */
  8797. public function CheckBox($name, $w, $checked=false, $prop=array()) {
  8798. $prop['value'] = ($checked ? 'Yes' : 'Off');
  8799. if (!isset($prop['strokeColor'])) {
  8800. $prop['strokeColor'] = 'black';
  8801. }
  8802. $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
  8803. }
  8804. /*
  8805. * Creates a button field
  8806. * @param string $name field name
  8807. * @param int $w width
  8808. * @param int $h height
  8809. * @param string $caption caption.
  8810. * @param string $action action triggered by the button (JavaScript code).
  8811. * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
  8812. * @access public
  8813. * @author Denis Van Nuffelen, Nicola Asuni
  8814. * @since 2.1.002 (2008-02-12)
  8815. */
  8816. public function Button($name, $w, $h, $caption, $action, $prop=array()) {
  8817. if (!isset($prop['strokeColor'])) {
  8818. $prop['strokeColor'] = 'black';
  8819. }
  8820. if (!isset($prop['borderStyle'])) {
  8821. $prop['borderStyle'] = 'beveled';
  8822. }
  8823. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  8824. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  8825. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  8826. $this->javascript .= 'f'.$name.".highlight='push';\n";
  8827. $this->javascript .= 'f'.$name.".print=false;\n";
  8828. }
  8829. // END JAVASCRIPT - FORMS ------------------------------
  8830. /*
  8831. * Enable Write permissions for PDF Reader.
  8832. * WARNING: This works only using the Adobe private key with the setSignature() method.
  8833. * @access protected
  8834. * @author Nicola Asuni
  8835. * @since 2.9.000 (2008-03-26)
  8836. */
  8837. protected function _putuserrights() {
  8838. if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] > 0))) {
  8839. return;
  8840. }
  8841. $this->_out('/Perms');
  8842. $this->_out('<<');
  8843. $this->_out('/UR3');
  8844. $this->_out('<<');
  8845. $this->_out('/Type/Sig');
  8846. $this->_out('/Filter/Adobe.PPKLite');
  8847. $this->_out('/SubFilter/adbe.pkcs7.detached');
  8848. $this->_out('/ByteRange[0 ********** ********** **********]');
  8849. $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
  8850. if ($this->ur) {
  8851. $this->_out('/Reference');
  8852. $this->_out('[');
  8853. $this->_out('<<');
  8854. $this->_out('/Type/SigRef');
  8855. $this->_out('/TransformMethod/UR3');
  8856. $this->_out('/TransformParams');
  8857. $this->_out('<<');
  8858. $this->_out('/Type/TransformParams');
  8859. $this->_out('/V/2.2');
  8860. if (!$this->empty_string($this->ur_document)) {
  8861. $this->_out('/Document['.$this->ur_document.']');
  8862. }
  8863. if (!$this->empty_string($this->ur_annots)) {
  8864. $this->_out('/Annots['.$this->ur_annots.']');
  8865. }
  8866. if (!$this->empty_string($this->ur_form)) {
  8867. $this->_out('/Form['.$this->ur_form.']');
  8868. }
  8869. if (!$this->empty_string($this->ur_signature)) {
  8870. $this->_out('/Signature['.$this->ur_signature.']');
  8871. }
  8872. $this->_out('>>');
  8873. $this->_out('>>');
  8874. $this->_out(']');
  8875. }
  8876. $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
  8877. $this->_out('>>');
  8878. $this->_out('>>');
  8879. }
  8880. /*
  8881. * Add certification signature (DocMDP)
  8882. * @access protected
  8883. * @author Nicola Asuni
  8884. * @since 4.6.008 (2009-05-07)
  8885. */
  8886. protected function _putcertification() {
  8887. if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] <= 0))) {
  8888. return;
  8889. }
  8890. $this->_out('/Perms');
  8891. $this->_out('<<');
  8892. $this->_out('/DocMDP');
  8893. $this->_out('<<');
  8894. $this->_out('/Type/Sig');
  8895. $this->_out('/Filter/Adobe.PPKLite');
  8896. $this->_out('/SubFilter/adbe.pkcs7.detached');
  8897. $this->_out('/ByteRange[0 ********** ********** **********]');
  8898. $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
  8899. $this->_out('/Reference');
  8900. $this->_out('[');
  8901. $this->_out('<<');
  8902. $this->_out('/Type/SigRef');
  8903. $this->_out('/TransformMethod/DocMDP');
  8904. $this->_out('/TransformParams');
  8905. $this->_out('<<');
  8906. $this->_out('/Type/TransformParams');
  8907. $this->_out('/V/1.2');
  8908. $this->_out('/P '.$this->signature_data['cert_type'].'');
  8909. $this->_out('>>');
  8910. $this->_out('>>');
  8911. $this->_out(']');
  8912. $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
  8913. if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
  8914. $this->_out('/Name '.$this->_textstring($this->signature_data['info']['Name']).'');
  8915. }
  8916. if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
  8917. $this->_out('/Location '.$this->_textstring($this->signature_data['info']['Location']).'');
  8918. }
  8919. if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
  8920. $this->_out('/Reason '.$this->_textstring($this->signature_data['info']['Reason']).'');
  8921. }
  8922. if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
  8923. $this->_out('/ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo']).'');
  8924. }
  8925. $this->_out('>>');
  8926. $this->_out('>>');
  8927. }
  8928. /*
  8929. * Set User's Rights for PDF Reader
  8930. * WARNING: This works only using the Adobe private key with the setSignature() method!.
  8931. * Check the PDF Reference 8.7.1 Transform Methods,
  8932. * Table 8.105 Entries in the UR transform parameters dictionary
  8933. * @param boolean $enable if true enable user's rights on PDF reader
  8934. * @param string $document 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.
  8935. * @param string $annots 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.
  8936. * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  8937. * @param string $signature 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.
  8938. * @access public
  8939. * @author Nicola Asuni
  8940. * @since 2.9.000 (2008-03-26)
  8941. */
  8942. public function setUserRights(
  8943. $enable=true,
  8944. $document='/FullSave',
  8945. $annots='/Create/Delete/Modify/Copy/Import/Export',
  8946. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  8947. $signature='/Modify') {
  8948. $this->ur = $enable;
  8949. $this->ur_document = $document;
  8950. $this->ur_annots = $annots;
  8951. $this->ur_form = $form;
  8952. $this->ur_signature = $signature;
  8953. }
  8954. /*
  8955. * Enable document signature (requires the OpenSSL Library).
  8956. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  8957. * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://')
  8958. * @param mixed $private_key private key (string or filename prefixed with 'file://')
  8959. * @param string $private_key_password password
  8960. * @param string $extracerts 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.
  8961. * @param int $cert_type 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.
  8962. * @parm array $info array of option information: Name, Location, Reason, ContactInfo.
  8963. * @access public
  8964. * @author Nicola Asuni
  8965. * @since 4.6.005 (2009-04-24)
  8966. */
  8967. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
  8968. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.pem -out tcpdf.pem
  8969. $this->sign = true;
  8970. $this->signature_data = array();
  8971. if (strlen($signing_cert) == 0) {
  8972. $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.pem';
  8973. }
  8974. if (strlen($private_key) == 0) {
  8975. $private_key = $signing_cert;
  8976. }
  8977. $this->signature_data['signcert'] = $signing_cert;
  8978. $this->signature_data['privkey'] = $private_key;
  8979. $this->signature_data['password'] = $private_key_password;
  8980. $this->signature_data['extracerts'] = $extracerts;
  8981. $this->signature_data['cert_type'] = $cert_type;
  8982. $this->signature_data['info'] = array();
  8983. }
  8984. /*
  8985. * Create a new page group.
  8986. * NOTE: call this function before calling AddPage()
  8987. * @param int $page starting group page (leave empty for next page).
  8988. * @access public
  8989. * @since 3.0.000 (2008-03-27)
  8990. */
  8991. public function startPageGroup($page='') {
  8992. if (empty($page)) {
  8993. $page = $this->page + 1;
  8994. }
  8995. $this->newpagegroup[$page] = true;
  8996. }
  8997. /**
  8998. * Defines an alias for the total number of pages.
  8999. * It will be substituted as the document is closed.
  9000. * @param string $alias The alias.
  9001. * @access public
  9002. * @since 1.4
  9003. * @see getAliasNbPages(), PageNo(), Footer()
  9004. */
  9005. public function AliasNbPages($alias='{nb}') {
  9006. $this->AliasNbPages = $alias;
  9007. }
  9008. /**
  9009. * Returns the string alias used for the total number of pages.
  9010. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  9011. * @return string
  9012. * @access public
  9013. * @since 4.0.018 (2008-08-08)
  9014. * @see AliasNbPages(), PageNo(), Footer()
  9015. */
  9016. public function getAliasNbPages() {
  9017. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  9018. return '{'.$this->AliasNbPages.'}';
  9019. }
  9020. return $this->AliasNbPages;
  9021. }
  9022. /**
  9023. * Defines an alias for the page number.
  9024. * It will be substituted as the document is closed.
  9025. * @param string $alias The alias.
  9026. * @access public
  9027. * @since 4.5.000 (2009-01-02)
  9028. * @see getAliasNbPages(), PageNo(), Footer()
  9029. */
  9030. public function AliasNumPage($alias='{pnb}') {
  9031. //Define an alias for total number of pages
  9032. $this->AliasNumPage = $alias;
  9033. }
  9034. /**
  9035. * Returns the string alias used for the page number.
  9036. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  9037. * @return string
  9038. * @access public
  9039. * @since 4.5.000 (2009-01-02)
  9040. * @see AliasNbPages(), PageNo(), Footer()
  9041. */
  9042. public function getAliasNumPage() {
  9043. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  9044. return '{'.$this->AliasNumPage.'}';
  9045. }
  9046. return $this->AliasNumPage;
  9047. }
  9048. /*
  9049. * Return the current page in the group.
  9050. * @return current page in the group
  9051. * @access public
  9052. * @since 3.0.000 (2008-03-27)
  9053. */
  9054. public function getGroupPageNo() {
  9055. return $this->pagegroups[$this->currpagegroup];
  9056. }
  9057. /**
  9058. * Returns the current group page number formatted as a string.
  9059. * @access public
  9060. * @since 4.3.003 (2008-11-18)
  9061. * @see PaneNo(), formatPageNumber()
  9062. */
  9063. public function getGroupPageNoFormatted() {
  9064. return $this->formatPageNumber($this->getGroupPageNo());
  9065. }
  9066. /*
  9067. * Return the alias of the current page group
  9068. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  9069. * (will be replaced by the total number of pages in this group).
  9070. * @return alias of the current page group
  9071. * @access public
  9072. * @since 3.0.000 (2008-03-27)
  9073. */
  9074. public function getPageGroupAlias() {
  9075. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  9076. return '{'.$this->currpagegroup.'}';
  9077. }
  9078. return $this->currpagegroup;
  9079. }
  9080. /*
  9081. * Return the alias for the page number on the current page group
  9082. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  9083. * (will be replaced by the total number of pages in this group).
  9084. * @return alias of the current page group
  9085. * @access public
  9086. * @since 4.5.000 (2009-01-02)
  9087. */
  9088. public function getPageNumGroupAlias() {
  9089. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  9090. return '{'.str_replace('{nb', '{pnb', $this->currpagegroup).'}';
  9091. }
  9092. return str_replace('{nb', '{pnb', $this->currpagegroup);
  9093. }
  9094. /**
  9095. * Format the page numbers.
  9096. * This method can be overriden for custom formats.
  9097. * @param int $num page number
  9098. * @access protected
  9099. * @since 4.2.005 (2008-11-06)
  9100. */
  9101. protected function formatPageNumber($num) {
  9102. return number_format((float)$num, 0, '', '.');
  9103. }
  9104. /**
  9105. * Format the page numbers on the Table Of Content.
  9106. * This method can be overriden for custom formats.
  9107. * @param int $num page number
  9108. * @access protected
  9109. * @since 4.5.001 (2009-01-04)
  9110. * @see addTOC()
  9111. */
  9112. protected function formatTOCPageNumber($num) {
  9113. return number_format((float)$num, 0, '', '.');
  9114. }
  9115. /**
  9116. * Returns the current page number formatted as a string.
  9117. * @access public
  9118. * @since 4.2.005 (2008-11-06)
  9119. * @see PaneNo(), formatPageNumber()
  9120. */
  9121. public function PageNoFormatted() {
  9122. return $this->formatPageNumber($this->PageNo());
  9123. }
  9124. /*
  9125. * Put visibility settings.
  9126. * @access protected
  9127. * @since 3.0.000 (2008-03-27)
  9128. */
  9129. protected function _putocg() {
  9130. $this->_newobj();
  9131. $this->n_ocg_print = $this->n;
  9132. $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
  9133. $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
  9134. $this->_out('endobj');
  9135. $this->_newobj();
  9136. $this->n_ocg_view=$this->n;
  9137. $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
  9138. $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
  9139. $this->_out('endobj');
  9140. }
  9141. /*
  9142. * Set the visibility of the successive elements.
  9143. * This can be useful, for instance, to put a background
  9144. * image or color that will show on screen but won't print.
  9145. * @param string $v visibility mode. Legal values are: all, print, screen.
  9146. * @access public
  9147. * @since 3.0.000 (2008-03-27)
  9148. */
  9149. public function setVisibility($v) {
  9150. if ($this->openMarkedContent) {
  9151. // close existing open marked-content
  9152. $this->_out('EMC');
  9153. $this->openMarkedContent = false;
  9154. }
  9155. switch($v) {
  9156. case 'print': {
  9157. $this->_out('/OC /OC1 BDC');
  9158. $this->openMarkedContent = true;
  9159. break;
  9160. }
  9161. case 'screen': {
  9162. $this->_out('/OC /OC2 BDC');
  9163. $this->openMarkedContent = true;
  9164. break;
  9165. }
  9166. case 'all': {
  9167. $this->_out('');
  9168. break;
  9169. }
  9170. default: {
  9171. $this->Error('Incorrect visibility: '.$v);
  9172. break;
  9173. }
  9174. }
  9175. $this->visibility = $v;
  9176. }
  9177. /*
  9178. * Add transparency parameters to the current extgstate
  9179. * @param array $params parameters
  9180. * @return the number of extgstates
  9181. * @access protected
  9182. * @since 3.0.000 (2008-03-27)
  9183. */
  9184. protected function addExtGState($parms) {
  9185. $n = count($this->extgstates) + 1;
  9186. $this->extgstates[$n]['parms'] = $parms;
  9187. return $n;
  9188. }
  9189. /*
  9190. * Add an extgstate
  9191. * @param array $gs extgstate
  9192. * @access protected
  9193. * @since 3.0.000 (2008-03-27)
  9194. */
  9195. protected function setExtGState($gs) {
  9196. $this->_out(sprintf('/GS%d gs', $gs));
  9197. }
  9198. /*
  9199. * Put extgstates for object transparency
  9200. * @param array $gs extgstate
  9201. * @access protected
  9202. * @since 3.0.000 (2008-03-27)
  9203. */
  9204. protected function _putextgstates() {
  9205. $ne = count($this->extgstates);
  9206. for ($i = 1; $i <= $ne; ++$i) {
  9207. $this->_newobj();
  9208. $this->extgstates[$i]['n'] = $this->n;
  9209. $this->_out('<</Type /ExtGState');
  9210. foreach ($this->extgstates[$i]['parms'] as $k => $v) {
  9211. $this->_out('/'.$k.' '.$v);
  9212. }
  9213. $this->_out('>>');
  9214. $this->_out('endobj');
  9215. }
  9216. }
  9217. /*
  9218. * Set alpha for stroking (CA) and non-stroking (ca) operations.
  9219. * @param float $alpha real value from 0 (transparent) to 1 (opaque)
  9220. * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
  9221. * @access public
  9222. * @since 3.0.000 (2008-03-27)
  9223. */
  9224. public function setAlpha($alpha, $bm='Normal') {
  9225. $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
  9226. $this->setExtGState($gs);
  9227. }
  9228. /*
  9229. * Set the default JPEG compression quality (1-100)
  9230. * @param int $quality JPEG quality, integer between 1 and 100
  9231. * @access public
  9232. * @since 3.0.000 (2008-03-27)
  9233. */
  9234. public function setJPEGQuality($quality) {
  9235. if (($quality < 1) OR ($quality > 100)) {
  9236. $quality = 75;
  9237. }
  9238. $this->jpeg_quality = intval($quality);
  9239. }
  9240. /*
  9241. * Set the default number of columns in a row for HTML tables.
  9242. * @param int $cols number of columns
  9243. * @access public
  9244. * @since 3.0.014 (2008-06-04)
  9245. */
  9246. public function setDefaultTableColumns($cols=4) {
  9247. $this->default_table_columns = intval($cols);
  9248. }
  9249. /*
  9250. * Set the height of cell repect font height.
  9251. * @param int $h cell proportion respect font height (typical value = 1.25).
  9252. * @access public
  9253. * @since 3.0.014 (2008-06-04)
  9254. */
  9255. public function setCellHeightRatio($h) {
  9256. $this->cell_height_ratio = $h;
  9257. }
  9258. /*
  9259. * return the height of cell repect font height.
  9260. * @access public
  9261. * @since 4.0.012 (2008-07-24)
  9262. */
  9263. public function getCellHeightRatio() {
  9264. return $this->cell_height_ratio;
  9265. }
  9266. /*
  9267. * Set the PDF version (check PDF reference for valid values).
  9268. * Default value is 1.t
  9269. * @access public
  9270. * @since 3.1.000 (2008-06-09)
  9271. */
  9272. public function setPDFVersion($version='1.7') {
  9273. $this->PDFVersion = $version;
  9274. }
  9275. /*
  9276. * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
  9277. * (see Section 8.1 of PDF reference, "Viewer Preferences").
  9278. * <ul>
  9279. * <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>
  9280. * <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>
  9281. * <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>
  9282. * <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>
  9283. * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
  9284. * <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>
  9285. * <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>
  9286. * <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>
  9287. * <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>
  9288. * <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>
  9289. * <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>
  9290. * <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>
  9291. * <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>
  9292. * <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>
  9293. * <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>
  9294. * <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>
  9295. * </ul>
  9296. * @param array $preferences array of options.
  9297. * @author Nicola Asuni
  9298. * @access public
  9299. * @since 3.1.000 (2008-06-09)
  9300. */
  9301. public function setViewerPreferences($preferences) {
  9302. $this->viewer_preferences = $preferences;
  9303. }
  9304. /**
  9305. * Paints a linear colour gradient.
  9306. * @param float $x abscissa of the top left corner of the rectangle.
  9307. * @param float $y ordinate of the top left corner of the rectangle.
  9308. * @param float $w width of the rectangle.
  9309. * @param float $h height of the rectangle.
  9310. * @param array $col1 first color (RGB components).
  9311. * @param array $col2 second color (RGB components).
  9312. * @param array $coords 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).
  9313. * @author Andreas W�rmser, Nicola Asuni
  9314. * @since 3.1.000 (2008-06-09)
  9315. * @access public
  9316. */
  9317. public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
  9318. $this->Clip($x, $y, $w, $h);
  9319. $this->Gradient(2, $col1, $col2, $coords);
  9320. }
  9321. /**
  9322. * Paints a radial colour gradient.
  9323. * @param float $x abscissa of the top left corner of the rectangle.
  9324. * @param float $y ordinate of the top left corner of the rectangle.
  9325. * @param float $w width of the rectangle.
  9326. * @param float $h height of the rectangle.
  9327. * @param array $col1 first color (RGB components).
  9328. * @param array $col2 second color (RGB components).
  9329. * @param array $coords 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.
  9330. * @author Andreas W�rmser, Nicola Asuni
  9331. * @since 3.1.000 (2008-06-09)
  9332. * @access public
  9333. */
  9334. public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
  9335. $this->Clip($x, $y, $w, $h);
  9336. $this->Gradient(3, $col1, $col2, $coords);
  9337. }
  9338. /**
  9339. * Paints a coons patch mesh.
  9340. * @param float $x abscissa of the top left corner of the rectangle.
  9341. * @param float $y ordinate of the top left corner of the rectangle.
  9342. * @param float $w width of the rectangle.
  9343. * @param float $h height of the rectangle.
  9344. * @param array $col1 first color (lower left corner) (RGB components).
  9345. * @param array $col2 second color (lower right corner) (RGB components).
  9346. * @param array $col3 third color (upper right corner) (RGB components).
  9347. * @param array $col4 fourth color (upper left corner) (RGB components).
  9348. * @param array $coords <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>
  9349. * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
  9350. * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
  9351. * @author Andreas W�rmser, Nicola Asuni
  9352. * @since 3.1.000 (2008-06-09)
  9353. * @access public
  9354. */
  9355. 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) {
  9356. $this->Clip($x, $y, $w, $h);
  9357. $n = count($this->gradients) + 1;
  9358. $this->gradients[$n]['type'] = 6; //coons patch mesh
  9359. //check the coords array if it is the simple array or the multi patch array
  9360. if (!isset($coords[0]['f'])) {
  9361. //simple array -> convert to multi patch array
  9362. if (!isset($col1[1])) {
  9363. $col1[1] = $col1[2] = $col1[0];
  9364. }
  9365. if (!isset($col2[1])) {
  9366. $col2[1] = $col2[2] = $col2[0];
  9367. }
  9368. if (!isset($col3[1])) {
  9369. $col3[1] = $col3[2] = $col3[0];
  9370. }
  9371. if (!isset($col4[1])) {
  9372. $col4[1] = $col4[2] = $col4[0];
  9373. }
  9374. $patch_array[0]['f'] = 0;
  9375. $patch_array[0]['points'] = $coords;
  9376. $patch_array[0]['colors'][0]['r'] = $col1[0];
  9377. $patch_array[0]['colors'][0]['g'] = $col1[1];
  9378. $patch_array[0]['colors'][0]['b'] = $col1[2];
  9379. $patch_array[0]['colors'][1]['r'] = $col2[0];
  9380. $patch_array[0]['colors'][1]['g'] = $col2[1];
  9381. $patch_array[0]['colors'][1]['b'] = $col2[2];
  9382. $patch_array[0]['colors'][2]['r'] = $col3[0];
  9383. $patch_array[0]['colors'][2]['g'] = $col3[1];
  9384. $patch_array[0]['colors'][2]['b'] = $col3[2];
  9385. $patch_array[0]['colors'][3]['r'] = $col4[0];
  9386. $patch_array[0]['colors'][3]['g'] = $col4[1];
  9387. $patch_array[0]['colors'][3]['b'] = $col4[2];
  9388. } else {
  9389. //multi patch array
  9390. $patch_array = $coords;
  9391. }
  9392. $bpcd = 65535; //16 BitsPerCoordinate
  9393. //build the data stream
  9394. $this->gradients[$n]['stream'] = '';
  9395. $count_patch = count($patch_array);
  9396. for ($i=0; $i < $count_patch; ++$i) {
  9397. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
  9398. $count_points = count($patch_array[$i]['points']);
  9399. for ($j=0; $j < $count_points; ++$j) {
  9400. //each point as 16 bit
  9401. $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
  9402. if ($patch_array[$i]['points'][$j] < 0) {
  9403. $patch_array[$i]['points'][$j] = 0;
  9404. }
  9405. if ($patch_array[$i]['points'][$j] > $bpcd) {
  9406. $patch_array[$i]['points'][$j] = $bpcd;
  9407. }
  9408. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
  9409. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
  9410. }
  9411. $count_cols = count($patch_array[$i]['colors']);
  9412. for ($j=0; $j < $count_cols; ++$j) {
  9413. //each color component as 8 bit
  9414. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
  9415. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
  9416. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
  9417. }
  9418. }
  9419. //paint the gradient
  9420. $this->_out('/Sh'.$n.' sh');
  9421. //restore previous Graphic State
  9422. $this->_out('Q');
  9423. }
  9424. /**
  9425. * Set a rectangular clipping area.
  9426. * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
  9427. * @param float $y ordinate of the top left corner of the rectangle.
  9428. * @param float $w width of the rectangle.
  9429. * @param float $h height of the rectangle.
  9430. * @author Andreas W�rmser, Nicola Asuni
  9431. * @since 3.1.000 (2008-06-09)
  9432. * @access protected
  9433. */
  9434. protected function Clip($x, $y, $w, $h) {
  9435. if ($this->rtl) {
  9436. $x = $this->w - $x - $w;
  9437. }
  9438. //save current Graphic State
  9439. $s = 'q';
  9440. //set clipping area
  9441. $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
  9442. //set up transformation matrix for gradient
  9443. $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
  9444. $this->_out($s);
  9445. }
  9446. /**
  9447. * Output gradient.
  9448. * @param int $type type of gradient.
  9449. * @param array $col1 first color (RGB components).
  9450. * @param array $col2 second color (RGB components).
  9451. * @param array $coords array of coordinates.
  9452. * @author Andreas W�rmser, Nicola Asuni
  9453. * @since 3.1.000 (2008-06-09)
  9454. * @access protected
  9455. */
  9456. protected function Gradient($type, $col1, $col2, $coords) {
  9457. $n = count($this->gradients) + 1;
  9458. $this->gradients[$n]['type'] = $type;
  9459. if (!isset($col1[1])) {
  9460. $col1[1]=$col1[2]=$col1[0];
  9461. }
  9462. $this->gradients[$n]['col1'] = sprintf('%.3F %.3F %.3F', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
  9463. if (!isset($col2[1])) {
  9464. $col2[1] = $col2[2] = $col2[0];
  9465. }
  9466. $this->gradients[$n]['col2'] = sprintf('%.3F %.3F %.3F', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
  9467. $this->gradients[$n]['coords'] = $coords;
  9468. //paint the gradient
  9469. $this->_out('/Sh'.$n.' sh');
  9470. //restore previous Graphic State
  9471. $this->_out('Q');
  9472. }
  9473. /**
  9474. * Output shaders.
  9475. * @author Andreas W�rmser, Nicola Asuni
  9476. * @since 3.1.000 (2008-06-09)
  9477. * @access protected
  9478. */
  9479. function _putshaders() {
  9480. foreach ($this->gradients as $id => $grad) {
  9481. if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
  9482. $this->_newobj();
  9483. $this->_out('<<');
  9484. $this->_out('/FunctionType 2');
  9485. $this->_out('/Domain [0.0 1.0]');
  9486. $this->_out('/C0 ['.$grad['col1'].']');
  9487. $this->_out('/C1 ['.$grad['col2'].']');
  9488. $this->_out('/N 1');
  9489. $this->_out('>>');
  9490. $this->_out('endobj');
  9491. $f1 = $this->n;
  9492. }
  9493. $this->_newobj();
  9494. $this->_out('<<');
  9495. $this->_out('/ShadingType '.$grad['type']);
  9496. $this->_out('/ColorSpace /DeviceRGB');
  9497. if ($grad['type'] == 2) {
  9498. $this->_out(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
  9499. $this->_out('/Function '.$f1.' 0 R');
  9500. $this->_out('/Extend [true true] ');
  9501. $this->_out('>>');
  9502. } elseif ($grad['type'] == 3) {
  9503. //x0, y0, r0, x1, y1, r1
  9504. //at this this time radius of inner circle is 0
  9505. $this->_out(sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]));
  9506. $this->_out('/Function '.$f1.' 0 R');
  9507. $this->_out('/Extend [true true] ');
  9508. $this->_out('>>');
  9509. } elseif ($grad['type'] == 6) {
  9510. $this->_out('/BitsPerCoordinate 16');
  9511. $this->_out('/BitsPerComponent 8');
  9512. $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
  9513. $this->_out('/BitsPerFlag 8');
  9514. $this->_out('/Length '.strlen($grad['stream']));
  9515. $this->_out('>>');
  9516. $this->_putstream($grad['stream']);
  9517. }
  9518. $this->_out('endobj');
  9519. $this->gradients[$id]['id'] = $this->n;
  9520. }
  9521. }
  9522. /**
  9523. * Output an arc
  9524. * @author Maxime Delorme, Nicola Asuni
  9525. * @since 3.1.000 (2008-06-09)
  9526. * @access protected
  9527. */
  9528. protected function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
  9529. $h = $this->h;
  9530. $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1*$this->k, ($h-$y1)*$this->k, $x2*$this->k, ($h-$y2)*$this->k, $x3*$this->k, ($h-$y3)*$this->k));
  9531. }
  9532. /**
  9533. * Draw the sector of a circle.
  9534. * It can be used for instance to render pie charts.
  9535. * @param float $xc abscissa of the center.
  9536. * @param float $yc ordinate of the center.
  9537. * @param float $r radius.
  9538. * @param float $a start angle (in degrees).
  9539. * @param float $b end angle (in degrees).
  9540. * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
  9541. * @param float $cw: indicates whether to go clockwise (default: true).
  9542. * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
  9543. * @author Maxime Delorme, Nicola Asuni
  9544. * @since 3.1.000 (2008-06-09)
  9545. * @access public
  9546. */
  9547. public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
  9548. if ($this->rtl) {
  9549. $xc = $this->w - $xc;
  9550. }
  9551. if ($cw) {
  9552. $d = $b;
  9553. $b = $o - $a;
  9554. $a = $o - $d;
  9555. } else {
  9556. $b += $o;
  9557. $a += $o;
  9558. }
  9559. $a = ($a % 360) + 360;
  9560. $b = ($b % 360) + 360;
  9561. if ($a > $b) {
  9562. $b +=360;
  9563. }
  9564. $b = $b / 360 * 2 * M_PI;
  9565. $a = $a / 360 * 2 * M_PI;
  9566. $d = $b - $a;
  9567. if ($d == 0 ) {
  9568. $d = 2 * M_PI;
  9569. }
  9570. $k = $this->k;
  9571. $hp = $this->h;
  9572. if ($style=='F') {
  9573. $op = 'f';
  9574. } elseif ($style=='FD' or $style=='DF') {
  9575. $op = 'b';
  9576. } else {
  9577. $op = 's';
  9578. }
  9579. if (sin($d/2)) {
  9580. $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
  9581. }
  9582. //first put the center
  9583. $this->_out(sprintf('%.2F %.2F m', ($xc)*$k, ($hp-$yc)*$k));
  9584. //put the first point
  9585. $this->_out(sprintf('%.2F %.2F l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
  9586. //draw the arc
  9587. if ($d < (M_PI/2)) {
  9588. $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
  9589. } else {
  9590. $b = $a + $d/4;
  9591. $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
  9592. $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
  9593. $a = $b;
  9594. $b = $a + $d/4;
  9595. $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
  9596. $a = $b;
  9597. $b = $a + $d/4;
  9598. $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b) );
  9599. $a = $b;
  9600. $b = $a + $d/4;
  9601. $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
  9602. }
  9603. //terminate drawing
  9604. $this->_out($op);
  9605. }
  9606. /**
  9607. * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
  9608. * Only vector drawing is supported, not text or bitmap.
  9609. * 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).
  9610. * @param string $file Name of the file containing the image.
  9611. * @param float $x Abscissa of the upper-left corner.
  9612. * @param float $y Ordinate of the upper-left corner.
  9613. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  9614. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  9615. * @param mixed $link URL or identifier returned by AddLink().
  9616. * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
  9617. * @param string $align 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>
  9618. * @param string $palign 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>
  9619. * @param mixed $border Indicates if borders must be drawn around the image. The value can be either 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>
  9620. * @author Valentin Schmidt, Nicola Asuni
  9621. * @since 3.1.000 (2008-06-09)
  9622. * @access public
  9623. */
  9624. public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0) {
  9625. if ($x === '') {
  9626. $x = $this->x;
  9627. }
  9628. if ($y === '') {
  9629. $y = $this->y;
  9630. }
  9631. $k = $this->k;
  9632. $data = file_get_contents($file);
  9633. if ($data === false) {
  9634. $this->Error('EPS file not found: '.$file);
  9635. }
  9636. $regs = array();
  9637. // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
  9638. preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
  9639. if (count($regs) > 1) {
  9640. $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
  9641. if (strpos($version_str, 'Adobe Illustrator') !== false) {
  9642. $versexp = explode(' ', $version_str);
  9643. $version = (float)array_pop($versexp);
  9644. if ($version >= 9) {
  9645. $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
  9646. }
  9647. }
  9648. }
  9649. // strip binary bytes in front of PS-header
  9650. $start = strpos($data, '%!PS-Adobe');
  9651. if ($start > 0) {
  9652. $data = substr($data, $start);
  9653. }
  9654. // find BoundingBox params
  9655. preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
  9656. if (count($regs) > 1) {
  9657. list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
  9658. } else {
  9659. $this->Error('No BoundingBox found in EPS file: '.$file);
  9660. }
  9661. $start = strpos($data, '%%EndSetup');
  9662. if ($start === false) {
  9663. $start = strpos($data, '%%EndProlog');
  9664. }
  9665. if ($start === false) {
  9666. $start = strpos($data, '%%BoundingBox');
  9667. }
  9668. $data = substr($data, $start);
  9669. $end = strpos($data, '%%PageTrailer');
  9670. if ($end===false) {
  9671. $end = strpos($data, 'showpage');
  9672. }
  9673. if ($end) {
  9674. $data = substr($data, 0, $end);
  9675. }
  9676. if ($w > 0) {
  9677. $scale_x = $w / (($x2 - $x1) / $k);
  9678. if ($h > 0) {
  9679. $scale_y = $h / (($y2 - $y1) / $k);
  9680. } else {
  9681. $scale_y = $scale_x;
  9682. $h = ($y2 - $y1) / $k * $scale_y;
  9683. }
  9684. } else {
  9685. if ($h > 0) {
  9686. $scale_y = $h / (($y2 - $y1) / $k);
  9687. $scale_x = $scale_y;
  9688. $w = ($x2-$x1) / $k * $scale_x;
  9689. } else {
  9690. $w = ($x2 - $x1) / $k;
  9691. $h = ($y2 - $y1) / $k;
  9692. }
  9693. }
  9694. // Check whether we need a new page first as this does not fit
  9695. if ($this->checkPageBreak($h, $y)) {
  9696. $y = $this->GetY() + $this->cMargin;
  9697. }
  9698. // set bottomcoordinates
  9699. $this->img_rb_y = $y + $h;
  9700. // set alignment
  9701. if ($this->rtl) {
  9702. if ($palign == 'L') {
  9703. $ximg = $this->lMargin;
  9704. // set right side coordinate
  9705. $this->img_rb_x = $ximg + $w;
  9706. } elseif ($palign == 'C') {
  9707. $ximg = ($this->w - $x - $w) / 2;
  9708. // set right side coordinate
  9709. $this->img_rb_x = $ximg + $w;
  9710. } else {
  9711. $ximg = $this->w - $x - $w;
  9712. // set left side coordinate
  9713. $this->img_rb_x = $ximg;
  9714. }
  9715. } else {
  9716. if ($palign == 'R') {
  9717. $ximg = $this->w - $this->rMargin - $w;
  9718. // set left side coordinate
  9719. $this->img_rb_x = $ximg;
  9720. } elseif ($palign == 'C') {
  9721. $ximg = ($this->w - $x - $w) / 2;
  9722. // set right side coordinate
  9723. $this->img_rb_x = $ximg + $w;
  9724. } else {
  9725. $ximg = $x;
  9726. // set right side coordinate
  9727. $this->img_rb_x = $ximg + $w;
  9728. }
  9729. }
  9730. if ($useBoundingBox) {
  9731. $dx = $ximg * $k - $x1;
  9732. $dy = $y * $k - $y1;
  9733. } else {
  9734. $dx = $ximg * $k;
  9735. $dy = $y * $k;
  9736. }
  9737. // save the current graphic state
  9738. $this->_out('q'.$this->epsmarker);
  9739. // translate
  9740. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
  9741. // scale
  9742. if (isset($scale_x)) {
  9743. $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
  9744. }
  9745. // handle pc/unix/mac line endings
  9746. preg_match('/[\r\n]+/s', $data, $regs);
  9747. $lines = explode($regs[0], $data);
  9748. $u=0;
  9749. $cnt = count($lines);
  9750. for ($i=0; $i < $cnt; ++$i) {
  9751. $line = $lines[$i];
  9752. if (($line == '') OR ($line{0} == '%')) {
  9753. continue;
  9754. }
  9755. $len = strlen($line);
  9756. $chunks = explode(' ', $line);
  9757. $cmd = array_pop($chunks);
  9758. // RGB
  9759. if (($cmd == 'Xa') OR ($cmd == 'XA')) {
  9760. $b = array_pop($chunks);
  9761. $g = array_pop($chunks);
  9762. $r = array_pop($chunks);
  9763. $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!
  9764. continue;
  9765. }
  9766. switch ($cmd) {
  9767. case 'm':
  9768. case 'l':
  9769. case 'v':
  9770. case 'y':
  9771. case 'c':
  9772. case 'k':
  9773. case 'K':
  9774. case 'g':
  9775. case 'G':
  9776. case 's':
  9777. case 'S':
  9778. case 'J':
  9779. case 'j':
  9780. case 'w':
  9781. case 'M':
  9782. case 'd':
  9783. case 'n':
  9784. case 'v': {
  9785. $this->_out($line);
  9786. break;
  9787. }
  9788. case 'x': {// custom fill color
  9789. list($c,$m,$y,$k) = $chunks;
  9790. $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' k');
  9791. break;
  9792. }
  9793. case 'X': { // custom stroke color
  9794. list($c,$m,$y,$k) = $chunks;
  9795. $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' K');
  9796. break;
  9797. }
  9798. case 'Y':
  9799. case 'N':
  9800. case 'V':
  9801. case 'L':
  9802. case 'C': {
  9803. $line{$len-1} = strtolower($cmd);
  9804. $this->_out($line);
  9805. break;
  9806. }
  9807. case 'b':
  9808. case 'B': {
  9809. $this->_out($cmd . '*');
  9810. break;
  9811. }
  9812. case 'f':
  9813. case 'F': {
  9814. if ($u > 0) {
  9815. $isU = false;
  9816. $max = min($i+5, $cnt);
  9817. for ($j=$i+1; $j < $max; ++$j)
  9818. $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
  9819. if ($isU) {
  9820. $this->_out('f*');
  9821. }
  9822. } else {
  9823. $this->_out('f*');
  9824. }
  9825. break;
  9826. }
  9827. case '*u': {
  9828. ++$u;
  9829. break;
  9830. }
  9831. case '*U': {
  9832. --$u;
  9833. break;
  9834. }
  9835. }
  9836. }
  9837. // restore previous graphic state
  9838. $this->_out($this->epsmarker.'Q');
  9839. if (!empty($border)) {
  9840. $bx = $x;
  9841. $by = $y;
  9842. $this->x = $x;
  9843. $this->y = $y;
  9844. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
  9845. $this->x = $bx;
  9846. $this->y = $by;
  9847. }
  9848. if ($link) {
  9849. $this->Link($ximg, $y, $w, $h, $link, 0);
  9850. }
  9851. // set pointer to align the successive text/objects
  9852. switch($align) {
  9853. case 'T':{
  9854. $this->y = $y;
  9855. $this->x = $this->img_rb_x;
  9856. break;
  9857. }
  9858. case 'M':{
  9859. $this->y = $y + round($h/2);
  9860. $this->x = $this->img_rb_x;
  9861. break;
  9862. }
  9863. case 'B':{
  9864. $this->y = $this->img_rb_y;
  9865. $this->x = $this->img_rb_x;
  9866. break;
  9867. }
  9868. case 'N':{
  9869. $this->SetY($this->img_rb_y);
  9870. break;
  9871. }
  9872. default:{
  9873. break;
  9874. }
  9875. }
  9876. $this->endlinex = $this->img_rb_x;
  9877. }
  9878. /**
  9879. * Set document barcode.
  9880. * @param string $bc barcode
  9881. * @access public
  9882. */
  9883. public function setBarcode($bc='') {
  9884. $this->barcode = $bc;
  9885. }
  9886. /**
  9887. * Get current barcode.
  9888. * @return string
  9889. * @access public
  9890. * @since 4.0.012 (2008-07-24)
  9891. */
  9892. public function getBarcode() {
  9893. return $this->barcode;
  9894. }
  9895. /**
  9896. * Print a Linear Barcode.
  9897. * @param string $code code to print
  9898. * @param string $type type of barcode.
  9899. * @param int $x x position in user units
  9900. * @param int $y y position in user units
  9901. * @param int $w width in user units
  9902. * @param int $h height in user units
  9903. * @param float $xres width of the smallest bar in user units
  9904. * @param array $style array of options:<ul><li>string $style['position'] barcode position inside the specified width: L = left (default for LTR); C = center; R = right (default for RTL); S = stretch</li><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li><li>boolean $style["text"] boolean if true prints text below the barcode</li><li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li><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></ul>
  9905. * @param string $align 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>
  9906. * @author Nicola Asuni
  9907. * @since 3.1.000 (2008-06-09)
  9908. * @access public
  9909. */
  9910. public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
  9911. if ($this->empty_string($code)) {
  9912. return;
  9913. }
  9914. require_once(dirname(__FILE__).'/barcodes.php');
  9915. // save current graphic settings
  9916. $gvars = $this->getGraphicVars();
  9917. // create new barcode object
  9918. $barcodeobj = new TCPDFBarcode($code, $type);
  9919. $arrcode = $barcodeobj->getBarcodeArray();
  9920. if ($arrcode === false) {
  9921. $this->Error('Error in 1D barcode string');
  9922. }
  9923. // set default values
  9924. if (!isset($style['position'])) {
  9925. if ($this->rtl) {
  9926. $style['position'] = 'R';
  9927. } else {
  9928. $style['position'] = 'L';
  9929. }
  9930. }
  9931. if (!isset($style['padding'])) {
  9932. $style['padding'] = 0;
  9933. }
  9934. if (!isset($style['fgcolor'])) {
  9935. $style['fgcolor'] = array(0,0,0); // default black
  9936. }
  9937. if (!isset($style['bgcolor'])) {
  9938. $style['bgcolor'] = false; // default transparent
  9939. }
  9940. if (!isset($style['border'])) {
  9941. $style['border'] = false;
  9942. }
  9943. if (!isset($style['text'])) {
  9944. $style['text'] = false;
  9945. $fontsize = 0;
  9946. }
  9947. if ($style['text'] AND isset($style['font'])) {
  9948. if (isset($style['fontsize'])) {
  9949. $fontsize = $style['fontsize'];
  9950. } else {
  9951. $fontsize = 0;
  9952. }
  9953. $this->SetFont($style['font'], '', $fontsize);
  9954. }
  9955. if (!isset($style['stretchtext'])) {
  9956. $style['stretchtext'] = 4;
  9957. }
  9958. // set foreground color
  9959. $this->SetDrawColorArray($style['fgcolor']);
  9960. $this->SetTextColorArray($style['fgcolor']);
  9961. if ($this->empty_string($w) OR ($w <= 0)) {
  9962. if ($this->rtl) {
  9963. $w = $this->x - $this->lMargin;
  9964. } else {
  9965. $w = $this->w - $this->rMargin - $this->x;
  9966. }
  9967. }
  9968. if ($this->empty_string($x)) {
  9969. $x = $this->GetX();
  9970. }
  9971. if ($this->rtl) {
  9972. $x = $this->w - $x;
  9973. }
  9974. if ($this->empty_string($y)) {
  9975. $y = $this->GetY();
  9976. }
  9977. if ($this->empty_string($xres)) {
  9978. $xres = 0.4;
  9979. }
  9980. $fbw = ($arrcode['maxw'] * $xres) + (2 * $style['padding']);
  9981. $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style['padding']);
  9982. if ($this->empty_string($h) OR ($h <= 0)) {
  9983. $h = 10 + $extraspace;
  9984. }
  9985. if ($this->checkPageBreak($h)) {
  9986. $y = $this->y;
  9987. }
  9988. // maximum bar heigth
  9989. $barh = $h - $extraspace;
  9990. switch ($style['position']) {
  9991. case 'L': { // left
  9992. if ($this->rtl) {
  9993. $xpos = $x - $w;
  9994. } else {
  9995. $xpos = $x;
  9996. }
  9997. break;
  9998. }
  9999. case 'C': { // center
  10000. $xdiff = (($w - $fbw) / 2);
  10001. if ($this->rtl) {
  10002. $xpos = $x - $w + $xdiff;
  10003. } else {
  10004. $xpos = $x + $xdiff;
  10005. }
  10006. break;
  10007. }
  10008. case 'R': { // right
  10009. if ($this->rtl) {
  10010. $xpos = $x - $fbw;
  10011. } else {
  10012. $xpos = $x + $w - $fbw;
  10013. }
  10014. break;
  10015. }
  10016. case 'S': { // stretch
  10017. $fbw = $w;
  10018. $xres = ($w - (2 * $style['padding'])) / $arrcode['maxw'];
  10019. if ($this->rtl) {
  10020. $xpos = $x - $w;
  10021. } else {
  10022. $xpos = $x;
  10023. }
  10024. break;
  10025. }
  10026. }
  10027. $xpos_rect = $xpos;
  10028. $xpos = $xpos_rect + $style['padding'];
  10029. $xpos_text = $xpos;
  10030. // barcode is always printed in LTR direction
  10031. $tempRTL = $this->rtl;
  10032. $this->rtl = false;
  10033. // print background color
  10034. if ($style['bgcolor']) {
  10035. $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style['bgcolor']);
  10036. } elseif ($style['border']) {
  10037. $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
  10038. }
  10039. // print bars
  10040. if ($arrcode !== false) {
  10041. foreach ($arrcode['bcode'] as $k => $v) {
  10042. $bw = ($v['w'] * $xres);
  10043. if ($v['t']) {
  10044. // draw a vertical bar
  10045. $ypos = $y + $style['padding'] + ($v['p'] * $barh / $arrcode['maxh']);
  10046. $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
  10047. }
  10048. $xpos += $bw;
  10049. }
  10050. }
  10051. // print text
  10052. if ($style['text']) {
  10053. // print text
  10054. $this->x = $xpos_text;
  10055. $this->y = $y + $style['padding'] + $barh;
  10056. $this->Cell(($arrcode['maxw'] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style['stretchtext']);
  10057. }
  10058. // restore original direction
  10059. $this->rtl = $tempRTL;
  10060. // restore previous settings
  10061. $this->setGraphicVars($gvars);
  10062. // set bottomcoordinates
  10063. $this->img_rb_y = $y + $h;
  10064. if ($this->rtl) {
  10065. // set left side coordinate
  10066. $this->img_rb_x = ($this->w - $x - $w);
  10067. } else {
  10068. // set right side coordinate
  10069. $this->img_rb_x = $x + $w;
  10070. }
  10071. // set pointer to align the successive text/objects
  10072. switch($align) {
  10073. case 'T':{
  10074. $this->y = $y;
  10075. $this->x = $this->img_rb_x;
  10076. break;
  10077. }
  10078. case 'M':{
  10079. $this->y = $y + round($h/2);
  10080. $this->x = $this->img_rb_x;
  10081. break;
  10082. }
  10083. case 'B':{
  10084. $this->y = $this->img_rb_y;
  10085. $this->x = $this->img_rb_x;
  10086. break;
  10087. }
  10088. case 'N':{
  10089. $this->SetY($this->img_rb_y);
  10090. break;
  10091. }
  10092. default:{
  10093. break;
  10094. }
  10095. }
  10096. }
  10097. /**
  10098. * This function is DEPRECATED, please use the new write1DBarcode() function.
  10099. * @param int $x x position in user units
  10100. * @param int $y y position in user units
  10101. * @param int $w width in user units
  10102. * @param int $h height position in user units
  10103. * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
  10104. * @param string $style barcode style
  10105. * @param string $font font for text
  10106. * @param int $xres x resolution
  10107. * @param string $code code to print
  10108. * @deprecated deprecated since version 3.1.000 (2008-06-10)
  10109. * @access public
  10110. * @see write1DBarcode()
  10111. */
  10112. public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
  10113. // convert old settings for the new write1DBarcode() function.
  10114. $xres = 1 / $xres;
  10115. $newstyle = array(
  10116. 'position' => 'L',
  10117. 'border' => false,
  10118. 'padding' => 0,
  10119. 'fgcolor' => array(0,0,0),
  10120. 'bgcolor' => false,
  10121. 'text' => true,
  10122. 'font' => $font,
  10123. 'fontsize' => 8,
  10124. 'stretchtext' => 4
  10125. );
  10126. if ($style & 1) {
  10127. $newstyle['border'] = true;
  10128. }
  10129. if ($style & 2) {
  10130. $newstyle['bgcolor'] = false;
  10131. }
  10132. if ($style & 4) {
  10133. $newstyle['position'] = 'C';
  10134. } elseif ($style & 8) {
  10135. $newstyle['position'] = 'L';
  10136. } elseif ($style & 16) {
  10137. $newstyle['position'] = 'R';
  10138. }
  10139. if ($style & 128) {
  10140. $newstyle['text'] = true;
  10141. }
  10142. if ($style & 256) {
  10143. $newstyle['stretchtext'] = 4;
  10144. }
  10145. $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
  10146. }
  10147. /**
  10148. * Print 2D Barcode.
  10149. * @param string $code code to print
  10150. * @param string $type type of barcode.
  10151. * @param int $x x position in user units
  10152. * @param int $y y position in user units
  10153. * @param int $w width in user units
  10154. * @param int $h height in user units
  10155. * @param array $style array of options:<ul><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li></ul>
  10156. * @param string $align 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>
  10157. * @author Nicola Asuni
  10158. * @since 4.5.037 (2009-04-07)
  10159. * @access public
  10160. */
  10161. public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='') {
  10162. if ($this->empty_string($code)) {
  10163. return;
  10164. }
  10165. require_once(dirname(__FILE__).'/2dbarcodes.php');
  10166. // save current graphic settings
  10167. $gvars = $this->getGraphicVars();
  10168. // create new barcode object
  10169. $barcodeobj = new TCPDF2DBarcode($code, $type);
  10170. $arrcode = $barcodeobj->getBarcodeArray();
  10171. if ($arrcode === false) {
  10172. $this->Error('Error in 2D barcode string');
  10173. }
  10174. // set default values
  10175. if (!isset($style['padding'])) {
  10176. $style['padding'] = 0;
  10177. }
  10178. if (!isset($style['fgcolor'])) {
  10179. $style['fgcolor'] = array(0,0,0); // default black
  10180. }
  10181. if (!isset($style['bgcolor'])) {
  10182. $style['bgcolor'] = false; // default transparent
  10183. }
  10184. if (!isset($style['border'])) {
  10185. $style['border'] = false;
  10186. }
  10187. // set foreground color
  10188. $this->SetDrawColorArray($style['fgcolor']);
  10189. if ($this->empty_string($x)) {
  10190. $x = $this->GetX();
  10191. }
  10192. if ($this->rtl) {
  10193. $x = $this->w - $x;
  10194. }
  10195. if ($this->empty_string($y)) {
  10196. $y = $this->GetY();
  10197. }
  10198. if ($this->empty_string($w) OR ($w <= 0)) {
  10199. if ($this->rtl) {
  10200. $w = $x - $this->lMargin;
  10201. } else {
  10202. $w = $this->w - $this->rMargin - $x;
  10203. }
  10204. }
  10205. if ($this->empty_string($h) OR ($h <= 0)) {
  10206. // 2d barcodes are square by default
  10207. $h = $w;
  10208. }
  10209. if ($this->checkPageBreak($h)) {
  10210. $y = $this->y;
  10211. }
  10212. // calculate barcode size (excluding padding)
  10213. $bw = $w - (2 * $style['padding']);
  10214. $bh = $h - (2 * $style['padding']);
  10215. // calculate starting coordinates
  10216. if ($this->rtl) {
  10217. $xpos = $x - $w;
  10218. } else {
  10219. $xpos = $x;
  10220. }
  10221. $xpos += $style['padding'];
  10222. $ypos = $y + $style['padding'];
  10223. // barcode is always printed in LTR direction
  10224. $tempRTL = $this->rtl;
  10225. $this->rtl = false;
  10226. // print background color
  10227. if ($style['bgcolor']) {
  10228. $this->Rect($x, $y, $w, $h, 'DF', '', $style['bgcolor']);
  10229. } elseif ($style['border']) {
  10230. $this->Rect($x, $y, $w, $h, 'D');
  10231. }
  10232. // print barcode cells
  10233. if ($arrcode !== false) {
  10234. $rows = $arrcode['num_rows'];
  10235. $cols = $arrcode['num_cols'];
  10236. // calculate dimension of single barcode cell
  10237. $cw = $bw / $cols;
  10238. $ch = $bh / $rows;
  10239. // for each row
  10240. for ($r = 0; $r < $rows; ++$r) {
  10241. $xr = $xpos;
  10242. // for each column
  10243. for ($c = 0; $c < $cols; ++$c) {
  10244. if ($arrcode['bcode'][$r][$c] == 1) {
  10245. // draw a single barcode cell
  10246. $this->Rect($xr, $ypos, $cw, $ch, 'F', array(), $style['fgcolor']);
  10247. }
  10248. $xr += $cw;
  10249. }
  10250. $ypos += $ch;
  10251. }
  10252. }
  10253. // restore original direction
  10254. $this->rtl = $tempRTL;
  10255. // restore previous settings
  10256. $this->setGraphicVars($gvars);
  10257. // set bottomcoordinates
  10258. $this->img_rb_y = $y + $h;
  10259. if ($this->rtl) {
  10260. // set left side coordinate
  10261. $this->img_rb_x = ($this->w - $x - $w);
  10262. } else {
  10263. // set right side coordinate
  10264. $this->img_rb_x = $x + $w;
  10265. }
  10266. // set pointer to align the successive text/objects
  10267. switch($align) {
  10268. case 'T':{
  10269. $this->y = $y;
  10270. $this->x = $this->img_rb_x;
  10271. break;
  10272. }
  10273. case 'M':{
  10274. $this->y = $y + round($h/2);
  10275. $this->x = $this->img_rb_x;
  10276. break;
  10277. }
  10278. case 'B':{
  10279. $this->y = $this->img_rb_y;
  10280. $this->x = $this->img_rb_x;
  10281. break;
  10282. }
  10283. case 'N':{
  10284. $this->SetY($this->img_rb_y);
  10285. break;
  10286. }
  10287. default:{
  10288. break;
  10289. }
  10290. }
  10291. }
  10292. /**
  10293. * Returns an array containing current margins:
  10294. * <ul>
  10295. <li>$ret['left'] = left margin</li>
  10296. <li>$ret['right'] = right margin</li>
  10297. <li>$ret['top'] = top margin</li>
  10298. <li>$ret['bottom'] = bottom margin</li>
  10299. <li>$ret['header'] = header margin</li>
  10300. <li>$ret['footer'] = footer margin</li>
  10301. <li>$ret['cell'] = cell margin</li>
  10302. * </ul>
  10303. * @return array containing all margins measures
  10304. * @access public
  10305. * @since 3.2.000 (2008-06-23)
  10306. */
  10307. public function getMargins() {
  10308. $ret = array(
  10309. 'left' => $this->lMargin,
  10310. 'right' => $this->rMargin,
  10311. 'top' => $this->tMargin,
  10312. 'bottom' => $this->bMargin,
  10313. 'header' => $this->header_margin,
  10314. 'footer' => $this->footer_margin,
  10315. 'cell' => $this->cMargin,
  10316. );
  10317. return $ret;
  10318. }
  10319. /**
  10320. * Returns an array containing original margins:
  10321. * <ul>
  10322. <li>$ret['left'] = left margin</li>
  10323. <li>$ret['right'] = right margin</li>
  10324. * </ul>
  10325. * @return array containing all margins measures
  10326. * @access public
  10327. * @since 4.0.012 (2008-07-24)
  10328. */
  10329. public function getOriginalMargins() {
  10330. $ret = array(
  10331. 'left' => $this->original_lMargin,
  10332. 'right' => $this->original_rMargin
  10333. );
  10334. return $ret;
  10335. }
  10336. /**
  10337. * Returns the current font size.
  10338. * @return current font size
  10339. * @access public
  10340. * @since 3.2.000 (2008-06-23)
  10341. */
  10342. public function getFontSize() {
  10343. return $this->FontSize;
  10344. }
  10345. /**
  10346. * Returns the current font size in points unit.
  10347. * @return current font size in points unit
  10348. * @access public
  10349. * @since 3.2.000 (2008-06-23)
  10350. */
  10351. public function getFontSizePt() {
  10352. return $this->FontSizePt;
  10353. }
  10354. /**
  10355. * Returns the current font family name.
  10356. * @return string current font family name
  10357. * @access public
  10358. * @since 4.3.008 (2008-12-05)
  10359. */
  10360. public function getFontFamily() {
  10361. return $this->FontFamily;
  10362. }
  10363. /**
  10364. * Returns the current font style.
  10365. * @return string current font style
  10366. * @access public
  10367. * @since 4.3.008 (2008-12-05)
  10368. */
  10369. public function getFontStyle() {
  10370. return $this->FontStyle;
  10371. }
  10372. /**
  10373. * Prints a cell (rectangular area) with optional borders, background color and html text string.
  10374. * 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 />
  10375. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  10376. * @param float $w Cell width. If 0, the cell extends up to the right margin.
  10377. * @param float $h Cell minimum height. The cell extends automatically if needed.
  10378. * @param float $x upper-left corner X coordinate
  10379. * @param float $y upper-left corner Y coordinate
  10380. * @param string $html html text to print. Default value: empty string.
  10381. * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either 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>
  10382. * @param int $ln 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>
  10383. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  10384. * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  10385. * @param boolean $reseth if true reset the last cell height (default true).
  10386. * @param string $align 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>
  10387. * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
  10388. * @access public
  10389. * @uses MultiCell()
  10390. * @see Multicell(), writeHTML()
  10391. */
  10392. public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true) {
  10393. return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0);
  10394. }
  10395. /**
  10396. * Returns the HTML DOM array.
  10397. * <ul><li>$dom[$key]['tag'] = true if tag, false otherwise;</li><li>$dom[$key]['value'] = tag name or text;</li><li>$dom[$key]['opening'] = true if opening tag, false otherwise;</li><li>$dom[$key]['attribute'] = array of attributes (attribute name is the key);</li><li>$dom[$key]['style'] = array of style attributes (attribute name is the key);</li><li>$dom[$key]['parent'] = id of parent element;</li><li>$dom[$key]['fontname'] = font family name;</li><li>$dom[$key]['fontstyle'] = font style;</li><li>$dom[$key]['fontsize'] = font size in points;</li><li>$dom[$key]['bgcolor'] = RGB array of background color;</li><li>$dom[$key]['fgcolor'] = RGB array of foreground color;</li><li>$dom[$key]['width'] = width in pixels;</li><li>$dom[$key]['height'] = height in pixels;</li><li>$dom[$key]['align'] = text alignment;</li><li>$dom[$key]['cols'] = number of colums in table;</li><li>$dom[$key]['rows'] = number of rows in table;</li></ul>
  10398. * @param string $html html code
  10399. * @return array
  10400. * @access protected
  10401. * @since 3.2.000 (2008-06-20)
  10402. */
  10403. protected function getHtmlDomArray($html) {
  10404. // remove all unsupported tags (the line below lists all supported tags)
  10405. $html = strip_tags($html, '<marker/><a><b><blockquote><br><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>');
  10406. //replace some blank characters
  10407. $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
  10408. $html = preg_replace('/<(table|tr|td|th|tcpdf|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|br|hr|li|ol|ul|p)([^\>]*)>[\n\r\t]+/', '<\\1\\2>', $html);
  10409. $html = preg_replace('@(\r\n|\r)@', "\n", $html);
  10410. $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
  10411. $html = strtr($html, $repTable);
  10412. while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html)) {
  10413. // preserve newlines on <pre> tag
  10414. $html = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html);
  10415. }
  10416. $html = str_replace("\n", ' ', $html);
  10417. // remove extra spaces from code
  10418. $html = preg_replace('/[\s]+<\/(table|tr|td|th|ul|ol|li)>/', '</\\1>', $html);
  10419. $html = preg_replace('/[\s]+<(tr|td|th|ul|ol|li|br)/', '<\\1', $html);
  10420. $html = preg_replace('/<\/(table|tr|td|th|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|ul|p)>[\s]+</', '</\\1><', $html);
  10421. $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
  10422. $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
  10423. $html = preg_replace('/<img/', ' <img', $html);
  10424. $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span></span>', $html);
  10425. $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
  10426. // trim string
  10427. $html = preg_replace('/^[\s]+/', '', $html);
  10428. $html = preg_replace('/[\s]+$/', '', $html);
  10429. // pattern for generic tag
  10430. $tagpattern = '/(<[^>]+>)/';
  10431. // explodes the string
  10432. $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  10433. // count elements
  10434. $maxel = count($a);
  10435. $elkey = 0;
  10436. $key = 0;
  10437. // create an array of elements
  10438. $dom = array();
  10439. $dom[$key] = array();
  10440. // set first void element
  10441. $dom[$key]['tag'] = false;
  10442. $dom[$key]['value'] = '';
  10443. $dom[$key]['parent'] = 0;
  10444. $dom[$key]['fontname'] = $this->FontFamily;
  10445. $dom[$key]['fontstyle'] = $this->FontStyle;
  10446. $dom[$key]['fontsize'] = $this->FontSizePt;
  10447. $dom[$key]['bgcolor'] = false;
  10448. $dom[$key]['fgcolor'] = $this->fgcolor;
  10449. $dom[$key]['align'] = '';
  10450. $dom[$key]['listtype'] = '';
  10451. $thead = false; // true when we are inside the THEAD tag
  10452. ++$key;
  10453. $level = array();
  10454. array_push($level, 0); // root
  10455. while ($elkey < $maxel) {
  10456. $dom[$key] = array();
  10457. $element = $a[$elkey];
  10458. $dom[$key]['elkey'] = $elkey;
  10459. if (preg_match($tagpattern, $element)) {
  10460. // html tag
  10461. $element = substr($element, 1, -1);
  10462. // get tag name
  10463. preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
  10464. $tagname = strtolower($tag[1]);
  10465. // check if we are inside a table header
  10466. if ($tagname == 'thead') {
  10467. if ($element{0} == '/') {
  10468. $thead = false;
  10469. } else {
  10470. $thead = true;
  10471. }
  10472. ++$elkey;
  10473. continue;
  10474. }
  10475. $dom[$key]['tag'] = true;
  10476. $dom[$key]['value'] = $tagname;
  10477. if ($element{0} == '/') {
  10478. // closing html tag
  10479. $dom[$key]['opening'] = false;
  10480. $dom[$key]['parent'] = end($level);
  10481. array_pop($level);
  10482. $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
  10483. $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
  10484. $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
  10485. $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
  10486. $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
  10487. $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
  10488. if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
  10489. $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
  10490. }
  10491. // set the number of columns in table tag
  10492. if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
  10493. $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
  10494. }
  10495. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  10496. $dom[($dom[$key]['parent'])]['content'] = '';
  10497. for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
  10498. $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
  10499. }
  10500. $key = $i;
  10501. }
  10502. // store header rows on a new table
  10503. if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] == true)) {
  10504. if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
  10505. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
  10506. }
  10507. for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
  10508. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
  10509. }
  10510. }
  10511. if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
  10512. $dom[($dom[$key]['parent'])]['thead'] .= '</table>';
  10513. }
  10514. } else {
  10515. // opening html tag
  10516. $dom[$key]['opening'] = true;
  10517. $dom[$key]['parent'] = end($level);
  10518. if (substr($element, -1, 1) != '/') {
  10519. // not self-closing tag
  10520. array_push($level, $key);
  10521. $dom[$key]['self'] = false;
  10522. } else {
  10523. $dom[$key]['self'] = true;
  10524. }
  10525. // copy some values from parent
  10526. $parentkey = 0;
  10527. if ($key > 0) {
  10528. $parentkey = $dom[$key]['parent'];
  10529. $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
  10530. $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
  10531. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
  10532. $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
  10533. $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
  10534. $dom[$key]['align'] = $dom[$parentkey]['align'];
  10535. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  10536. }
  10537. // get attributes
  10538. preg_match_all('/([^=\s]*)=["]?([^"]*)["]?/', $element, $attr_array, PREG_PATTERN_ORDER);
  10539. $dom[$key]['attribute'] = array(); // reset attribute array
  10540. while (list($id, $name) = each($attr_array[1])) {
  10541. $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
  10542. }
  10543. // split style attributes
  10544. if (isset($dom[$key]['attribute']['style'])) {
  10545. // get style attributes
  10546. preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  10547. $dom[$key]['style'] = array(); // reset style attribute array
  10548. while (list($id, $name) = each($style_array[1])) {
  10549. $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
  10550. }
  10551. // --- get some style attributes ---
  10552. if (isset($dom[$key]['style']['font-family'])) {
  10553. // font family
  10554. if (isset($dom[$key]['style']['font-family'])) {
  10555. $fontslist = explode(',', strtolower($dom[$key]['style']['font-family']));
  10556. foreach ($fontslist as $font) {
  10557. $font = trim(strtolower($font));
  10558. if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
  10559. $dom[$key]['fontname'] = $font;
  10560. break;
  10561. }
  10562. }
  10563. }
  10564. }
  10565. // list-style-type
  10566. if (isset($dom[$key]['style']['list-style-type'])) {
  10567. $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
  10568. if ($dom[$key]['listtype'] == 'inherit') {
  10569. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  10570. }
  10571. }
  10572. // font size
  10573. if (isset($dom[$key]['style']['font-size'])) {
  10574. $fsize = trim($dom[$key]['style']['font-size']);
  10575. switch ($fsize) {
  10576. // absolute-size
  10577. case 'xx-small': {
  10578. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
  10579. break;
  10580. }
  10581. case 'x-small': {
  10582. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
  10583. break;
  10584. }
  10585. case 'small': {
  10586. $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
  10587. break;
  10588. }
  10589. case 'medium': {
  10590. $dom[$key]['fontsize'] = $dom[0]['fontsize'];
  10591. break;
  10592. }
  10593. case 'large': {
  10594. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
  10595. break;
  10596. }
  10597. case 'x-large': {
  10598. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
  10599. break;
  10600. }
  10601. case 'xx-large': {
  10602. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
  10603. break;
  10604. }
  10605. // relative-size
  10606. case 'smaller': {
  10607. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
  10608. break;
  10609. }
  10610. case 'larger': {
  10611. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
  10612. break;
  10613. }
  10614. default: {
  10615. $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
  10616. }
  10617. }
  10618. }
  10619. // font style
  10620. if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == 'b')) {
  10621. $dom[$key]['fontstyle'] .= 'B';
  10622. }
  10623. if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
  10624. $dom[$key]['fontstyle'] .= '"I';
  10625. }
  10626. // font color
  10627. if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
  10628. $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
  10629. }
  10630. // background color
  10631. if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
  10632. $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
  10633. }
  10634. // text-decoration
  10635. if (isset($dom[$key]['style']['text-decoration'])) {
  10636. $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
  10637. foreach ($decors as $dec) {
  10638. $dec = trim($dec);
  10639. if (!$this->empty_string($dec)) {
  10640. if ($dec{0} == 'u') {
  10641. $dom[$key]['fontstyle'] .= 'U';
  10642. } elseif ($dec{0} == 'l') {
  10643. $dom[$key]['fontstyle'] .= 'D';
  10644. }
  10645. }
  10646. }
  10647. }
  10648. // check for width attribute
  10649. if (isset($dom[$key]['style']['width'])) {
  10650. $dom[$key]['width'] = $dom[$key]['style']['width'];
  10651. }
  10652. // check for height attribute
  10653. if (isset($dom[$key]['style']['height'])) {
  10654. $dom[$key]['height'] = $dom[$key]['style']['height'];
  10655. }
  10656. // check for text alignment
  10657. if (isset($dom[$key]['style']['text-align'])) {
  10658. $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
  10659. }
  10660. // check for border attribute
  10661. if (isset($dom[$key]['style']['border'])) {
  10662. $dom[$key]['attribute']['border'] = $dom[$key]['style']['border'];
  10663. }
  10664. }
  10665. // check for font tag
  10666. if ($dom[$key]['value'] == 'font') {
  10667. // font family
  10668. if (isset($dom[$key]['attribute']['face'])) {
  10669. $fontslist = explode(',', strtolower($dom[$key]['attribute']['face']));
  10670. foreach ($fontslist as $font) {
  10671. $font = trim(strtolower($font));
  10672. if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
  10673. $dom[$key]['fontname'] = $font;
  10674. break;
  10675. }
  10676. }
  10677. }
  10678. // font size
  10679. if (isset($dom[$key]['attribute']['size'])) {
  10680. if ($key > 0) {
  10681. if ($dom[$key]['attribute']['size']{0} == '+') {
  10682. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
  10683. } elseif ($dom[$key]['attribute']['size']{0} == '-') {
  10684. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
  10685. } else {
  10686. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  10687. }
  10688. } else {
  10689. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  10690. }
  10691. }
  10692. }
  10693. // force natural alignment for lists
  10694. if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
  10695. AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
  10696. if ($this->rtl) {
  10697. $dom[$key]['align'] = 'R';
  10698. } else {
  10699. $dom[$key]['align'] = 'L';
  10700. }
  10701. }
  10702. if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
  10703. $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
  10704. }
  10705. if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
  10706. $dom[$key]['fontstyle'] .= 'B';
  10707. }
  10708. if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
  10709. $dom[$key]['fontstyle'] .= 'I';
  10710. }
  10711. if ($dom[$key]['value'] == 'u') {
  10712. $dom[$key]['fontstyle'] .= 'U';
  10713. }
  10714. if ($dom[$key]['value'] == 'del') {
  10715. $dom[$key]['fontstyle'] .= 'D';
  10716. }
  10717. if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
  10718. $dom[$key]['fontname'] = $this->default_monospaced_font;
  10719. }
  10720. if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
  10721. $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
  10722. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
  10723. $dom[$key]['fontstyle'] .= 'B';
  10724. }
  10725. if (($dom[$key]['value'] == 'table')) {
  10726. $dom[$key]['rows'] = 0; // number of rows
  10727. $dom[$key]['trids'] = array(); // IDs of TR elements
  10728. $dom[$key]['thead'] = ''; // table header rows
  10729. }
  10730. if (($dom[$key]['value'] == 'tr')) {
  10731. $dom[$key]['cols'] = 0;
  10732. // store the number of rows on table element
  10733. ++$dom[($dom[$key]['parent'])]['rows'];
  10734. // store the TR elements IDs on table element
  10735. array_push($dom[($dom[$key]['parent'])]['trids'], $key);
  10736. if ($thead) {
  10737. $dom[$key]['thead'] = true;
  10738. } else {
  10739. $dom[$key]['thead'] = false;
  10740. }
  10741. }
  10742. if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
  10743. if (isset($dom[$key]['attribute']['colspan'])) {
  10744. $colspan = intval($dom[$key]['attribute']['colspan']);
  10745. } else {
  10746. $colspan = 1;
  10747. }
  10748. $dom[$key]['attribute']['colspan'] = $colspan;
  10749. $dom[($dom[$key]['parent'])]['cols'] += $colspan;
  10750. }
  10751. // set foreground color attribute
  10752. if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
  10753. $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
  10754. }
  10755. // set background color attribute
  10756. if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
  10757. $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
  10758. }
  10759. // check for width attribute
  10760. if (isset($dom[$key]['attribute']['width'])) {
  10761. $dom[$key]['width'] = $dom[$key]['attribute']['width'];
  10762. }
  10763. // check for height attribute
  10764. if (isset($dom[$key]['attribute']['height'])) {
  10765. $dom[$key]['height'] = $dom[$key]['attribute']['height'];
  10766. }
  10767. // check for text alignment
  10768. if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
  10769. $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
  10770. }
  10771. } // end opening tag
  10772. } else {
  10773. // text
  10774. $dom[$key]['tag'] = false;
  10775. $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
  10776. $dom[$key]['parent'] = end($level);
  10777. }
  10778. ++$elkey;
  10779. ++$key;
  10780. }
  10781. return $dom;
  10782. }
  10783. /**
  10784. * Allows to preserve some HTML formatting (limited support).<br />
  10785. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  10786. * 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
  10787. * @param string $html text to display
  10788. * @param boolean $ln if true add a new line after text (default = true)
  10789. * @param int $fill Indicates if the background must be painted (true) or transparent (false).
  10790. * @param boolean $reseth if true reset the last cell height (default false).
  10791. * @param boolean $cell if true add the default cMargin space to each Write (default false).
  10792. * @param string $align 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>
  10793. * @access public
  10794. */
  10795. public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
  10796. $gvars = $this->getGraphicVars();
  10797. // store current values
  10798. $prevPage = $this->page;
  10799. $prevlMargin = $this->lMargin;
  10800. $prevrMargin = $this->rMargin;
  10801. $curfontname = $this->FontFamily;
  10802. $curfontstyle = $this->FontStyle;
  10803. $curfontsize = $this->FontSizePt;
  10804. $this->newline = true;
  10805. $minstartliney = $this->y;
  10806. $yshift = 0;
  10807. $startlinepage = $this->page;
  10808. $newline = true;
  10809. $loop = 0;
  10810. $curpos = 0;
  10811. $blocktags = array('blockquote','br','dd','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','ul','tcpdf');
  10812. $this->premode = false;
  10813. if (isset($this->PageAnnots[$this->page])) {
  10814. $pask = count($this->PageAnnots[$this->page]);
  10815. } else {
  10816. $pask = 0;
  10817. }
  10818. if (isset($this->footerlen[$this->page])) {
  10819. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  10820. } else {
  10821. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  10822. }
  10823. $startlinepos = $this->footerpos[$this->page];
  10824. $lalign = $align;
  10825. $plalign = $align;
  10826. if ($this->rtl) {
  10827. $w = $this->x - $this->lMargin;
  10828. } else {
  10829. $w = $this->w - $this->rMargin - $this->x;
  10830. }
  10831. $w -= (2 * $this->cMargin);
  10832. if ($cell) {
  10833. if ($this->rtl) {
  10834. $this->x -= $this->cMargin;
  10835. } else {
  10836. $this->x += $this->cMargin;
  10837. }
  10838. }
  10839. if ($this->customlistindent >= 0) {
  10840. $this->listindent = $this->customlistindent;
  10841. } else {
  10842. $this->listindent = $this->GetStringWidth('0000');
  10843. }
  10844. $this->listnum = 0;
  10845. if (($this->empty_string($this->lasth)) OR ($reseth)) {
  10846. //set row height
  10847. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  10848. }
  10849. $dom = $this->getHtmlDomArray($html);
  10850. $maxel = count($dom);
  10851. $key = 0;
  10852. while ($key < $maxel) {
  10853. if ($dom[$key]['tag'] OR ($key == 0)) {
  10854. if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
  10855. $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
  10856. }
  10857. // vertically align image in line
  10858. if ((!$this->newline)
  10859. AND ($dom[$key]['value'] == 'img')
  10860. AND (isset($dom[$key]['attribute']['height']))
  10861. AND ($dom[$key]['attribute']['height'] > 0)) {
  10862. // get image height
  10863. $imgh = $this->getHTMLUnitToUnits($dom[$key]['attribute']['height'], $this->lasth, 'px');
  10864. if (!$this->InFooter) {
  10865. // check for page break
  10866. $this->checkPageBreak($imgh);
  10867. }
  10868. if ($this->page > $startlinepage) {
  10869. // fix lines splitted over two pages
  10870. if (isset($this->footerlen[$startlinepage])) {
  10871. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  10872. }
  10873. // line to be moved one page forward
  10874. $pagebuff = $this->getPageBuffer($startlinepage);
  10875. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  10876. $tstart = substr($pagebuff, 0, $startlinepos);
  10877. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  10878. // remove line start from previous page
  10879. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  10880. $pagebuff = $this->getPageBuffer($this->page);
  10881. $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
  10882. $tend = substr($pagebuff, $this->intmrk[$this->page]);
  10883. // add line start to current page
  10884. $yshift = $minstartliney - $this->y;
  10885. $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
  10886. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  10887. // shift the annotations and links
  10888. if (isset($this->PageAnnots[$startlinepage])) {
  10889. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  10890. if ($pak >= $pask) {
  10891. $this->PageAnnots[$this->page][] = $pac;
  10892. unset($this->PageAnnots[$startlinepage][$pak]);
  10893. $npak = count($this->PageAnnots[$this->page]) - 1;
  10894. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  10895. }
  10896. }
  10897. }
  10898. $startlinepos = $this->intmrk[$this->page];
  10899. $startlinepage = $this->page;
  10900. $startliney = $this->y;
  10901. }
  10902. $this->y += (($curfontsize / $this->k) - $imgh);
  10903. $minstartliney = min($this->y, $minstartliney);
  10904. } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
  10905. // account for different font size
  10906. $pfontname = $curfontname;
  10907. $pfontstyle = $curfontstyle;
  10908. $pfontsize = $curfontsize;
  10909. $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
  10910. $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
  10911. $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
  10912. if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
  10913. $this->SetFont($fontname, $fontstyle, $fontsize);
  10914. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  10915. if (is_numeric($fontsize) AND ($fontsize > 0)
  10916. AND is_numeric($curfontsize) AND ($curfontsize > 0)
  10917. AND ($fontsize != $curfontsize) AND (!$this->newline)
  10918. AND ($key < ($maxel - 1))
  10919. ) {
  10920. if ((!$this->newline) AND ($this->page > $startlinepage)) {
  10921. // fix lines splitted over two pages
  10922. if (isset($this->footerlen[$startlinepage])) {
  10923. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  10924. }
  10925. // line to be moved one page forward
  10926. $pagebuff = $this->getPageBuffer($startlinepage);
  10927. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  10928. $tstart = substr($pagebuff, 0, $startlinepos);
  10929. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  10930. // remove line start from previous page
  10931. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  10932. $pagebuff = $this->getPageBuffer($this->page);
  10933. $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
  10934. $tend = substr($pagebuff, $this->intmrk[$this->page]);
  10935. // add line start to current page
  10936. $yshift = $minstartliney - $this->y;
  10937. $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
  10938. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  10939. // shift the annotations and links
  10940. if (isset($this->PageAnnots[$startlinepage])) {
  10941. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  10942. if ($pak >= $pask) {
  10943. $this->PageAnnots[$this->page][] = $pac;
  10944. unset($this->PageAnnots[$startlinepage][$pak]);
  10945. $npak = count($this->PageAnnots[$this->page]) - 1;
  10946. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  10947. }
  10948. }
  10949. }
  10950. }
  10951. $this->y += (($curfontsize - $fontsize) / $this->k);
  10952. $minstartliney = min($this->y, $minstartliney);
  10953. }
  10954. $curfontname = $fontname;
  10955. $curfontstyle = $fontstyle;
  10956. $curfontsize = $fontsize;
  10957. }
  10958. }
  10959. if (($plalign == 'J') AND (in_array($dom[$key]['value'], $blocktags))) {
  10960. $plalign = '';
  10961. }
  10962. // get current position on page buffer
  10963. $curpos = $this->pagelen[$startlinepage];
  10964. if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
  10965. $this->SetFillColorArray($dom[$key]['bgcolor']);
  10966. $wfill = true;
  10967. } else {
  10968. $wfill = $fill | false;
  10969. }
  10970. if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
  10971. $this->SetTextColorArray($dom[$key]['fgcolor']);
  10972. }
  10973. if (isset($dom[$key]['align'])) {
  10974. $lalign = $dom[$key]['align'];
  10975. }
  10976. if ($this->empty_string($lalign)) {
  10977. $lalign = $align;
  10978. }
  10979. }
  10980. // align lines
  10981. if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
  10982. $newline = true;
  10983. // we are at the beginning of a new line
  10984. if (isset($startlinex)) {
  10985. $yshift = $minstartliney - $startliney;
  10986. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  10987. $yshift = 0;
  10988. }
  10989. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
  10990. // the last line must be shifted to be aligned as requested
  10991. $linew = abs($this->endlinex - $startlinex);
  10992. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  10993. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  10994. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  10995. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  10996. } elseif (isset($opentagpos)) {
  10997. $midpos = $opentagpos;
  10998. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  10999. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  11000. $midpos = $this->footerpos[$startlinepage];
  11001. } else {
  11002. $midpos = 0;
  11003. }
  11004. if ($midpos > 0) {
  11005. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  11006. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  11007. } else {
  11008. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  11009. $pend = '';
  11010. }
  11011. // calculate shifting amount
  11012. $tw = $w;
  11013. if ($this->lMargin != $prevlMargin) {
  11014. $tw += ($prevlMargin - $this->lMargin);
  11015. }
  11016. if ($this->rMargin != $prevrMargin) {
  11017. $tw += ($prevrMargin - $this->rMargin);
  11018. }
  11019. $mdiff = abs($tw - $linew);
  11020. $t_x = 0;
  11021. if ($plalign == 'C') {
  11022. if ($this->rtl) {
  11023. $t_x = -($mdiff / 2);
  11024. } else {
  11025. $t_x = ($mdiff / 2);
  11026. }
  11027. } elseif (($plalign == 'R') AND (!$this->rtl)) {
  11028. // right alignment on LTR document
  11029. $t_x = $mdiff;
  11030. } elseif (($plalign == 'L') AND ($this->rtl)) {
  11031. // left alignment on RTL document
  11032. $t_x = -$mdiff;
  11033. } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
  11034. // Justification
  11035. if ($this->rtl OR $this->tmprtl) {
  11036. $t_x = $this->lMargin - $this->endlinex;
  11037. }
  11038. $no = 0;
  11039. $ns = 0;
  11040. $pmidtemp = $pmid;
  11041. // escape special characters
  11042. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  11043. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  11044. // search spaces
  11045. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
  11046. $maxkk = count($lnstring[1]) - 1;
  11047. for ($kk=0; $kk <= $maxkk; ++$kk) {
  11048. // restore special characters
  11049. $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
  11050. $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
  11051. if ($kk == $maxkk) {
  11052. if ($this->rtl OR $this->tmprtl) {
  11053. $tvalue = ltrim($lnstring[1][$kk]);
  11054. } else {
  11055. $tvalue = rtrim($lnstring[1][$kk]);
  11056. }
  11057. } else {
  11058. $tvalue = $lnstring[1][$kk];
  11059. }
  11060. // count spaces on line
  11061. $no += substr_count($lnstring[1][$kk], chr(32));
  11062. $ns += substr_count($tvalue, chr(32));
  11063. }
  11064. if ($this->rtl OR $this->tmprtl) {
  11065. $t_x = $this->lMargin - $this->endlinex - (($no - $ns - 1) * $this->GetStringWidth(chr(32)));
  11066. }
  11067. // calculate additional space to add to each space
  11068. $spacewidth = (($tw - $linew + (($no - $ns) * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1)) * $this->k;
  11069. $spacewidthu = ($tw - $linew + ($no * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1) / $this->FontSize / $this->k;
  11070. $nsmax = $ns;
  11071. $ns = 0;
  11072. reset($lnstring);
  11073. $offset = 0;
  11074. $strcount = 0;
  11075. $prev_epsposbeg = 0;
  11076. global $spacew;
  11077. while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
  11078. if ($this->rtl OR $this->tmprtl) {
  11079. $spacew = ($spacewidth * ($nsmax - $ns));
  11080. } else {
  11081. $spacew = ($spacewidth * $ns);
  11082. }
  11083. $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
  11084. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
  11085. $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
  11086. if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
  11087. OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
  11088. // shift EPS images
  11089. $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
  11090. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
  11091. $pmid_b = substr($pmid, 0, $epsposbeg);
  11092. $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
  11093. $pmid_e = substr($pmid, $epsposend);
  11094. $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
  11095. $offset = $epsposend;
  11096. continue;
  11097. }
  11098. $prev_epsposbeg = $epsposbeg;
  11099. $currentxpos = 0;
  11100. // shift blocks of code
  11101. switch ($strpiece[2][0]) {
  11102. case 'Td':
  11103. case 'cm':
  11104. case 'm':
  11105. case 'l': {
  11106. // get current X position
  11107. preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  11108. $currentxpos = $xmatches[1];
  11109. if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
  11110. if ($strcount == $maxkk) {
  11111. if ($this->rtl OR $this->tmprtl) {
  11112. $tvalue = $lnstring[1][$strcount];
  11113. } else {
  11114. $tvalue = rtrim($lnstring[1][$strcount]);
  11115. }
  11116. } else {
  11117. $tvalue = $lnstring[1][$strcount];
  11118. }
  11119. $ns += substr_count($tvalue, chr(32));
  11120. ++$strcount;
  11121. }
  11122. if ($this->rtl OR $this->tmprtl) {
  11123. $spacew = ($spacewidth * ($nsmax - $ns));
  11124. }
  11125. // justify block
  11126. $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
  11127. create_function('$matches', 'global $spacew;
  11128. $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
  11129. return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
  11130. break;
  11131. }
  11132. case 're': {
  11133. // get current X position
  11134. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  11135. $currentxpos = $xmatches[1];
  11136. // justify block
  11137. $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
  11138. create_function('$matches', 'global $spacew;
  11139. $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
  11140. return "".$newx." ".$matches[2]." ".$matches[3]." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
  11141. break;
  11142. }
  11143. case 'c': {
  11144. // get current X position
  11145. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  11146. $currentxpos = $xmatches[1];
  11147. // justify block
  11148. $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
  11149. create_function('$matches', 'global $spacew;
  11150. $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
  11151. $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
  11152. $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
  11153. return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
  11154. break;
  11155. }
  11156. }
  11157. // shift the annotations and links
  11158. if (isset($this->PageAnnots[$this->page])) {
  11159. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  11160. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  11161. $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
  11162. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  11163. break;
  11164. }
  11165. }
  11166. }
  11167. } // end of while
  11168. // remove markers
  11169. $pmid = str_replace('x*#!#*x', '', $pmid);
  11170. if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
  11171. // multibyte characters
  11172. $spacew = $spacewidthu;
  11173. $pmidtemp = $pmid;
  11174. // escape special characters
  11175. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  11176. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  11177. $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
  11178. create_function('$matches', 'global $spacew;
  11179. $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
  11180. $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
  11181. return "[(".str_replace(chr(0).chr(32), ") ".(-2830 * $spacew)." (", $matches[1]).")]";'), $pmidtemp);
  11182. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
  11183. $endlinepos = strlen($pstart."\n".$pmid."\n");
  11184. } else {
  11185. // non-unicode (single-byte characters)
  11186. $rs = sprintf("%.3F Tw", $spacewidth);
  11187. $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
  11188. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
  11189. $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
  11190. }
  11191. }
  11192. } // end of J
  11193. if (($t_x != 0) OR ($yshift < 0)) {
  11194. // shift the line
  11195. $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
  11196. $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
  11197. $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
  11198. // shift the annotations and links
  11199. if (isset($this->PageAnnots[$this->page])) {
  11200. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  11201. if ($pak >= $pask) {
  11202. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  11203. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  11204. }
  11205. }
  11206. }
  11207. $this->y -= $yshift;
  11208. }
  11209. }
  11210. }
  11211. $this->newline = false;
  11212. $pbrk = $this->checkPageBreak($this->lasth);
  11213. $this->SetFont($fontname, $fontstyle, $fontsize);
  11214. if ($wfill) {
  11215. $this->SetFillColorArray($this->bgcolor);
  11216. }
  11217. $startlinex = $this->x;
  11218. $startliney = $this->y;
  11219. $minstartliney = $this->y;
  11220. $startlinepage = $this->page;
  11221. if (isset($endlinepos) AND (!$pbrk)) {
  11222. $startlinepos = $endlinepos;
  11223. unset($endlinepos);
  11224. } else {
  11225. if (isset($this->footerlen[$this->page])) {
  11226. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  11227. } else {
  11228. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  11229. }
  11230. $startlinepos = $this->footerpos[$this->page];
  11231. }
  11232. $plalign = $lalign;
  11233. if (isset($this->PageAnnots[$this->page])) {
  11234. $pask = count($this->PageAnnots[$this->page]);
  11235. } else {
  11236. $pask = 0;
  11237. }
  11238. }
  11239. if (isset($opentagpos)) {
  11240. unset($opentagpos);
  11241. }
  11242. if ($dom[$key]['tag']) {
  11243. if ($dom[$key]['opening']) {
  11244. if ($dom[$key]['value'] == 'table') {
  11245. if ($this->rtl) {
  11246. $wtmp = $this->x - $this->lMargin;
  11247. } else {
  11248. $wtmp = $this->w - $this->rMargin - $this->x;
  11249. }
  11250. $wtmp -= (2 * $this->cMargin);
  11251. // calculate cell width
  11252. if (isset($dom[$key]['width'])) {
  11253. $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  11254. } else {
  11255. $table_width = $wtmp;
  11256. }
  11257. }
  11258. // table content is handled in a special way
  11259. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  11260. $trid = $dom[$key]['parent'];
  11261. $table_el = $dom[$trid]['parent'];
  11262. if (!isset($dom[$table_el]['cols'])) {
  11263. $dom[$table_el]['cols'] = $trid['cols'];
  11264. }
  11265. $oldmargin = $this->cMargin;
  11266. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
  11267. $currentcmargin = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
  11268. } else {
  11269. $currentcmargin = 0;
  11270. }
  11271. $this->cMargin = $currentcmargin;
  11272. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
  11273. $cellspacing = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'], 1, 'px');
  11274. } else {
  11275. $cellspacing = 0;
  11276. }
  11277. if ($this->rtl) {
  11278. $cellspacingx = -$cellspacing;
  11279. } else {
  11280. $cellspacingx = $cellspacing;
  11281. }
  11282. $colspan = $dom[$key]['attribute']['colspan'];
  11283. $wtmp = ($colspan * ($table_width / $dom[$table_el]['cols']));
  11284. if (isset($dom[$key]['width'])) {
  11285. $cellw = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  11286. } else {
  11287. $cellw = $wtmp;
  11288. }
  11289. if (isset($dom[$key]['height'])) {
  11290. // minimum cell height
  11291. $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
  11292. } else {
  11293. $cellh = 0;
  11294. }
  11295. $cellw -= $cellspacing;
  11296. if (isset($dom[$key]['content'])) {
  11297. $cell_content = $dom[$key]['content'];
  11298. } else {
  11299. $cell_content = '&nbsp;';
  11300. }
  11301. $tagtype = $dom[$key]['value'];
  11302. $parentid = $key;
  11303. while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
  11304. // move $key index forward
  11305. ++$key;
  11306. }
  11307. if (!isset($dom[$trid]['startpage'])) {
  11308. $dom[$trid]['startpage'] = $this->page;
  11309. } else {
  11310. $this->setPage($dom[$trid]['startpage']);
  11311. }
  11312. if (!isset($dom[$trid]['starty'])) {
  11313. $dom[$trid]['starty'] = $this->y;
  11314. } else {
  11315. $this->y = $dom[$trid]['starty'];
  11316. }
  11317. if (!isset($dom[$trid]['startx'])) {
  11318. $dom[$trid]['startx'] = $this->x;
  11319. }
  11320. $this->x += ($cellspacingx / 2);
  11321. if (isset($dom[$parentid]['attribute']['rowspan'])) {
  11322. $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
  11323. } else {
  11324. $rowspan = 1;
  11325. }
  11326. // skip row-spanned cells started on the previous rows
  11327. if (isset($dom[$table_el]['rowspans'])) {
  11328. $rsk = 0;
  11329. $rskmax = count($dom[$table_el]['rowspans']);
  11330. while ($rsk < $rskmax) {
  11331. $trwsp = $dom[$table_el]['rowspans'][$rsk];
  11332. $rsstartx = $trwsp['startx'];
  11333. $rsendx = $trwsp['endx'];
  11334. // account for margin changes
  11335. if ($trwsp['startpage'] < $this->page) {
  11336. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
  11337. $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
  11338. $rsstartx -= $dl;
  11339. $rsendx -= $dl;
  11340. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
  11341. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
  11342. $rsstartx += $dl;
  11343. $rsendx += $dl;
  11344. }
  11345. }
  11346. if (($trwsp['rowspan'] > 0)
  11347. AND ($rsstartx > ($this->x - $cellspacing - $currentcmargin - $this->feps))
  11348. AND ($rsstartx < ($this->x + $cellspacing + $currentcmargin + $this->feps))
  11349. AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page))) {
  11350. // set the starting X position of the current cell
  11351. $this->x = $rsendx + $cellspacingx;
  11352. if (($trwsp['rowspan'] == 1)
  11353. AND (isset($dom[$trid]['endy']))
  11354. AND (isset($dom[$trid]['endpage']))
  11355. AND ($trwsp['endpage'] == $dom[$trid]['endpage'])) {
  11356. // set ending Y position for row
  11357. $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  11358. $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
  11359. }
  11360. $rsk = 0;
  11361. } else {
  11362. ++$rsk;
  11363. }
  11364. }
  11365. }
  11366. // add rowspan information to table element
  11367. if ($rowspan > 1) {
  11368. if (isset($this->footerlen[$this->page])) {
  11369. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  11370. } else {
  11371. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  11372. }
  11373. $trintmrkpos = $this->footerpos[$this->page];
  11374. $trsid = array_push($dom[$table_el]['rowspans'], array('trid' => $trid, 'rowspan' => $rowspan, 'mrowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
  11375. }
  11376. $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
  11377. if ($rowspan > 1) {
  11378. $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
  11379. }
  11380. // push background colors
  11381. if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
  11382. $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
  11383. }
  11384. $prevLastH = $this->lasth;
  11385. // ****** write the cell content ******
  11386. $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
  11387. $this->lasth = $prevLastH;
  11388. $this->cMargin = $oldmargin;
  11389. $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
  11390. // update the end of row position
  11391. if ($rowspan <= 1) {
  11392. if (isset($dom[$trid]['endy'])) {
  11393. if ($this->page == $dom[$trid]['endpage']) {
  11394. $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
  11395. } elseif ($this->page > $dom[$trid]['endpage']) {
  11396. $dom[$trid]['endy'] = $this->y;
  11397. }
  11398. } else {
  11399. $dom[$trid]['endy'] = $this->y;
  11400. }
  11401. if (isset($dom[$trid]['endpage'])) {
  11402. $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
  11403. } else {
  11404. $dom[$trid]['endpage'] = $this->page;
  11405. }
  11406. } else {
  11407. // account for row-spanned cells
  11408. $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
  11409. $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
  11410. $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
  11411. }
  11412. if (isset($dom[$table_el]['rowspans'])) {
  11413. // update endy and endpage on rowspanned cells
  11414. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  11415. if ($trwsp['rowspan'] > 0) {
  11416. if (isset($dom[$trid]['endpage'])) {
  11417. if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
  11418. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  11419. } elseif ($trwsp['endpage'] < $dom[$trid]['endpage']) {
  11420. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
  11421. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
  11422. } else {
  11423. $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
  11424. }
  11425. }
  11426. }
  11427. }
  11428. }
  11429. $this->x += ($cellspacingx / 2);
  11430. } else {
  11431. // opening tag (or self-closing tag)
  11432. if (!isset($opentagpos)) {
  11433. if (!$this->InFooter) {
  11434. if (isset($this->footerlen[$this->page])) {
  11435. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  11436. } else {
  11437. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  11438. }
  11439. $opentagpos = $this->footerpos[$this->page];
  11440. }
  11441. }
  11442. $this->openHTMLTagHandler($dom, $key, $cell);
  11443. }
  11444. } else {
  11445. // closing tag
  11446. $this->closeHTMLTagHandler($dom, $key, $cell);
  11447. }
  11448. } elseif (strlen($dom[$key]['value']) > 0) {
  11449. // print list-item
  11450. if (!$this->empty_string($this->lispacer)) {
  11451. $this->SetFont($pfontname, $pfontstyle, $pfontsize);
  11452. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  11453. $minstartliney = $this->y;
  11454. $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
  11455. $this->SetFont($curfontname, $curfontstyle, $curfontsize);
  11456. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  11457. if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
  11458. $this->y += (($pfontsize - $curfontsize) / $this->k);
  11459. $minstartliney = min($this->y, $minstartliney);
  11460. }
  11461. }
  11462. // text
  11463. $this->htmlvspace = 0;
  11464. if ((!$this->premode) AND ($this->rtl OR $this->tmprtl)) {
  11465. // reverse spaces order
  11466. $len1 = strlen($dom[$key]['value']);
  11467. $lsp = $len1 - strlen(ltrim($dom[$key]['value']));
  11468. $rsp = $len1 - strlen(rtrim($dom[$key]['value']));
  11469. $tmpstr = '';
  11470. if ($rsp > 0) {
  11471. $tmpstr .= substr($dom[$key]['value'], -$rsp);
  11472. }
  11473. $tmpstr .= trim($dom[$key]['value']);
  11474. if ($lsp > 0) {
  11475. $tmpstr .= substr($dom[$key]['value'], 0, $lsp);
  11476. }
  11477. $dom[$key]['value'] = $tmpstr;
  11478. }
  11479. if ($newline) {
  11480. if (!$this->premode) {
  11481. if (($this->rtl OR $this->tmprtl)) {
  11482. $dom[$key]['value'] = rtrim($dom[$key]['value']);
  11483. } else {
  11484. $dom[$key]['value'] = ltrim($dom[$key]['value']);
  11485. }
  11486. }
  11487. $newline = false;
  11488. $firstblock = true;
  11489. } else {
  11490. $firstblock = false;
  11491. }
  11492. $strrest = '';
  11493. if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
  11494. // HTML <a> Link
  11495. $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $this->HREF['color'], $this->HREF['style']);
  11496. } else {
  11497. $ctmpmargin = $this->cMargin;
  11498. $this->cMargin = 0;
  11499. // ****** write only until the end of the line and get the rest ******
  11500. $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock);
  11501. $this->cMargin = $ctmpmargin;
  11502. }
  11503. if (strlen($strrest) > 0) {
  11504. // store the remaining string on the previous $key position
  11505. $this->newline = true;
  11506. if ($cell) {
  11507. if ($this->rtl) {
  11508. $this->x -= $this->cMargin;
  11509. } else {
  11510. $this->x += $this->cMargin;
  11511. }
  11512. }
  11513. if ($strrest == $dom[$key]['value']) {
  11514. // used to avoid infinite loop
  11515. ++$loop;
  11516. } else {
  11517. $loop = 0;
  11518. }
  11519. $dom[$key]['value'] = ltrim($strrest);
  11520. if ($loop < 3) {
  11521. --$key;
  11522. }
  11523. } else {
  11524. $loop = 0;
  11525. }
  11526. }
  11527. ++$key;
  11528. } // end for each $key
  11529. // align the last line
  11530. if (isset($startlinex)) {
  11531. $yshift = $minstartliney - $startliney;
  11532. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  11533. $yshift = 0;
  11534. }
  11535. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
  11536. // the last line must be shifted to be aligned as requested
  11537. $linew = abs($this->endlinex - $startlinex);
  11538. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  11539. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  11540. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  11541. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  11542. } elseif (isset($opentagpos)) {
  11543. $midpos = $opentagpos;
  11544. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  11545. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  11546. $midpos = $this->footerpos[$startlinepage];
  11547. } else {
  11548. $midpos = 0;
  11549. }
  11550. if ($midpos > 0) {
  11551. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  11552. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  11553. } else {
  11554. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  11555. $pend = '';
  11556. }
  11557. // calculate shifting amount
  11558. $tw = $w;
  11559. if ($this->lMargin != $prevlMargin) {
  11560. $tw += ($prevlMargin - $this->lMargin);
  11561. }
  11562. if ($this->rMargin != $prevrMargin) {
  11563. $tw += ($prevrMargin - $this->rMargin);
  11564. }
  11565. $mdiff = abs($tw - $linew);
  11566. if ($plalign == 'C') {
  11567. if ($this->rtl) {
  11568. $t_x = -($mdiff / 2);
  11569. } else {
  11570. $t_x = ($mdiff / 2);
  11571. }
  11572. } elseif (($plalign == 'R') AND (!$this->rtl)) {
  11573. // right alignment on LTR document
  11574. $t_x = $mdiff;
  11575. } elseif (($plalign == 'L') AND ($this->rtl)) {
  11576. // left alignment on RTL document
  11577. $t_x = -$mdiff;
  11578. } else {
  11579. $t_x = 0;
  11580. }
  11581. if (($t_x != 0) OR ($yshift < 0)) {
  11582. // shift the line
  11583. $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
  11584. $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
  11585. $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
  11586. // shift the annotations and links
  11587. if (isset($this->PageAnnots[$this->page])) {
  11588. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  11589. if ($pak >= $pask) {
  11590. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  11591. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  11592. }
  11593. }
  11594. }
  11595. $this->y -= $yshift;
  11596. }
  11597. }
  11598. }
  11599. if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
  11600. $this->Ln($this->lasth);
  11601. }
  11602. // restore previous values
  11603. $this->setGraphicVars($gvars);
  11604. if ($this->page > $prevPage) {
  11605. $this->lMargin = $this->pagedim[$this->page]['olm'];
  11606. $this->rMargin = $this->pagedim[$this->page]['orm'];
  11607. }
  11608. unset($dom);
  11609. }
  11610. /**
  11611. * Process opening tags.
  11612. * @param array $dom html dom array
  11613. * @param int $key current element id
  11614. * @param boolean $cell if true add the default cMargin space to each new line (default false).
  11615. * @access protected
  11616. */
  11617. protected function openHTMLTagHandler(&$dom, $key, $cell=false) {
  11618. $tag = $dom[$key];
  11619. $parent = $dom[($dom[$key]['parent'])];
  11620. $firstorlast = ($key == 1);
  11621. // check for text direction attribute
  11622. if (isset($tag['attribute']['dir'])) {
  11623. $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
  11624. } else {
  11625. $this->tmprtl = false;
  11626. }
  11627. //Opening tag
  11628. switch($tag['value']) {
  11629. case 'table': {
  11630. $cp = 0;
  11631. $cs = 0;
  11632. $dom[$key]['rowspans'] = array();
  11633. if (!$this->empty_string($dom[$key]['thead'])) {
  11634. // set table header
  11635. $this->thead = $dom[$key]['thead'];
  11636. }
  11637. if (isset($tag['attribute']['cellpadding'])) {
  11638. $cp = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
  11639. $this->oldcMargin = $this->cMargin;
  11640. $this->cMargin = $cp;
  11641. }
  11642. if (isset($tag['attribute']['cellspacing'])) {
  11643. $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  11644. }
  11645. $this->checkPageBreak((2 * $cp) + (2 * $cs) + $this->lasth);
  11646. break;
  11647. }
  11648. case 'tr': {
  11649. // array of columns positions
  11650. $dom[$key]['cellpos'] = array();
  11651. break;
  11652. }
  11653. case 'hr': {
  11654. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
  11655. $this->htmlvspace = 0;
  11656. $wtmp = $this->w - $this->lMargin - $this->rMargin;
  11657. if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
  11658. $hrWidth = $this->getHTMLUnitToUnits($tag['attribute']['width'], $wtmp, 'px');
  11659. } else {
  11660. $hrWidth = $wtmp;
  11661. }
  11662. $x = $this->GetX();
  11663. $y = $this->GetY();
  11664. $prevlinewidth = $this->GetLineWidth();
  11665. $this->Line($x, $y, $x + $hrWidth, $y);
  11666. $this->SetLineWidth($prevlinewidth);
  11667. $this->addHTMLVertSpace(1, $cell, '', !isset($dom[($key + 1)]), $tag['value'], false);
  11668. break;
  11669. }
  11670. case 'a': {
  11671. if (array_key_exists('href', $tag['attribute'])) {
  11672. $this->HREF['url'] = $tag['attribute']['href'];
  11673. }
  11674. $this->HREF['color'] = $this->htmlLinkColorArray;
  11675. $this->HREF['style'] = $this->htmlLinkFontStyle;
  11676. if (array_key_exists('style', $tag['attribute'])) {
  11677. // get style attributes
  11678. preg_match_all('/([^;:\s]*):([^;]*)/', $tag['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  11679. $astyle = array();
  11680. while (list($id, $name) = each($style_array[1])) {
  11681. $name = strtolower($name);
  11682. $astyle[$name] = trim($style_array[2][$id]);
  11683. }
  11684. if (isset($astyle['color'])) {
  11685. $this->HREF['color'] = $this->convertHTMLColorToDec($astyle['color']);
  11686. }
  11687. if (isset($astyle['text-decoration'])) {
  11688. $this->HREF['style'] = '';
  11689. $decors = explode(' ', strtolower($astyle['text-decoration']));
  11690. foreach ($decors as $dec) {
  11691. $dec = trim($dec);
  11692. if (!$this->empty_string($dec)) {
  11693. if ($dec{0} == 'u') {
  11694. $this->HREF['style'] .= 'U';
  11695. } elseif ($dec{0} == 'l') {
  11696. $this->HREF['style'] .= 'D';
  11697. }
  11698. }
  11699. }
  11700. }
  11701. }
  11702. break;
  11703. }
  11704. case 'img': {
  11705. if (isset($tag['attribute']['src'])) {
  11706. // replace relative path with real server path
  11707. if ($tag['attribute']['src'][0] == '/') {
  11708. $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
  11709. }
  11710. $tag['attribute']['src'] = urldecode($tag['attribute']['src']);
  11711. $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
  11712. if (!isset($tag['attribute']['width'])) {
  11713. $tag['attribute']['width'] = 0;
  11714. }
  11715. if (!isset($tag['attribute']['height'])) {
  11716. $tag['attribute']['height'] = 0;
  11717. }
  11718. //if (!isset($tag['attribute']['align'])) {
  11719. // the only alignment supported is "bottom"
  11720. // further development is required for other modes.
  11721. $tag['attribute']['align'] = 'bottom';
  11722. //}
  11723. switch($tag['attribute']['align']) {
  11724. case 'top': {
  11725. $align = 'T';
  11726. break;
  11727. }
  11728. case 'middle': {
  11729. $align = 'M';
  11730. break;
  11731. }
  11732. case 'bottom': {
  11733. $align = 'B';
  11734. break;
  11735. }
  11736. default: {
  11737. $align = 'B';
  11738. break;
  11739. }
  11740. }
  11741. $fileinfo = pathinfo($tag['attribute']['src']);
  11742. if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
  11743. $type = strtolower($fileinfo['extension']);
  11744. }
  11745. $prevy = $this->y;
  11746. $xpos = $this->GetX();
  11747. if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == ' ')) {
  11748. if ($this->rtl) {
  11749. $xpos += $this->GetStringWidth(' ');
  11750. } else {
  11751. $xpos -= $this->GetStringWidth(' ');
  11752. }
  11753. }
  11754. $imglink = '';
  11755. if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
  11756. $imglink = $this->HREF['url'];
  11757. if ($imglink{0} == '#') {
  11758. // convert url to internal link
  11759. $page = intval(substr($imglink, 1));
  11760. $imglink = $this->AddLink();
  11761. $this->SetLink($imglink, 0, $page);
  11762. }
  11763. }
  11764. $border = 0;
  11765. if (isset($tag['attribute']['border']) AND !empty($tag['attribute']['border'])) {
  11766. // currently only support 1 (frame) or a combination of 'LTRB'
  11767. $border = $tag['attribute']['border'];
  11768. }
  11769. $iw = '';
  11770. if (isset($tag['attribute']['width'])) {
  11771. $iw = $this->getHTMLUnitToUnits($tag['attribute']['width'], 1, 'px', false);
  11772. }
  11773. $ih = '';
  11774. if (isset($tag['attribute']['height'])) {
  11775. $ih = $this->getHTMLUnitToUnits($tag['attribute']['height'], 1, 'px', false);
  11776. }
  11777. if (($type == 'eps') OR ($type == 'ai')) {
  11778. $this->ImageEps($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, $imglink, true, $align, '', $border);
  11779. } else {
  11780. $this->Image($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border);
  11781. }
  11782. switch($align) {
  11783. case 'T': {
  11784. $this->y = $prevy;
  11785. break;
  11786. }
  11787. case 'M': {
  11788. $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
  11789. break;
  11790. }
  11791. case 'B': {
  11792. $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
  11793. break;
  11794. }
  11795. }
  11796. }
  11797. break;
  11798. }
  11799. case 'dl': {
  11800. ++$this->listnum;
  11801. $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
  11802. break;
  11803. }
  11804. case 'dt': {
  11805. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
  11806. break;
  11807. }
  11808. case 'dd': {
  11809. if ($this->rtl) {
  11810. $this->rMargin += $this->listindent;
  11811. } else {
  11812. $this->lMargin += $this->listindent;
  11813. }
  11814. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
  11815. break;
  11816. }
  11817. case 'ul':
  11818. case 'ol': {
  11819. $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
  11820. $this->htmlvspace = 0;
  11821. ++$this->listnum;
  11822. if ($tag['value'] == 'ol') {
  11823. $this->listordered[$this->listnum] = true;
  11824. } else {
  11825. $this->listordered[$this->listnum] = false;
  11826. }
  11827. if (isset($tag['attribute']['start'])) {
  11828. $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
  11829. } else {
  11830. $this->listcount[$this->listnum] = 0;
  11831. }
  11832. if ($this->rtl) {
  11833. $this->rMargin += $this->listindent;
  11834. } else {
  11835. $this->lMargin += $this->listindent;
  11836. }
  11837. $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
  11838. $this->htmlvspace = 0;
  11839. break;
  11840. }
  11841. case 'li': {
  11842. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
  11843. if ($this->listordered[$this->listnum]) {
  11844. // ordered item
  11845. if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
  11846. $this->lispacer = $parent['attribute']['type'];
  11847. } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
  11848. $this->lispacer = $parent['listtype'];
  11849. } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
  11850. $this->lispacer = $this->lisymbol;
  11851. } else {
  11852. $this->lispacer = '#';
  11853. }
  11854. ++$this->listcount[$this->listnum];
  11855. if (isset($tag['attribute']['value'])) {
  11856. $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
  11857. }
  11858. } else {
  11859. // unordered item
  11860. if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
  11861. $this->lispacer = $parent['attribute']['type'];
  11862. } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
  11863. $this->lispacer = $parent['listtype'];
  11864. } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
  11865. $this->lispacer = $this->lisymbol;
  11866. } else {
  11867. $this->lispacer = '!';
  11868. }
  11869. }
  11870. break;
  11871. }
  11872. case 'blockquote': {
  11873. if ($this->rtl) {
  11874. $this->rMargin += $this->listindent;
  11875. } else {
  11876. $this->lMargin += $this->listindent;
  11877. }
  11878. $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
  11879. break;
  11880. }
  11881. case 'br': {
  11882. $this->Ln('', $cell);
  11883. break;
  11884. }
  11885. case 'div': {
  11886. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
  11887. break;
  11888. }
  11889. case 'p': {
  11890. $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
  11891. break;
  11892. }
  11893. case 'pre': {
  11894. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
  11895. $this->premode = true;
  11896. break;
  11897. }
  11898. case 'sup': {
  11899. $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
  11900. break;
  11901. }
  11902. case 'sub': {
  11903. $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
  11904. break;
  11905. }
  11906. case 'h1':
  11907. case 'h2':
  11908. case 'h3':
  11909. case 'h4':
  11910. case 'h5':
  11911. case 'h6': {
  11912. $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], false);
  11913. break;
  11914. }
  11915. case 'tcpdf': {
  11916. if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
  11917. // Special tag used to call TCPDF methods
  11918. if (isset($tag['attribute']['method'])) {
  11919. $tcpdf_method = $tag['attribute']['method'];
  11920. if (method_exists($this, $tcpdf_method)) {
  11921. if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
  11922. $params = unserialize(urldecode($tag['attribute']['params']));
  11923. call_user_func_array(array($this, $tcpdf_method), $params);
  11924. } else {
  11925. $this->$tcpdf_method();
  11926. }
  11927. $this->newline = true;
  11928. }
  11929. }
  11930. }
  11931. }
  11932. default: {
  11933. break;
  11934. }
  11935. }
  11936. }
  11937. /**
  11938. * Process closing tags.
  11939. * @param array $dom html dom array
  11940. * @param int $key current element id
  11941. * @param boolean $cell if true add the default cMargin space to each new line (default false).
  11942. * @access protected
  11943. */
  11944. protected function closeHTMLTagHandler(&$dom, $key, $cell=false) {
  11945. $tag = $dom[$key];
  11946. $parent = $dom[($dom[$key]['parent'])];
  11947. $firstorlast = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
  11948. //Closing tag
  11949. switch($tag['value']) {
  11950. case 'tr': {
  11951. $table_el = $dom[($dom[$key]['parent'])]['parent'];
  11952. if(!isset($parent['endy'])) {
  11953. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  11954. $parent['endy'] = $this->y;
  11955. }
  11956. if(!isset($parent['endpage'])) {
  11957. $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
  11958. $parent['endpage'] = $this->page;
  11959. }
  11960. // update row-spanned cells
  11961. if (isset($dom[$table_el]['rowspans'])) {
  11962. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  11963. $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
  11964. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  11965. if ($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) {
  11966. $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
  11967. } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) {
  11968. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  11969. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  11970. }
  11971. }
  11972. }
  11973. // report new endy and endpage to the rowspanned cells
  11974. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  11975. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  11976. $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
  11977. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  11978. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
  11979. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  11980. }
  11981. }
  11982. // update remaining rowspanned cells
  11983. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  11984. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  11985. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
  11986. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
  11987. }
  11988. }
  11989. }
  11990. $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
  11991. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  11992. if (isset($dom[$table_el]['attribute']['cellspacing'])) {
  11993. $cellspacing = $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
  11994. $this->y += $cellspacing;
  11995. }
  11996. $this->Ln(0, $cell);
  11997. $this->x = $parent['startx'];
  11998. // account for booklet mode
  11999. if ($this->page > $parent['startpage']) {
  12000. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
  12001. $this->x += ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
  12002. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
  12003. $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
  12004. }
  12005. }
  12006. break;
  12007. }
  12008. case 'table': {
  12009. // draw borders
  12010. $table_el = $parent;
  12011. if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
  12012. OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
  12013. $border = 1;
  12014. } else {
  12015. $border = 0;
  12016. }
  12017. // fix bottom line alignment of last line before page break
  12018. foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
  12019. // update row-spanned cells
  12020. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  12021. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  12022. if ($trwsp['trid'] == $trkey) {
  12023. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
  12024. }
  12025. if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
  12026. $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
  12027. }
  12028. }
  12029. }
  12030. if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
  12031. $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
  12032. $dom[$prevtrkey]['endy'] = $pgendy;
  12033. // update row-spanned cells
  12034. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  12035. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  12036. if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] == 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
  12037. $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
  12038. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
  12039. }
  12040. }
  12041. }
  12042. }
  12043. $prevtrkey = $trkey;
  12044. $table_el = $dom[($dom[$key]['parent'])];
  12045. }
  12046. // for each row
  12047. foreach ($table_el['trids'] as $j => $trkey) {
  12048. $parent = $dom[$trkey];
  12049. // for each cell on the row
  12050. foreach ($parent['cellpos'] as $k => $cellpos) {
  12051. if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
  12052. $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
  12053. $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
  12054. $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
  12055. $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
  12056. $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
  12057. } else {
  12058. $endy = $parent['endy'];
  12059. $startpage = $parent['startpage'];
  12060. $endpage = $parent['endpage'];
  12061. }
  12062. if ($endpage > $startpage) {
  12063. // design borders around HTML cells.
  12064. for ($page=$startpage; $page <= $endpage; ++$page) {
  12065. $this->setPage($page);
  12066. if ($page == $startpage) {
  12067. $this->y = $parent['starty']; // put cursor at the beginning of row on the first page
  12068. $ch = $this->getPageHeight() - $parent['starty'] - $this->getBreakMargin();
  12069. $cborder = $this->getBorderMode($border, $position='start');
  12070. } elseif ($page == $endpage) {
  12071. $this->y = $this->tMargin; // put cursor at the beginning of last page
  12072. $ch = $endy - $this->tMargin;
  12073. $cborder = $this->getBorderMode($border, $position='end');
  12074. } else {
  12075. $this->y = $this->tMargin; // put cursor at the beginning of the current page
  12076. $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
  12077. $cborder = $this->getBorderMode($border, $position='middle');
  12078. }
  12079. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  12080. $this->SetFillColorArray($cellpos['bgcolor']);
  12081. $fill = true;
  12082. } else {
  12083. $fill = false;
  12084. }
  12085. $cw = abs($cellpos['endx'] - $cellpos['startx']);
  12086. $this->x = $cellpos['startx'];
  12087. // account for margin changes
  12088. if ($page > $startpage) {
  12089. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  12090. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  12091. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['lm'] != $this->pagedim[$startpage]['olm'])) {
  12092. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  12093. }
  12094. }
  12095. // design a cell around the text
  12096. $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $cborder, 1, '', $fill, '', 0, true);
  12097. if ($cborder OR $fill) {
  12098. $pagebuff = $this->getPageBuffer($this->page);
  12099. $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
  12100. $pend = substr($pagebuff, $this->intmrk[$this->page]);
  12101. $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
  12102. $this->intmrk[$this->page] += strlen($ccode."\n");
  12103. }
  12104. }
  12105. } else {
  12106. $this->setPage($startpage);
  12107. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  12108. $this->SetFillColorArray($cellpos['bgcolor']);
  12109. $fill = true;
  12110. } else {
  12111. $fill = false;
  12112. }
  12113. $this->x = $cellpos['startx'];
  12114. $this->y = $parent['starty'];
  12115. $cw = abs($cellpos['endx'] - $cellpos['startx']);
  12116. $ch = $endy - $parent['starty'];
  12117. // design a cell around the text
  12118. $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $border, 1, '', $fill, '', 0, true);
  12119. if ($border OR $fill) {
  12120. if (end($this->transfmrk[$this->page]) !== false) {
  12121. $pagemarkkey = key($this->transfmrk[$this->page]);
  12122. $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
  12123. } elseif ($this->InFooter) {
  12124. $pagemark = &$this->footerpos[$this->page];
  12125. } else {
  12126. $pagemark = &$this->intmrk[$this->page];
  12127. }
  12128. $pagebuff = $this->getPageBuffer($this->page);
  12129. $pstart = substr($pagebuff, 0, $pagemark);
  12130. $pend = substr($pagebuff, $pagemark);
  12131. $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
  12132. $pagemark += strlen($ccode."\n");
  12133. }
  12134. }
  12135. }
  12136. if (isset($table_el['attribute']['cellspacing'])) {
  12137. $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
  12138. $this->y += $cellspacing;
  12139. }
  12140. $this->Ln(0, $cell);
  12141. $this->x = $parent['startx'];
  12142. if ($endpage > $startpage) {
  12143. if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
  12144. $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
  12145. } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
  12146. $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
  12147. }
  12148. }
  12149. }
  12150. if (isset($parent['cellpadding'])) {
  12151. $this->cMargin = $this->oldcMargin;
  12152. }
  12153. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  12154. if (!$this->empty_string($this->theadMargin)) {
  12155. // restore top margin
  12156. $this->tMargin = $this->theadMargin;
  12157. $this->pagedim[$this->page]['tm'] = $this->theadMargin;
  12158. }
  12159. // reset table header
  12160. $this->thead = '';
  12161. $this->theadMargin = '';
  12162. break;
  12163. }
  12164. case 'a': {
  12165. $this->HREF = '';
  12166. break;
  12167. }
  12168. case 'sup': {
  12169. $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
  12170. break;
  12171. }
  12172. case 'sub': {
  12173. $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
  12174. break;
  12175. }
  12176. case 'div': {
  12177. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
  12178. break;
  12179. }
  12180. case 'blockquote': {
  12181. if ($this->rtl) {
  12182. $this->rMargin -= $this->listindent;
  12183. } else {
  12184. $this->lMargin -= $this->listindent;
  12185. }
  12186. $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
  12187. break;
  12188. }
  12189. case 'p': {
  12190. $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
  12191. break;
  12192. }
  12193. case 'pre': {
  12194. $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
  12195. $this->premode = false;
  12196. break;
  12197. }
  12198. case 'dl': {
  12199. --$this->listnum;
  12200. if ($this->listnum <= 0) {
  12201. $this->listnum = 0;
  12202. $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
  12203. }
  12204. break;
  12205. }
  12206. case 'dt': {
  12207. $this->lispacer = '';
  12208. $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
  12209. break;
  12210. }
  12211. case 'dd': {
  12212. $this->lispacer = '';
  12213. if ($this->rtl) {
  12214. $this->rMargin -= $this->listindent;
  12215. } else {
  12216. $this->lMargin -= $this->listindent;
  12217. }
  12218. $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
  12219. break;
  12220. }
  12221. case 'ul':
  12222. case 'ol': {
  12223. --$this->listnum;
  12224. $this->lispacer = '';
  12225. if ($this->rtl) {
  12226. $this->rMargin -= $this->listindent;
  12227. } else {
  12228. $this->lMargin -= $this->listindent;
  12229. }
  12230. if ($this->listnum <= 0) {
  12231. $this->listnum = 0;
  12232. $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
  12233. }
  12234. $this->lasth = $this->FontSize * $this->cell_height_ratio;
  12235. break;
  12236. }
  12237. case 'li': {
  12238. $this->lispacer = '';
  12239. $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
  12240. break;
  12241. }
  12242. case 'h1':
  12243. case 'h2':
  12244. case 'h3':
  12245. case 'h4':
  12246. case 'h5':
  12247. case 'h6': {
  12248. $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], true);
  12249. break;
  12250. }
  12251. default : {
  12252. break;
  12253. }
  12254. }
  12255. $this->tmprtl = false;
  12256. }
  12257. /**
  12258. * Add vertical spaces if needed.
  12259. * @param int $n number of spaces to add
  12260. * @param boolean $cell if true add the default cMargin space to each new line (default false).
  12261. * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
  12262. * @param boolean $firstorlast if true do not print additional empty lines.
  12263. * @param string $tag HTML tag to which this space will be applied
  12264. * @param boolean $closing true if this space will be applied to a closing tag, false otherwise
  12265. * @access protected
  12266. */
  12267. protected function addHTMLVertSpace($n, $cell=false, $h='', $firstorlast=false, $tag='', $closing=false) {
  12268. if ($firstorlast) {
  12269. $this->Ln(0, $cell);
  12270. $this->htmlvspace = 0;
  12271. return;
  12272. }
  12273. if (isset($this->tagvspaces[$tag][intval($closing)]['n'])) {
  12274. $n = $this->tagvspaces[$tag][intval($closing)]['n'];
  12275. }
  12276. if (isset($this->tagvspaces[$tag][intval($closing)]['h'])) {
  12277. $h = $this->tagvspaces[$tag][intval($closing)]['h'];
  12278. }
  12279. if (is_string($h)) {
  12280. $vsize = $n * $this->lasth;
  12281. } else {
  12282. $vsize = $n * $h;
  12283. }
  12284. if ($vsize > $this->htmlvspace) {
  12285. $this->Ln(($vsize - $this->htmlvspace), $cell);
  12286. $this->htmlvspace = $vsize;
  12287. }
  12288. }
  12289. /**
  12290. * Set the default bullet to be used as LI bullet symbol
  12291. * @param string $symbol 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')
  12292. * @access public
  12293. * @since 4.0.028 (2008-09-26)
  12294. */
  12295. public function setLIsymbol($symbol='!') {
  12296. $symbol = strtolower($symbol);
  12297. switch ($symbol) {
  12298. case '!' :
  12299. case '#' :
  12300. case 'disc' :
  12301. case 'disc' :
  12302. case 'circle' :
  12303. case 'square' :
  12304. case '1':
  12305. case 'decimal':
  12306. case 'decimal-leading-zero':
  12307. case 'i':
  12308. case 'lower-roman':
  12309. case 'I':
  12310. case 'upper-roman':
  12311. case 'a':
  12312. case 'lower-alpha':
  12313. case 'lower-latin':
  12314. case 'A':
  12315. case 'upper-alpha':
  12316. case 'upper-latin':
  12317. case 'lower-greek': {
  12318. $this->lisymbol = $symbol;
  12319. break;
  12320. }
  12321. default : {
  12322. $this->lisymbol = '';
  12323. }
  12324. }
  12325. }
  12326. /**
  12327. * Set the booklet mode for double-sided pages.
  12328. * @param boolean $booklet true set the booklet mode on, fals eotherwise.
  12329. * @param float $inner Inner page margin.
  12330. * @param float $outer Outer page margin.
  12331. * @access public
  12332. * @since 4.2.000 (2008-10-29)
  12333. */
  12334. public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
  12335. $this->booklet = $booklet;
  12336. if ($inner >= 0) {
  12337. $this->lMargin = $inner;
  12338. }
  12339. if ($outer >= 0) {
  12340. $this->rMargin = $outer;
  12341. }
  12342. }
  12343. /**
  12344. * Swap the left and right margins.
  12345. * @param boolean $reverse if true swap left and right margins.
  12346. * @access protected
  12347. * @since 4.2.000 (2008-10-29)
  12348. */
  12349. protected function swapMargins($reverse=true) {
  12350. if ($reverse) {
  12351. // swap left and right margins
  12352. $mtemp = $this->original_lMargin;
  12353. $this->original_lMargin = $this->original_rMargin;
  12354. $this->original_rMargin = $mtemp;
  12355. $deltam = $this->original_lMargin - $this->original_rMargin;
  12356. $this->lMargin += $deltam;
  12357. $this->rMargin -= $deltam;
  12358. }
  12359. }
  12360. /**
  12361. * Set the vertical spaces for HTML tags.
  12362. * The array must have the following structure (example):
  12363. * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
  12364. * The first array level contains the tag names,
  12365. * the second level contains 0 for opening tags or 1 for closing tags,
  12366. * the third level contains the vertical space unit (h) and the number spaces to add (n).
  12367. * If the h parameter is not specified, default values are used.
  12368. * @param array $tagvs array of tags and relative vertical spaces.
  12369. * @access public
  12370. * @since 4.2.001 (2008-10-30)
  12371. */
  12372. public function setHtmlVSpace($tagvs) {
  12373. $this->tagvspaces = $tagvs;
  12374. }
  12375. /**
  12376. * Set custom width for list indentation.
  12377. * @param float $width width of the indentation. Use negative value to disable it.
  12378. * @access public
  12379. * @since 4.2.007 (2008-11-12)
  12380. */
  12381. public function setListIndentWidth($width) {
  12382. return $this->customlistindent = floatval($width);
  12383. }
  12384. /**
  12385. * Set the top/bottom cell sides to be open or closed when the cell cross the page.
  12386. * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page.
  12387. * @access public
  12388. * @since 4.2.010 (2008-11-14)
  12389. */
  12390. public function setOpenCell($isopen) {
  12391. $this->opencell = $isopen;
  12392. }
  12393. /**
  12394. * Set the color and font style for HTML links.
  12395. * @param array $color RGB array of colors
  12396. * @param string $fontstyle additional font styles to add
  12397. * @access public
  12398. * @since 4.4.003 (2008-12-09)
  12399. */
  12400. public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
  12401. $this->htmlLinkColorArray = $color;
  12402. $this->htmlLinkFontStyle = $fontstyle;
  12403. }
  12404. /**
  12405. * convert html string containing value and unit of measure to user's units or points.
  12406. * @param string $htmlval string containing values and unit
  12407. * @param string $refsize reference value in points
  12408. * @param string $defaultunit default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  12409. * @param boolean $point if true returns points, otherwise returns value in user's units
  12410. * @return float value in user's unit or point if $points=true
  12411. * @access public
  12412. * @since 4.4.004 (2008-12-10)
  12413. */
  12414. public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
  12415. $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
  12416. $retval = 0;
  12417. $value = 0;
  12418. $unit = 'px';
  12419. $k = $this->k;
  12420. if ($points) {
  12421. $k = 1;
  12422. }
  12423. if (in_array($defaultunit, $supportedunits)) {
  12424. $unit = $defaultunit;
  12425. }
  12426. if (is_numeric($htmlval)) {
  12427. $value = floatval($htmlval);
  12428. } elseif (preg_match('/([0-9\.]+)/', $htmlval, $mnum)) {
  12429. $value = floatval($mnum[1]);
  12430. if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
  12431. if (in_array($munit[1], $supportedunits)) {
  12432. $unit = $munit[1];
  12433. }
  12434. }
  12435. }
  12436. switch ($unit) {
  12437. // percentage
  12438. case '%': {
  12439. $retval = (($value * $refsize) / 100);
  12440. break;
  12441. }
  12442. // relative-size
  12443. case 'em': {
  12444. $retval = ($value * $refsize);
  12445. break;
  12446. }
  12447. case 'ex': {
  12448. $retval = $value * ($refsize / 2);
  12449. break;
  12450. }
  12451. // absolute-size
  12452. case 'in': {
  12453. $retval = ($value * $this->dpi) / $k;
  12454. break;
  12455. }
  12456. case 'cm': {
  12457. $retval = ($value / 2.54 * $this->dpi) / $k;
  12458. break;
  12459. }
  12460. case 'mm': {
  12461. $retval = ($value / 25.4 * $this->dpi) / $k;
  12462. break;
  12463. }
  12464. case 'pc': {
  12465. // one pica is 12 points
  12466. $retval = ($value * 12) / $k;
  12467. break;
  12468. }
  12469. case 'pt': {
  12470. $retval = $value / $k;
  12471. break;
  12472. }
  12473. case 'px': {
  12474. $retval = $this->pixelsToUnits($value);
  12475. break;
  12476. }
  12477. }
  12478. return $retval;
  12479. }
  12480. /**
  12481. * Returns the Roman representation of an integer number
  12482. * @param int number to convert
  12483. * @return string roman representation of the specified number
  12484. * @access public
  12485. * @since 4.4.004 (2008-12-10)
  12486. */
  12487. public function intToRoman($number) {
  12488. $roman = '';
  12489. while ($number >= 1000) {
  12490. $roman .= 'M';
  12491. $number -= 1000;
  12492. }
  12493. while ($number >= 900) {
  12494. $roman .= 'CM';
  12495. $number -= 900;
  12496. }
  12497. while ($number >= 500) {
  12498. $roman .= 'D';
  12499. $number -= 500;
  12500. }
  12501. while ($number >= 400) {
  12502. $roman .= 'CD';
  12503. $number -= 400;
  12504. }
  12505. while ($number >= 100) {
  12506. $roman .= 'C';
  12507. $number -= 100;
  12508. }
  12509. while ($number >= 90) {
  12510. $roman .= 'XC';
  12511. $number -= 90;
  12512. }
  12513. while ($number >= 50) {
  12514. $roman .= 'L';
  12515. $number -= 50;
  12516. }
  12517. while ($number >= 40) {
  12518. $roman .= 'XL';
  12519. $number -= 40;
  12520. }
  12521. while ($number >= 10) {
  12522. $roman .= 'X';
  12523. $number -= 10;
  12524. }
  12525. while ($number >= 9) {
  12526. $roman .= 'IX';
  12527. $number -= 9;
  12528. }
  12529. while ($number >= 5) {
  12530. $roman .= 'V';
  12531. $number -= 5;
  12532. }
  12533. while ($number >= 4) {
  12534. $roman .= 'IV';
  12535. $number -= 4;
  12536. }
  12537. while ($number >= 1) {
  12538. $roman .= 'I';
  12539. --$number;
  12540. }
  12541. return $roman;
  12542. }
  12543. /**
  12544. * Output an HTML list bullet or ordered item symbol
  12545. * @param int $listdepth list nesting level
  12546. * @param string $listtype type of list
  12547. * @param float $size current font size
  12548. * @access protected
  12549. * @since 4.4.004 (2008-12-10)
  12550. */
  12551. protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
  12552. $size /= $this->k;
  12553. $fill = '';
  12554. $color = $this->fgcolor;
  12555. $width = 0;
  12556. $textitem = '';
  12557. $tmpx = $this->x;
  12558. $lspace = $this->GetStringWidth(' ');
  12559. if ($listtype == '!') {
  12560. // set default list type for unordered list
  12561. $deftypes = array('disc', 'circle', 'square');
  12562. $listtype = $deftypes[($listdepth - 1) % 3];
  12563. } elseif ($listtype == '#') {
  12564. // set default list type for ordered list
  12565. $listtype = 'decimal';
  12566. }
  12567. switch ($listtype) {
  12568. // unordered types
  12569. case 'none': {
  12570. break;
  12571. }
  12572. case 'disc': {
  12573. $fill = 'F';
  12574. }
  12575. case 'circle': {
  12576. $fill .= 'D';
  12577. $r = $size / 6;
  12578. $lspace += (2 * $r);
  12579. if ($this->rtl) {
  12580. $this->x = $this->w - $this->x - $lspace;
  12581. } else {
  12582. $this->x -= $lspace;
  12583. }
  12584. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, $fill, array('color'=>$color), $color, 8);
  12585. break;
  12586. }
  12587. case 'square': {
  12588. $l = $size / 3;
  12589. $lspace += $l;
  12590. if ($this->rtl) {
  12591. $this->x = $this->w - $this->x - $lspace;
  12592. } else {
  12593. $this->x -= $lspace;
  12594. }
  12595. $this->Rect($this->x, ($this->y + (($this->lasth - $l)/ 2)), $l, $l, 'F', array(), $color);
  12596. break;
  12597. }
  12598. // ordered types
  12599. // $this->listcount[$this->listnum];
  12600. // $textitem
  12601. case '1':
  12602. case 'decimal': {
  12603. $textitem = $this->listcount[$this->listnum];
  12604. break;
  12605. }
  12606. case 'decimal-leading-zero': {
  12607. $textitem = sprintf("%02d", $this->listcount[$this->listnum]);
  12608. break;
  12609. }
  12610. case 'i':
  12611. case 'lower-roman': {
  12612. $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
  12613. break;
  12614. }
  12615. case 'I':
  12616. case 'upper-roman': {
  12617. $textitem = $this->intToRoman($this->listcount[$this->listnum]);
  12618. break;
  12619. }
  12620. case 'a':
  12621. case 'lower-alpha':
  12622. case 'lower-latin': {
  12623. $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
  12624. break;
  12625. }
  12626. case 'A':
  12627. case 'upper-alpha':
  12628. case 'upper-latin': {
  12629. $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
  12630. break;
  12631. }
  12632. case 'lower-greek': {
  12633. $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
  12634. break;
  12635. }
  12636. /*
  12637. // Types to be implemented (special handling)
  12638. case 'hebrew': {
  12639. break;
  12640. }
  12641. case 'armenian': {
  12642. break;
  12643. }
  12644. case 'georgian': {
  12645. break;
  12646. }
  12647. case 'cjk-ideographic': {
  12648. break;
  12649. }
  12650. case 'hiragana': {
  12651. break;
  12652. }
  12653. case 'katakana': {
  12654. break;
  12655. }
  12656. case 'hiragana-iroha': {
  12657. break;
  12658. }
  12659. case 'katakana-iroha': {
  12660. break;
  12661. }
  12662. */
  12663. default: {
  12664. $textitem = $this->listcount[$this->listnum];
  12665. }
  12666. }
  12667. if (!$this->empty_string($textitem)) {
  12668. // print ordered item
  12669. if ($this->rtl) {
  12670. $textitem = '.'.$textitem;
  12671. } else {
  12672. $textitem = $textitem.'.';
  12673. }
  12674. $lspace += $this->GetStringWidth($textitem);
  12675. if ($this->rtl) {
  12676. $this->x += $lspace;
  12677. } else {
  12678. $this->x -= $lspace;
  12679. }
  12680. $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
  12681. }
  12682. $this->x = $tmpx;
  12683. $this->lispacer = '';
  12684. }
  12685. /**
  12686. * Returns current graphic variables as array.
  12687. * @return array graphic variables
  12688. * @access protected
  12689. * @since 4.2.010 (2008-11-14)
  12690. */
  12691. protected function getGraphicVars() {
  12692. $grapvars = array(
  12693. 'FontFamily' => $this->FontFamily,
  12694. 'FontStyle' => $this->FontStyle,
  12695. 'FontSizePt' => $this->FontSizePt,
  12696. 'rMargin' => $this->rMargin,
  12697. 'lMargin' => $this->lMargin,
  12698. 'cMargin' => $this->cMargin,
  12699. 'LineWidth' => $this->LineWidth,
  12700. 'linestyleWidth' => $this->linestyleWidth,
  12701. 'linestyleCap' => $this->linestyleCap,
  12702. 'linestyleJoin' => $this->linestyleJoin,
  12703. 'linestyleDash' => $this->linestyleDash,
  12704. 'DrawColor' => $this->DrawColor,
  12705. 'FillColor' => $this->FillColor,
  12706. 'TextColor' => $this->TextColor,
  12707. 'ColorFlag' => $this->ColorFlag,
  12708. 'bgcolor' => $this->bgcolor,
  12709. 'fgcolor' => $this->fgcolor,
  12710. 'htmlvspace' => $this->htmlvspace,
  12711. 'lasth' => $this->lasth
  12712. );
  12713. return $grapvars;
  12714. }
  12715. /**
  12716. * Set graphic variables.
  12717. * @param $gvars array graphic variables
  12718. * @access protected
  12719. * @since 4.2.010 (2008-11-14)
  12720. */
  12721. protected function setGraphicVars($gvars) {
  12722. $this->FontFamily = $gvars['FontFamily'];
  12723. $this->FontStyle = $gvars['FontStyle'];
  12724. $this->FontSizePt = $gvars['FontSizePt'];
  12725. $this->rMargin = $gvars['rMargin'];
  12726. $this->lMargin = $gvars['lMargin'];
  12727. $this->cMargin = $gvars['cMargin'];
  12728. $this->LineWidth = $gvars['LineWidth'];
  12729. $this->linestyleWidth = $gvars['linestyleWidth'];
  12730. $this->linestyleCap = $gvars['linestyleCap'];
  12731. $this->linestyleJoin = $gvars['linestyleJoin'];
  12732. $this->linestyleDash = $gvars['linestyleDash'];
  12733. $this->DrawColor = $gvars['DrawColor'];
  12734. $this->FillColor = $gvars['FillColor'];
  12735. $this->TextColor = $gvars['TextColor'];
  12736. $this->ColorFlag = $gvars['ColorFlag'];
  12737. $this->bgcolor = $gvars['bgcolor'];
  12738. $this->fgcolor = $gvars['fgcolor'];
  12739. $this->htmlvspace = $gvars['htmlvspace'];
  12740. //$this->lasth = $gvars['lasth'];
  12741. $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
  12742. if (!$this->empty_string($this->FontFamily)) {
  12743. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  12744. }
  12745. }
  12746. /**
  12747. * Returns a temporary filename for caching object on filesystem.
  12748. * @param string $prefix prefix to add to filename
  12749. * return string filename.
  12750. * @access protected
  12751. * @since 4.5.000 (2008-12-31)
  12752. */
  12753. protected function getObjFilename($name) {
  12754. return tempnam(K_PATH_CACHE, $name.'_');
  12755. }
  12756. /**
  12757. * Writes data to a temporary file on filesystem.
  12758. * @param string $file file name
  12759. * @param mixed $data data to write on file
  12760. * @param boolean $append if true append data, false replace.
  12761. * @access protected
  12762. * @since 4.5.000 (2008-12-31)
  12763. */
  12764. protected function writeDiskCache($filename, $data, $append=false) {
  12765. if ($append) {
  12766. $fmode = 'ab+';
  12767. } else {
  12768. $fmode = 'wb+';
  12769. }
  12770. $f = @fopen($filename, $fmode);
  12771. if (!$f) {
  12772. $this->Error('Unable to write cache file: '.$filename);
  12773. } else {
  12774. fwrite($f, $data);
  12775. fclose($f);
  12776. }
  12777. // update file lenght (needed for transactions)
  12778. if (!isset($this->cache_file_lenght['_'.$filename])) {
  12779. $this->cache_file_lenght['_'.$filename] = strlen($data);
  12780. } else {
  12781. $this->cache_file_lenght['_'.$filename] += strlen($data);
  12782. }
  12783. }
  12784. /**
  12785. * Read data from a temporary file on filesystem.
  12786. * @param string $file file name
  12787. * @return mixed retrieved data
  12788. * @access protected
  12789. * @since 4.5.000 (2008-12-31)
  12790. */
  12791. protected function readDiskCache($filename) {
  12792. return file_get_contents($filename);
  12793. }
  12794. /**
  12795. * Set buffer content (always append data).
  12796. * @param string $data data
  12797. * @access protected
  12798. * @since 4.5.000 (2009-01-02)
  12799. */
  12800. protected function setBuffer($data) {
  12801. $this->bufferlen += strlen($data);
  12802. if ($this->diskcache) {
  12803. if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
  12804. $this->buffer = $this->getObjFilename('buffer');
  12805. }
  12806. $this->writeDiskCache($this->buffer, $data, true);
  12807. } else {
  12808. $this->buffer .= $data;
  12809. }
  12810. }
  12811. /**
  12812. * Get buffer content.
  12813. * @return string buffer content
  12814. * @access protected
  12815. * @since 4.5.000 (2009-01-02)
  12816. */
  12817. protected function getBuffer() {
  12818. if ($this->diskcache) {
  12819. return $this->readDiskCache($this->buffer);
  12820. } else {
  12821. return $this->buffer;
  12822. }
  12823. }
  12824. /**
  12825. * Set page buffer content.
  12826. * @param int $page page number
  12827. * @param string $data page data
  12828. * @param boolean $append if true append data, false replace.
  12829. * @access protected
  12830. * @since 4.5.000 (2008-12-31)
  12831. */
  12832. protected function setPageBuffer($page, $data, $append=false) {
  12833. if ($this->diskcache) {
  12834. if (!isset($this->pages[$page])) {
  12835. $this->pages[$page] = $this->getObjFilename('page'.$page);
  12836. }
  12837. $this->writeDiskCache($this->pages[$page], $data, $append);
  12838. } else {
  12839. if ($append) {
  12840. $this->pages[$page] .= $data;
  12841. } else {
  12842. $this->pages[$page] = $data;
  12843. }
  12844. }
  12845. if ($append AND isset($this->pagelen[$page])) {
  12846. $this->pagelen[$page] += strlen($data);
  12847. } else {
  12848. $this->pagelen[$page] = strlen($data);
  12849. }
  12850. }
  12851. /**
  12852. * Get page buffer content.
  12853. * @param int $page page number
  12854. * @return string page buffer content or false in case of error
  12855. * @access protected
  12856. * @since 4.5.000 (2008-12-31)
  12857. */
  12858. protected function getPageBuffer($page) {
  12859. if ($this->diskcache) {
  12860. return $this->readDiskCache($this->pages[$page]);
  12861. } elseif (isset($this->pages[$page])) {
  12862. return $this->pages[$page];
  12863. }
  12864. return false;
  12865. }
  12866. /**
  12867. * Set image buffer content.
  12868. * @param string $image image key
  12869. * @param array $data image data
  12870. * @access protected
  12871. * @since 4.5.000 (2008-12-31)
  12872. */
  12873. protected function setImageBuffer($image, $data) {
  12874. if ($this->diskcache) {
  12875. if (!isset($this->images[$image])) {
  12876. $this->images[$image] = $this->getObjFilename('image'.$image);
  12877. }
  12878. $this->writeDiskCache($this->images[$image], serialize($data));
  12879. } else {
  12880. $this->images[$image] = $data;
  12881. }
  12882. if (!in_array($image, $this->imagekeys)) {
  12883. $this->imagekeys[] = $image;
  12884. }
  12885. ++$this->numimages;
  12886. }
  12887. /**
  12888. * Set image buffer content.
  12889. * @param string $image image key
  12890. * @param string $key image sub-key
  12891. * @param array $data image data
  12892. * @access protected
  12893. * @since 4.5.000 (2008-12-31)
  12894. */
  12895. protected function setImageSubBuffer($image, $key, $data) {
  12896. if (!isset($this->images[$image])) {
  12897. $this->setImageBuffer($image, array());
  12898. }
  12899. if ($this->diskcache) {
  12900. $tmpimg = $this->getImageBuffer($image);
  12901. $tmpimg[$key] = $data;
  12902. $this->writeDiskCache($this->images[$image], serialize($tmpimg));
  12903. } else {
  12904. $this->images[$image][$key] = $data;
  12905. }
  12906. }
  12907. /**
  12908. * Get page buffer content.
  12909. * @param string $image image key
  12910. * @return string image buffer content or false in case of error
  12911. * @access protected
  12912. * @since 4.5.000 (2008-12-31)
  12913. */
  12914. protected function getImageBuffer($image) {
  12915. if ($this->diskcache AND isset($this->images[$image])) {
  12916. return unserialize($this->readDiskCache($this->images[$image]));
  12917. } elseif (isset($this->images[$image])) {
  12918. return $this->images[$image];
  12919. }
  12920. return false;
  12921. }
  12922. /**
  12923. * Set font buffer content.
  12924. * @param string $font font key
  12925. * @param array $data font data
  12926. * @access protected
  12927. * @since 4.5.000 (2009-01-02)
  12928. */
  12929. protected function setFontBuffer($font, $data) {
  12930. if ($this->diskcache) {
  12931. if (!isset($this->fonts[$font])) {
  12932. $this->fonts[$font] = $this->getObjFilename('font');
  12933. }
  12934. $this->writeDiskCache($this->fonts[$font], serialize($data));
  12935. } else {
  12936. $this->fonts[$font] = $data;
  12937. }
  12938. if (!in_array($font, $this->fontkeys)) {
  12939. $this->fontkeys[] = $font;
  12940. }
  12941. }
  12942. /**
  12943. * Set font buffer content.
  12944. * @param string $font font key
  12945. * @param string $key font sub-key
  12946. * @param array $data font data
  12947. * @access protected
  12948. * @since 4.5.000 (2009-01-02)
  12949. */
  12950. protected function setFontSubBuffer($font, $key, $data) {
  12951. if (!isset($this->fonts[$font])) {
  12952. $this->setFontBuffer($font, array());
  12953. }
  12954. if ($this->diskcache) {
  12955. $tmpfont = $this->getFontBuffer($font);
  12956. $tmpfont[$key] = $data;
  12957. $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
  12958. } else {
  12959. $this->fonts[$font][$key] = $data;
  12960. }
  12961. }
  12962. /**
  12963. * Get font buffer content.
  12964. * @param string $font font key
  12965. * @return string font buffer content or false in case of error
  12966. * @access protected
  12967. * @since 4.5.000 (2009-01-02)
  12968. */
  12969. protected function getFontBuffer($font) {
  12970. if ($this->diskcache AND isset($this->fonts[$font])) {
  12971. return unserialize($this->readDiskCache($this->fonts[$font]));
  12972. } elseif (isset($this->fonts[$font])) {
  12973. return $this->fonts[$font];
  12974. }
  12975. return false;
  12976. }
  12977. /**
  12978. * Move a page to a previous position.
  12979. * @param int $frompage number of the source page
  12980. * @param int $topage number of the destination page (must be less than $frompage)
  12981. * @return true in case of success, false in case of error.
  12982. * @access public
  12983. * @since 4.5.000 (2009-01-02)
  12984. */
  12985. public function movePage($frompage, $topage) {
  12986. if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
  12987. return false;
  12988. }
  12989. if ($frompage == $this->page) {
  12990. // close the page before moving it
  12991. $this->endPage();
  12992. }
  12993. // move all page-related states
  12994. $tmppage = $this->pages[$frompage];
  12995. $tmppagedim = $this->pagedim[$frompage];
  12996. $tmppagelen = $this->pagelen[$frompage];
  12997. $tmpintmrk = $this->intmrk[$frompage];
  12998. if (isset($this->footerpos[$frompage])) {
  12999. $tmpfooterpos = $this->footerpos[$frompage];
  13000. }
  13001. if (isset($this->footerlen[$frompage])) {
  13002. $tmpfooterlen = $this->footerlen[$frompage];
  13003. }
  13004. if (isset($this->transfmrk[$frompage])) {
  13005. $tmptransfmrk = $this->transfmrk[$frompage];
  13006. }
  13007. if (isset($this->PageAnnots[$frompage])) {
  13008. $tmpannots = $this->PageAnnots[$frompage];
  13009. }
  13010. if (isset($this->newpagegroup[$frompage])) {
  13011. $tmpnewpagegroup = $this->newpagegroup[$frompage];
  13012. }
  13013. for ($i = $frompage; $i > $topage; --$i) {
  13014. $j = $i - 1;
  13015. // shift pages down
  13016. $this->pages[$i] = $this->pages[$j];
  13017. $this->pagedim[$i] = $this->pagedim[$j];
  13018. $this->pagelen[$i] = $this->pagelen[$j];
  13019. $this->intmrk[$i] = $this->intmrk[$j];
  13020. if (isset($this->footerpos[$j])) {
  13021. $this->footerpos[$i] = $this->footerpos[$j];
  13022. } elseif (isset($this->footerpos[$i])) {
  13023. unset($this->footerpos[$i]);
  13024. }
  13025. if (isset($this->footerlen[$j])) {
  13026. $this->footerlen[$i] = $this->footerlen[$j];
  13027. } elseif (isset($this->footerlen[$i])) {
  13028. unset($this->footerlen[$i]);
  13029. }
  13030. if (isset($this->transfmrk[$j])) {
  13031. $this->transfmrk[$i] = $this->transfmrk[$j];
  13032. } elseif (isset($this->transfmrk[$i])) {
  13033. unset($this->transfmrk[$i]);
  13034. }
  13035. if (isset($this->PageAnnots[$j])) {
  13036. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  13037. } elseif (isset($this->PageAnnots[$i])) {
  13038. unset($this->PageAnnots[$i]);
  13039. }
  13040. if (isset($this->newpagegroup[$j])) {
  13041. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  13042. } elseif (isset($this->newpagegroup[$i])) {
  13043. unset($this->newpagegroup[$i]);
  13044. }
  13045. }
  13046. $this->pages[$topage] = $tmppage;
  13047. $this->pagedim[$topage] = $tmppagedim;
  13048. $this->pagelen[$topage] = $tmppagelen;
  13049. $this->intmrk[$topage] = $tmpintmrk;
  13050. if (isset($tmpfooterpos)) {
  13051. $this->footerpos[$topage] = $tmpfooterpos;
  13052. } elseif (isset($this->footerpos[$topage])) {
  13053. unset($this->footerpos[$topage]);
  13054. }
  13055. if (isset($tmpfooterlen)) {
  13056. $this->footerlen[$topage] = $tmpfooterlen;
  13057. } elseif (isset($this->footerlen[$topage])) {
  13058. unset($this->footerlen[$topage]);
  13059. }
  13060. if (isset($tmptransfmrk)) {
  13061. $this->transfmrk[$topage] = $tmptransfmrk;
  13062. } elseif (isset($this->transfmrk[$topage])) {
  13063. unset($this->transfmrk[$topage]);
  13064. }
  13065. if (isset($tmpannots)) {
  13066. $this->PageAnnots[$topage] = $tmpannots;
  13067. } elseif (isset($this->PageAnnots[$topage])) {
  13068. unset($this->PageAnnots[$topage]);
  13069. }
  13070. if (isset($tmpnewpagegroup)) {
  13071. $this->newpagegroup[$topage] = $tmpnewpagegroup;
  13072. } elseif (isset($this->newpagegroup[$topage])) {
  13073. unset($this->newpagegroup[$topage]);
  13074. }
  13075. // adjust outlines
  13076. $tmpoutlines = $this->outlines;
  13077. foreach ($tmpoutlines as $key => $outline) {
  13078. if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
  13079. $this->outlines[$key]['p'] = $outline['p'] + 1;
  13080. } elseif ($outline['p'] == $frompage) {
  13081. $this->outlines[$key]['p'] = $topage;
  13082. }
  13083. }
  13084. // adjust links
  13085. $tmplinks = $this->links;
  13086. foreach ($tmplinks as $key => $link) {
  13087. if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
  13088. $this->links[$key][0] = $link[0] + 1;
  13089. } elseif ($link[0] == $frompage) {
  13090. $this->links[$key][0] = $topage;
  13091. }
  13092. }
  13093. // adjust javascript
  13094. $tmpjavascript = $this->javascript;
  13095. global $jfrompage, $jtopage;
  13096. $jfrompage = $frompage;
  13097. $jtopage = $topage;
  13098. $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
  13099. create_function('$matches', 'global $jfrompage, $jtopage;
  13100. $pagenum = intval($matches[3]) + 1;
  13101. if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
  13102. $newpage = ($pagenum + 1);
  13103. } elseif ($pagenum == $jfrompage) {
  13104. $newpage = $jtopage;
  13105. } else {
  13106. $newpage = $pagenum;
  13107. }
  13108. --$newpage;
  13109. return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
  13110. // return to last page
  13111. $this->lastPage(true);
  13112. return true;
  13113. }
  13114. /**
  13115. * Remove the specified page.
  13116. * @param int $page page to remove
  13117. * @return true in case of success, false in case of error.
  13118. * @access public
  13119. * @since 4.6.004 (2009-04-23)
  13120. */
  13121. public function deletePage($page) {
  13122. if ($page > $this->numpages) {
  13123. return false;
  13124. }
  13125. // delete current page
  13126. unset($this->pages[$page]);
  13127. unset($this->pagedim[$page]);
  13128. unset($this->pagelen[$page]);
  13129. unset($this->intmrk[$page]);
  13130. if (isset($this->footerpos[$page])) {
  13131. unset($this->footerpos[$page]);
  13132. }
  13133. if (isset($this->footerlen[$page])) {
  13134. unset($this->footerlen[$page]);
  13135. }
  13136. if (isset($this->transfmrk[$page])) {
  13137. unset($this->transfmrk[$page]);
  13138. }
  13139. if (isset($this->PageAnnots[$page])) {
  13140. unset($this->PageAnnots[$page]);
  13141. }
  13142. if (isset($thi