PageRenderTime 137ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/tcpdf/tcpdf.php

http://github.com/moodle/moodle
PHP | 13907 lines | 8473 code | 556 blank | 4878 comment | 1757 complexity | b384cf9e37aedd36c736919085cd2463 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. //============================================================+
  3. // File name : tcpdf.php
  4. // Version : 6.3.2
  5. // Begin : 2002-08-03
  6. // Last Update : 2019-09-20
  7. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  8. // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2002-2019 Nicola Asuni - Tecnick.com LTD
  11. //
  12. // This file is part of TCPDF software library.
  13. //
  14. // TCPDF is free software: you can redistribute it and/or modify it
  15. // under the terms of the GNU Lesser General Public License as
  16. // published by the Free Software Foundation, either version 3 of the
  17. // License, or (at your option) any later version.
  18. //
  19. // TCPDF is distributed in the hope that it will be useful, but
  20. // WITHOUT ANY WARRANTY; without even the implied warranty of
  21. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  22. // See the GNU Lesser General Public License for more details.
  23. //
  24. // You should have received a copy of the License
  25. // along with TCPDF. If not, see
  26. // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
  27. //
  28. // See LICENSE.TXT file for more information.
  29. // -------------------------------------------------------------------
  30. //
  31. // Description :
  32. // This is a PHP class for generating PDF documents without requiring external extensions.
  33. //
  34. // NOTE:
  35. // This class was originally derived in 2002 from the Public
  36. // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
  37. // but now is almost entirely rewritten and contains thousands of
  38. // new lines of code and hundreds new features.
  39. //
  40. // Main features:
  41. // * no external libraries are required for the basic functions;
  42. // * all standard page formats, custom page formats, custom margins and units of measure;
  43. // * UTF-8 Unicode and Right-To-Left languages;
  44. // * TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
  45. // * font subsetting;
  46. // * methods to publish some XHTML + CSS code, Javascript and Forms;
  47. // * images, graphic (geometric figures) and transformation methods;
  48. // * supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)
  49. // * 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
  50. // * JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
  51. // * automatic page header and footer management;
  52. // * document encryption up to 256 bit and digital signature certifications;
  53. // * transactions to UNDO commands;
  54. // * PDF annotations, including links, text and file attachments;
  55. // * text rendering modes (fill, stroke and clipping);
  56. // * multiple columns mode;
  57. // * no-write page regions;
  58. // * bookmarks, named destinations and table of content;
  59. // * text hyphenation;
  60. // * text stretching and spacing (tracking);
  61. // * automatic page break, line break and text alignments including justification;
  62. // * automatic page numbering and page groups;
  63. // * move and delete pages;
  64. // * page compression (requires php-zlib extension);
  65. // * XOBject Templates;
  66. // * Layers and object visibility.
  67. // * PDF/A-1b support
  68. //============================================================+
  69. /**
  70. * @file
  71. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  72. * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
  73. * <h3>TCPDF main features are:</h3>
  74. * <ul>
  75. * <li>no external libraries are required for the basic functions;</li>
  76. * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
  77. * <li>UTF-8 Unicode and Right-To-Left languages;</li>
  78. * <li>TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
  79. * <li>font subsetting;</li>
  80. * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
  81. * <li>images, graphic (geometric figures) and transformation methods;
  82. * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)</li>
  83. * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;</li>
  84. * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
  85. * <li>automatic page header and footer management;</li>
  86. * <li>document encryption up to 256 bit and digital signature certifications;</li>
  87. * <li>transactions to UNDO commands;</li>
  88. * <li>PDF annotations, including links, text and file attachments;</li>
  89. * <li>text rendering modes (fill, stroke and clipping);</li>
  90. * <li>multiple columns mode;</li>
  91. * <li>no-write page regions;</li>
  92. * <li>bookmarks, named destinations and table of content;</li>
  93. * <li>text hyphenation;</li>
  94. * <li>text stretching and spacing (tracking);</li>
  95. * <li>automatic page break, line break and text alignments including justification;</li>
  96. * <li>automatic page numbering and page groups;</li>
  97. * <li>move and delete pages;</li>
  98. * <li>page compression (requires php-zlib extension);</li>
  99. * <li>XOBject Templates;</li>
  100. * <li>Layers and object visibility;</li>
  101. * <li>PDF/A-1b support.</li>
  102. * </ul>
  103. * Tools to encode your unicode fonts are on fonts/utils directory.</p>
  104. * @package com.tecnick.tcpdf
  105. * @author Nicola Asuni
  106. * @version 6.3.2
  107. */
  108. // TCPDF configuration
  109. require_once(dirname(__FILE__).'/tcpdf_autoconfig.php');
  110. // TCPDF static font methods and data
  111. require_once(dirname(__FILE__).'/include/tcpdf_font_data.php');
  112. // TCPDF static font methods and data
  113. require_once(dirname(__FILE__).'/include/tcpdf_fonts.php');
  114. // TCPDF static color methods and data
  115. require_once(dirname(__FILE__).'/include/tcpdf_colors.php');
  116. // TCPDF static image methods and data
  117. require_once(dirname(__FILE__).'/include/tcpdf_images.php');
  118. // TCPDF static methods and data
  119. require_once(dirname(__FILE__).'/include/tcpdf_static.php');
  120. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  121. /**
  122. * @class TCPDF
  123. * PHP class for generating PDF documents without requiring external extensions.
  124. * TCPDF project (http://www.tcpdf.org) has been originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
  125. * @package com.tecnick.tcpdf
  126. * @brief PHP class for generating PDF documents without requiring external extensions.
  127. * @version 6.3.2
  128. * @author Nicola Asuni - info@tecnick.com
  129. * @IgnoreAnnotation("protected")
  130. * @IgnoreAnnotation("public")
  131. * @IgnoreAnnotation("pre")
  132. */
  133. class TCPDF {
  134. // Protected properties
  135. /**
  136. * Current page number.
  137. * @protected
  138. */
  139. protected $page;
  140. /**
  141. * Current object number.
  142. * @protected
  143. */
  144. protected $n;
  145. /**
  146. * Array of object offsets.
  147. * @protected
  148. */
  149. protected $offsets = array();
  150. /**
  151. * Array of object IDs for each page.
  152. * @protected
  153. */
  154. protected $pageobjects = array();
  155. /**
  156. * Buffer holding in-memory PDF.
  157. * @protected
  158. */
  159. protected $buffer;
  160. /**
  161. * Array containing pages.
  162. * @protected
  163. */
  164. protected $pages = array();
  165. /**
  166. * Current document state.
  167. * @protected
  168. */
  169. protected $state;
  170. /**
  171. * Compression flag.
  172. * @protected
  173. */
  174. protected $compress;
  175. /**
  176. * Current page orientation (P = Portrait, L = Landscape).
  177. * @protected
  178. */
  179. protected $CurOrientation;
  180. /**
  181. * Page dimensions.
  182. * @protected
  183. */
  184. protected $pagedim = array();
  185. /**
  186. * Scale factor (number of points in user unit).
  187. * @protected
  188. */
  189. protected $k;
  190. /**
  191. * Width of page format in points.
  192. * @protected
  193. */
  194. protected $fwPt;
  195. /**
  196. * Height of page format in points.
  197. * @protected
  198. */
  199. protected $fhPt;
  200. /**
  201. * Current width of page in points.
  202. * @protected
  203. */
  204. protected $wPt;
  205. /**
  206. * Current height of page in points.
  207. * @protected
  208. */
  209. protected $hPt;
  210. /**
  211. * Current width of page in user unit.
  212. * @protected
  213. */
  214. protected $w;
  215. /**
  216. * Current height of page in user unit.
  217. * @protected
  218. */
  219. protected $h;
  220. /**
  221. * Left margin.
  222. * @protected
  223. */
  224. protected $lMargin;
  225. /**
  226. * Right margin.
  227. * @protected
  228. */
  229. protected $rMargin;
  230. /**
  231. * Cell left margin (used by regions).
  232. * @protected
  233. */
  234. protected $clMargin;
  235. /**
  236. * Cell right margin (used by regions).
  237. * @protected
  238. */
  239. protected $crMargin;
  240. /**
  241. * Top margin.
  242. * @protected
  243. */
  244. protected $tMargin;
  245. /**
  246. * Page break margin.
  247. * @protected
  248. */
  249. protected $bMargin;
  250. /**
  251. * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  252. * @since 5.9.000 (2010-10-03)
  253. * @protected
  254. */
  255. protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  256. /**
  257. * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  258. * @since 5.9.000 (2010-10-04)
  259. * @protected
  260. */
  261. protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  262. /**
  263. * Current horizontal position in user unit for cell positioning.
  264. * @protected
  265. */
  266. protected $x;
  267. /**
  268. * Current vertical position in user unit for cell positioning.
  269. * @protected
  270. */
  271. protected $y;
  272. /**
  273. * Height of last cell printed.
  274. * @protected
  275. */
  276. protected $lasth;
  277. /**
  278. * Line width in user unit.
  279. * @protected
  280. */
  281. protected $LineWidth;
  282. /**
  283. * Array of standard font names.
  284. * @protected
  285. */
  286. protected $CoreFonts;
  287. /**
  288. * Array of used fonts.
  289. * @protected
  290. */
  291. protected $fonts = array();
  292. /**
  293. * Array of font files.
  294. * @protected
  295. */
  296. protected $FontFiles = array();
  297. /**
  298. * Array of encoding differences.
  299. * @protected
  300. */
  301. protected $diffs = array();
  302. /**
  303. * Array of used images.
  304. * @protected
  305. */
  306. protected $images = array();
  307. /**
  308. * Depth of the svg tag, to keep track if the svg tag is a subtag or the root tag.
  309. * @protected
  310. */
  311. protected $svg_tag_depth = 0;
  312. /**
  313. * Array of Annotations in pages.
  314. * @protected
  315. */
  316. protected $PageAnnots = array();
  317. /**
  318. * Array of internal links.
  319. * @protected
  320. */
  321. protected $links = array();
  322. /**
  323. * Current font family.
  324. * @protected
  325. */
  326. protected $FontFamily;
  327. /**
  328. * Current font style.
  329. * @protected
  330. */
  331. protected $FontStyle;
  332. /**
  333. * Current font ascent (distance between font top and baseline).
  334. * @protected
  335. * @since 2.8.000 (2007-03-29)
  336. */
  337. protected $FontAscent;
  338. /**
  339. * Current font descent (distance between font bottom and baseline).
  340. * @protected
  341. * @since 2.8.000 (2007-03-29)
  342. */
  343. protected $FontDescent;
  344. /**
  345. * Underlining flag.
  346. * @protected
  347. */
  348. protected $underline;
  349. /**
  350. * Overlining flag.
  351. * @protected
  352. */
  353. protected $overline;
  354. /**
  355. * Current font info.
  356. * @protected
  357. */
  358. protected $CurrentFont;
  359. /**
  360. * Current font size in points.
  361. * @protected
  362. */
  363. protected $FontSizePt;
  364. /**
  365. * Current font size in user unit.
  366. * @protected
  367. */
  368. protected $FontSize;
  369. /**
  370. * Commands for drawing color.
  371. * @protected
  372. */
  373. protected $DrawColor;
  374. /**
  375. * Commands for filling color.
  376. * @protected
  377. */
  378. protected $FillColor;
  379. /**
  380. * Commands for text color.
  381. * @protected
  382. */
  383. protected $TextColor;
  384. /**
  385. * Indicates whether fill and text colors are different.
  386. * @protected
  387. */
  388. protected $ColorFlag;
  389. /**
  390. * Automatic page breaking.
  391. * @protected
  392. */
  393. protected $AutoPageBreak;
  394. /**
  395. * Threshold used to trigger page breaks.
  396. * @protected
  397. */
  398. protected $PageBreakTrigger;
  399. /**
  400. * Flag set when processing page header.
  401. * @protected
  402. */
  403. protected $InHeader = false;
  404. /**
  405. * Flag set when processing page footer.
  406. * @protected
  407. */
  408. protected $InFooter = false;
  409. /**
  410. * Zoom display mode.
  411. * @protected
  412. */
  413. protected $ZoomMode;
  414. /**
  415. * Layout display mode.
  416. * @protected
  417. */
  418. protected $LayoutMode;
  419. /**
  420. * If true set the document information dictionary in Unicode.
  421. * @protected
  422. */
  423. protected $docinfounicode = true;
  424. /**
  425. * Document title.
  426. * @protected
  427. */
  428. protected $title = '';
  429. /**
  430. * Document subject.
  431. * @protected
  432. */
  433. protected $subject = '';
  434. /**
  435. * Document author.
  436. * @protected
  437. */
  438. protected $author = '';
  439. /**
  440. * Document keywords.
  441. * @protected
  442. */
  443. protected $keywords = '';
  444. /**
  445. * Document creator.
  446. * @protected
  447. */
  448. protected $creator = '';
  449. /**
  450. * Starting page number.
  451. * @protected
  452. */
  453. protected $starting_page_number = 1;
  454. /**
  455. * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
  456. * @since 2002-07-31
  457. * @author Nicola Asuni
  458. * @protected
  459. */
  460. protected $img_rb_x;
  461. /**
  462. * The right-bottom corner Y coordinate of last inserted image.
  463. * @since 2002-07-31
  464. * @author Nicola Asuni
  465. * @protected
  466. */
  467. protected $img_rb_y;
  468. /**
  469. * Adjusting factor to convert pixels to user units.
  470. * @since 2004-06-14
  471. * @author Nicola Asuni
  472. * @protected
  473. */
  474. protected $imgscale = 1;
  475. /**
  476. * Boolean flag set to true when the input text is unicode (require unicode fonts).
  477. * @since 2005-01-02
  478. * @author Nicola Asuni
  479. * @protected
  480. */
  481. protected $isunicode = false;
  482. /**
  483. * PDF version.
  484. * @since 1.5.3
  485. * @protected
  486. */
  487. protected $PDFVersion = '1.7';
  488. /**
  489. * ID of the stored default header template (-1 = not set).
  490. * @protected
  491. */
  492. protected $header_xobjid = false;
  493. /**
  494. * If true reset the Header Xobject template at each page
  495. * @protected
  496. */
  497. protected $header_xobj_autoreset = false;
  498. /**
  499. * Minimum distance between header and top page margin.
  500. * @protected
  501. */
  502. protected $header_margin;
  503. /**
  504. * Minimum distance between footer and bottom page margin.
  505. * @protected
  506. */
  507. protected $footer_margin;
  508. /**
  509. * Original left margin value.
  510. * @protected
  511. * @since 1.53.0.TC013
  512. */
  513. protected $original_lMargin;
  514. /**
  515. * Original right margin value.
  516. * @protected
  517. * @since 1.53.0.TC013
  518. */
  519. protected $original_rMargin;
  520. /**
  521. * Default font used on page header.
  522. * @protected
  523. */
  524. protected $header_font;
  525. /**
  526. * Default font used on page footer.
  527. * @protected
  528. */
  529. protected $footer_font;
  530. /**
  531. * Language templates.
  532. * @protected
  533. */
  534. protected $l;
  535. /**
  536. * Barcode to print on page footer (only if set).
  537. * @protected
  538. */
  539. protected $barcode = false;
  540. /**
  541. * Boolean flag to print/hide page header.
  542. * @protected
  543. */
  544. protected $print_header = true;
  545. /**
  546. * Boolean flag to print/hide page footer.
  547. * @protected
  548. */
  549. protected $print_footer = true;
  550. /**
  551. * Header image logo.
  552. * @protected
  553. */
  554. protected $header_logo = '';
  555. /**
  556. * Width of header image logo in user units.
  557. * @protected
  558. */
  559. protected $header_logo_width = 30;
  560. /**
  561. * Title to be printed on default page header.
  562. * @protected
  563. */
  564. protected $header_title = '';
  565. /**
  566. * String to pring on page header after title.
  567. * @protected
  568. */
  569. protected $header_string = '';
  570. /**
  571. * Color for header text (RGB array).
  572. * @since 5.9.174 (2012-07-25)
  573. * @protected
  574. */
  575. protected $header_text_color = array(0,0,0);
  576. /**
  577. * Color for header line (RGB array).
  578. * @since 5.9.174 (2012-07-25)
  579. * @protected
  580. */
  581. protected $header_line_color = array(0,0,0);
  582. /**
  583. * Color for footer text (RGB array).
  584. * @since 5.9.174 (2012-07-25)
  585. * @protected
  586. */
  587. protected $footer_text_color = array(0,0,0);
  588. /**
  589. * Color for footer line (RGB array).
  590. * @since 5.9.174 (2012-07-25)
  591. * @protected
  592. */
  593. protected $footer_line_color = array(0,0,0);
  594. /**
  595. * Text shadow data array.
  596. * @since 5.9.174 (2012-07-25)
  597. * @protected
  598. */
  599. protected $txtshadow = array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal');
  600. /**
  601. * Default number of columns for html table.
  602. * @protected
  603. */
  604. protected $default_table_columns = 4;
  605. // variables for html parser
  606. /**
  607. * HTML PARSER: array to store current link and rendering styles.
  608. * @protected
  609. */
  610. protected $HREF = array();
  611. /**
  612. * List of available fonts on filesystem.
  613. * @protected
  614. */
  615. protected $fontlist = array();
  616. /**
  617. * Current foreground color.
  618. * @protected
  619. */
  620. protected $fgcolor;
  621. /**
  622. * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
  623. * @protected
  624. */
  625. protected $listordered = array();
  626. /**
  627. * HTML PARSER: array count list items on nested lists.
  628. * @protected
  629. */
  630. protected $listcount = array();
  631. /**
  632. * HTML PARSER: current list nesting level.
  633. * @protected
  634. */
  635. protected $listnum = 0;
  636. /**
  637. * HTML PARSER: indent amount for lists.
  638. * @protected
  639. */
  640. protected $listindent = 0;
  641. /**
  642. * HTML PARSER: current list indententation level.
  643. * @protected
  644. */
  645. protected $listindentlevel = 0;
  646. /**
  647. * Current background color.
  648. * @protected
  649. */
  650. protected $bgcolor;
  651. /**
  652. * Temporary font size in points.
  653. * @protected
  654. */
  655. protected $tempfontsize = 10;
  656. /**
  657. * Spacer string for LI tags.
  658. * @protected
  659. */
  660. protected $lispacer = '';
  661. /**
  662. * Default encoding.
  663. * @protected
  664. * @since 1.53.0.TC010
  665. */
  666. protected $encoding = 'UTF-8';
  667. /**
  668. * PHP internal encoding.
  669. * @protected
  670. * @since 1.53.0.TC016
  671. */
  672. protected $internal_encoding;
  673. /**
  674. * Boolean flag to indicate if the document language is Right-To-Left.
  675. * @protected
  676. * @since 2.0.000
  677. */
  678. protected $rtl = false;
  679. /**
  680. * Boolean flag used to force RTL or LTR string direction.
  681. * @protected
  682. * @since 2.0.000
  683. */
  684. protected $tmprtl = false;
  685. // --- Variables used for document encryption:
  686. /**
  687. * IBoolean flag indicating whether document is protected.
  688. * @protected
  689. * @since 2.0.000 (2008-01-02)
  690. */
  691. protected $encrypted;
  692. /**
  693. * Array containing encryption settings.
  694. * @protected
  695. * @since 5.0.005 (2010-05-11)
  696. */
  697. protected $encryptdata = array();
  698. /**
  699. * Last RC4 key encrypted (cached for optimisation).
  700. * @protected
  701. * @since 2.0.000 (2008-01-02)
  702. */
  703. protected $last_enc_key;
  704. /**
  705. * Last RC4 computed key.
  706. * @protected
  707. * @since 2.0.000 (2008-01-02)
  708. */
  709. protected $last_enc_key_c;
  710. /**
  711. * File ID (used on document trailer).
  712. * @protected
  713. * @since 5.0.005 (2010-05-12)
  714. */
  715. protected $file_id;
  716. // --- bookmark ---
  717. /**
  718. * Outlines for bookmark.
  719. * @protected
  720. * @since 2.1.002 (2008-02-12)
  721. */
  722. protected $outlines = array();
  723. /**
  724. * Outline root for bookmark.
  725. * @protected
  726. * @since 2.1.002 (2008-02-12)
  727. */
  728. protected $OutlineRoot;
  729. // --- javascript and form ---
  730. /**
  731. * Javascript code.
  732. * @protected
  733. * @since 2.1.002 (2008-02-12)
  734. */
  735. protected $javascript = '';
  736. /**
  737. * Javascript counter.
  738. * @protected
  739. * @since 2.1.002 (2008-02-12)
  740. */
  741. protected $n_js;
  742. /**
  743. * line through state
  744. * @protected
  745. * @since 2.8.000 (2008-03-19)
  746. */
  747. protected $linethrough;
  748. /**
  749. * Array with additional document-wide usage rights for the document.
  750. * @protected
  751. * @since 5.8.014 (2010-08-23)
  752. */
  753. protected $ur = array();
  754. /**
  755. * DPI (Dot Per Inch) Document Resolution (do not change).
  756. * @protected
  757. * @since 3.0.000 (2008-03-27)
  758. */
  759. protected $dpi = 72;
  760. /**
  761. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  762. * @protected
  763. * @since 3.0.000 (2008-03-27)
  764. */
  765. protected $newpagegroup = array();
  766. /**
  767. * Array that contains the number of pages in each page group.
  768. * @protected
  769. * @since 3.0.000 (2008-03-27)
  770. */
  771. protected $pagegroups = array();
  772. /**
  773. * Current page group number.
  774. * @protected
  775. * @since 3.0.000 (2008-03-27)
  776. */
  777. protected $currpagegroup = 0;
  778. /**
  779. * Array of transparency objects and parameters.
  780. * @protected
  781. * @since 3.0.000 (2008-03-27)
  782. */
  783. protected $extgstates;
  784. /**
  785. * Set the default JPEG compression quality (1-100).
  786. * @protected
  787. * @since 3.0.000 (2008-03-27)
  788. */
  789. protected $jpeg_quality;
  790. /**
  791. * Default cell height ratio.
  792. * @protected
  793. * @since 3.0.014 (2008-05-23)
  794. */
  795. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  796. /**
  797. * PDF viewer preferences.
  798. * @protected
  799. * @since 3.1.000 (2008-06-09)
  800. */
  801. protected $viewer_preferences;
  802. /**
  803. * A name object specifying how the document should be displayed when opened.
  804. * @protected
  805. * @since 3.1.000 (2008-06-09)
  806. */
  807. protected $PageMode;
  808. /**
  809. * Array for storing gradient information.
  810. * @protected
  811. * @since 3.1.000 (2008-06-09)
  812. */
  813. protected $gradients = array();
  814. /**
  815. * Array used to store positions inside the pages buffer (keys are the page numbers).
  816. * @protected
  817. * @since 3.2.000 (2008-06-26)
  818. */
  819. protected $intmrk = array();
  820. /**
  821. * Array used to store positions inside the pages buffer (keys are the page numbers).
  822. * @protected
  823. * @since 5.7.000 (2010-08-03)
  824. */
  825. protected $bordermrk = array();
  826. /**
  827. * Array used to store page positions to track empty pages (keys are the page numbers).
  828. * @protected
  829. * @since 5.8.007 (2010-08-18)
  830. */
  831. protected $emptypagemrk = array();
  832. /**
  833. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  834. * @protected
  835. * @since 4.6.021 (2009-07-20)
  836. */
  837. protected $cntmrk = array();
  838. /**
  839. * Array used to store footer positions of each page.
  840. * @protected
  841. * @since 3.2.000 (2008-07-01)
  842. */
  843. protected $footerpos = array();
  844. /**
  845. * Array used to store footer length of each page.
  846. * @protected
  847. * @since 4.0.014 (2008-07-29)
  848. */
  849. protected $footerlen = array();
  850. /**
  851. * Boolean flag to indicate if a new line is created.
  852. * @protected
  853. * @since 3.2.000 (2008-07-01)
  854. */
  855. protected $newline = true;
  856. /**
  857. * End position of the latest inserted line.
  858. * @protected
  859. * @since 3.2.000 (2008-07-01)
  860. */
  861. protected $endlinex = 0;
  862. /**
  863. * PDF string for width value of the last line.
  864. * @protected
  865. * @since 4.0.006 (2008-07-16)
  866. */
  867. protected $linestyleWidth = '';
  868. /**
  869. * PDF string for CAP value of the last line.
  870. * @protected
  871. * @since 4.0.006 (2008-07-16)
  872. */
  873. protected $linestyleCap = '0 J';
  874. /**
  875. * PDF string for join value of the last line.
  876. * @protected
  877. * @since 4.0.006 (2008-07-16)
  878. */
  879. protected $linestyleJoin = '0 j';
  880. /**
  881. * PDF string for dash value of the last line.
  882. * @protected
  883. * @since 4.0.006 (2008-07-16)
  884. */
  885. protected $linestyleDash = '[] 0 d';
  886. /**
  887. * Boolean flag to indicate if marked-content sequence is open.
  888. * @protected
  889. * @since 4.0.013 (2008-07-28)
  890. */
  891. protected $openMarkedContent = false;
  892. /**
  893. * Count the latest inserted vertical spaces on HTML.
  894. * @protected
  895. * @since 4.0.021 (2008-08-24)
  896. */
  897. protected $htmlvspace = 0;
  898. /**
  899. * Array of Spot colors.
  900. * @protected
  901. * @since 4.0.024 (2008-09-12)
  902. */
  903. protected $spot_colors = array();
  904. /**
  905. * Symbol used for HTML unordered list items.
  906. * @protected
  907. * @since 4.0.028 (2008-09-26)
  908. */
  909. protected $lisymbol = '';
  910. /**
  911. * String used to mark the beginning and end of EPS image blocks.
  912. * @protected
  913. * @since 4.1.000 (2008-10-18)
  914. */
  915. protected $epsmarker = 'x#!#EPS#!#x';
  916. /**
  917. * Array of transformation matrix.
  918. * @protected
  919. * @since 4.2.000 (2008-10-29)
  920. */
  921. protected $transfmatrix = array();
  922. /**
  923. * Current key for transformation matrix.
  924. * @protected
  925. * @since 4.8.005 (2009-09-17)
  926. */
  927. protected $transfmatrix_key = 0;
  928. /**
  929. * Booklet mode for double-sided pages.
  930. * @protected
  931. * @since 4.2.000 (2008-10-29)
  932. */
  933. protected $booklet = false;
  934. /**
  935. * Epsilon value used for float calculations.
  936. * @protected
  937. * @since 4.2.000 (2008-10-29)
  938. */
  939. protected $feps = 0.005;
  940. /**
  941. * Array used for custom vertical spaces for HTML tags.
  942. * @protected
  943. * @since 4.2.001 (2008-10-30)
  944. */
  945. protected $tagvspaces = array();
  946. /**
  947. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  948. * @protected
  949. * @since 4.2.007 (2008-11-12)
  950. */
  951. protected $customlistindent = -1;
  952. /**
  953. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  954. * @protected
  955. * @since 4.2.010 (2008-11-14)
  956. */
  957. protected $opencell = true;
  958. /**
  959. * Array of files to embedd.
  960. * @protected
  961. * @since 4.4.000 (2008-12-07)
  962. */
  963. protected $embeddedfiles = array();
  964. /**
  965. * Boolean flag to indicate if we are inside a PRE tag.
  966. * @protected
  967. * @since 4.4.001 (2008-12-08)
  968. */
  969. protected $premode = false;
  970. /**
  971. * Array used to store positions of graphics transformation blocks inside the page buffer.
  972. * keys are the page numbers
  973. * @protected
  974. * @since 4.4.002 (2008-12-09)
  975. */
  976. protected $transfmrk = array();
  977. /**
  978. * Default color for html links.
  979. * @protected
  980. * @since 4.4.003 (2008-12-09)
  981. */
  982. protected $htmlLinkColorArray = array(0, 0, 255);
  983. /**
  984. * Default font style to add to html links.
  985. * @protected
  986. * @since 4.4.003 (2008-12-09)
  987. */
  988. protected $htmlLinkFontStyle = 'U';
  989. /**
  990. * Counts the number of pages.
  991. * @protected
  992. * @since 4.5.000 (2008-12-31)
  993. */
  994. protected $numpages = 0;
  995. /**
  996. * Array containing page lengths in bytes.
  997. * @protected
  998. * @since 4.5.000 (2008-12-31)
  999. */
  1000. protected $pagelen = array();
  1001. /**
  1002. * Counts the number of pages.
  1003. * @protected
  1004. * @since 4.5.000 (2008-12-31)
  1005. */
  1006. protected $numimages = 0;
  1007. /**
  1008. * Store the image keys.
  1009. * @protected
  1010. * @since 4.5.000 (2008-12-31)
  1011. */
  1012. protected $imagekeys = array();
  1013. /**
  1014. * Length of the buffer in bytes.
  1015. * @protected
  1016. * @since 4.5.000 (2008-12-31)
  1017. */
  1018. protected $bufferlen = 0;
  1019. /**
  1020. * Counts the number of fonts.
  1021. * @protected
  1022. * @since 4.5.000 (2009-01-02)
  1023. */
  1024. protected $numfonts = 0;
  1025. /**
  1026. * Store the font keys.
  1027. * @protected
  1028. * @since 4.5.000 (2009-01-02)
  1029. */
  1030. protected $fontkeys = array();
  1031. /**
  1032. * Store the font object IDs.
  1033. * @protected
  1034. * @since 4.8.001 (2009-09-09)
  1035. */
  1036. protected $font_obj_ids = array();
  1037. /**
  1038. * Store the fage status (true when opened, false when closed).
  1039. * @protected
  1040. * @since 4.5.000 (2009-01-02)
  1041. */
  1042. protected $pageopen = array();
  1043. /**
  1044. * Default monospace font.
  1045. * @protected
  1046. * @since 4.5.025 (2009-03-10)
  1047. */
  1048. protected $default_monospaced_font = 'courier';
  1049. /**
  1050. * Cloned copy of the current class object.
  1051. * @protected
  1052. * @since 4.5.029 (2009-03-19)
  1053. */
  1054. protected $objcopy;
  1055. /**
  1056. * Array used to store the lengths of cache files.
  1057. * @protected
  1058. * @since 4.5.029 (2009-03-19)
  1059. */
  1060. protected $cache_file_length = array();
  1061. /**
  1062. * Table header content to be repeated on each new page.
  1063. * @protected
  1064. * @since 4.5.030 (2009-03-20)
  1065. */
  1066. protected $thead = '';
  1067. /**
  1068. * Margins used for table header.
  1069. * @protected
  1070. * @since 4.5.030 (2009-03-20)
  1071. */
  1072. protected $theadMargins = array();
  1073. /**
  1074. * Boolean flag to enable document digital signature.
  1075. * @protected
  1076. * @since 4.6.005 (2009-04-24)
  1077. */
  1078. protected $sign = false;
  1079. /**
  1080. * Digital signature data.
  1081. * @protected
  1082. * @since 4.6.005 (2009-04-24)
  1083. */
  1084. protected $signature_data = array();
  1085. /**
  1086. * Digital signature max length.
  1087. * @protected
  1088. * @since 4.6.005 (2009-04-24)
  1089. */
  1090. protected $signature_max_length = 11742;
  1091. /**
  1092. * Data for digital signature appearance.
  1093. * @protected
  1094. * @since 5.3.011 (2010-06-16)
  1095. */
  1096. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1097. /**
  1098. * Array of empty digital signature appearances.
  1099. * @protected
  1100. * @since 5.9.101 (2011-07-06)
  1101. */
  1102. protected $empty_signature_appearance = array();
  1103. /**
  1104. * Boolean flag to enable document timestamping with TSA.
  1105. * @protected
  1106. * @since 6.0.085 (2014-06-19)
  1107. */
  1108. protected $tsa_timestamp = false;
  1109. /**
  1110. * Timestamping data.
  1111. * @protected
  1112. * @since 6.0.085 (2014-06-19)
  1113. */
  1114. protected $tsa_data = array();
  1115. /**
  1116. * Regular expression used to find blank characters (required for word-wrapping).
  1117. * @protected
  1118. * @since 4.6.006 (2009-04-28)
  1119. */
  1120. protected $re_spaces = '/[^\S\xa0]/';
  1121. /**
  1122. * Array of $re_spaces parts.
  1123. * @protected
  1124. * @since 5.5.011 (2010-07-09)
  1125. */
  1126. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1127. /**
  1128. * Digital signature object ID.
  1129. * @protected
  1130. * @since 4.6.022 (2009-06-23)
  1131. */
  1132. protected $sig_obj_id = 0;
  1133. /**
  1134. * ID of page objects.
  1135. * @protected
  1136. * @since 4.7.000 (2009-08-29)
  1137. */
  1138. protected $page_obj_id = array();
  1139. /**
  1140. * List of form annotations IDs.
  1141. * @protected
  1142. * @since 4.8.000 (2009-09-07)
  1143. */
  1144. protected $form_obj_id = array();
  1145. /**
  1146. * Deafult Javascript field properties. Possible values are described on official Javascript for Acrobat API reference. Annotation options can be directly specified using the 'aopt' entry.
  1147. * @protected
  1148. * @since 4.8.000 (2009-09-07)
  1149. */
  1150. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1151. /**
  1152. * Javascript objects array.
  1153. * @protected
  1154. * @since 4.8.000 (2009-09-07)
  1155. */
  1156. protected $js_objects = array();
  1157. /**
  1158. * Current form action (used during XHTML rendering).
  1159. * @protected
  1160. * @since 4.8.000 (2009-09-07)
  1161. */
  1162. protected $form_action = '';
  1163. /**
  1164. * Current form encryption type (used during XHTML rendering).
  1165. * @protected
  1166. * @since 4.8.000 (2009-09-07)
  1167. */
  1168. protected $form_enctype = 'application/x-www-form-urlencoded';
  1169. /**
  1170. * Current method to submit forms.
  1171. * @protected
  1172. * @since 4.8.000 (2009-09-07)
  1173. */
  1174. protected $form_mode = 'post';
  1175. /**
  1176. * List of fonts used on form fields (fontname => fontkey).
  1177. * @protected
  1178. * @since 4.8.001 (2009-09-09)
  1179. */
  1180. protected $annotation_fonts = array();
  1181. /**
  1182. * List of radio buttons parent objects.
  1183. * @protected
  1184. * @since 4.8.001 (2009-09-09)
  1185. */
  1186. protected $radiobutton_groups = array();
  1187. /**
  1188. * List of radio group objects IDs.
  1189. * @protected
  1190. * @since 4.8.001 (2009-09-09)
  1191. */
  1192. protected $radio_groups = array();
  1193. /**
  1194. * Text indentation value (used for text-indent CSS attribute).
  1195. * @protected
  1196. * @since 4.8.006 (2009-09-23)
  1197. */
  1198. protected $textindent = 0;
  1199. /**
  1200. * Store page number when startTransaction() is called.
  1201. * @protected
  1202. * @since 4.8.006 (2009-09-23)
  1203. */
  1204. protected $start_transaction_page = 0;
  1205. /**
  1206. * Store Y position when startTransaction() is called.
  1207. * @protected
  1208. * @since 4.9.001 (2010-03-28)
  1209. */
  1210. protected $start_transaction_y = 0;
  1211. /**
  1212. * True when we are printing the thead section on a new page.
  1213. * @protected
  1214. * @since 4.8.027 (2010-01-25)
  1215. */
  1216. protected $inthead = false;
  1217. /**
  1218. * Array of column measures (width, space, starting Y position).
  1219. * @protected
  1220. * @since 4.9.001 (2010-03-28)
  1221. */
  1222. protected $columns = array();
  1223. /**
  1224. * Number of colums.
  1225. * @protected
  1226. * @since 4.9.001 (2010-03-28)
  1227. */
  1228. protected $num_columns = 1;
  1229. /**
  1230. * Current column number.
  1231. * @protected
  1232. * @since 4.9.001 (2010-03-28)
  1233. */
  1234. protected $current_column = 0;
  1235. /**
  1236. * Starting page for columns.
  1237. * @protected
  1238. * @since 4.9.001 (2010-03-28)
  1239. */
  1240. protected $column_start_page = 0;
  1241. /**
  1242. * Maximum page and column selected.
  1243. * @protected
  1244. * @since 5.8.000 (2010-08-11)
  1245. */
  1246. protected $maxselcol = array('page' => 0, 'column' => 0);
  1247. /**
  1248. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1249. * @protected
  1250. * @since 5.8.000 (2010-08-11)
  1251. */
  1252. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1253. /**
  1254. * Text rendering mode: 0 = Fill text; 1 = Stroke text; 2 = Fill, then stroke text; 3 = Neither fill nor stroke text (invisible); 4 = Fill text and add to path for clipping; 5 = Stroke text and add to path for clipping; 6 = Fill, then stroke text and add to path for clipping; 7 = Add text to path for clipping.
  1255. * @protected
  1256. * @since 4.9.008 (2010-04-03)
  1257. */
  1258. protected $textrendermode = 0;
  1259. /**
  1260. * Text stroke width in doc units.
  1261. * @protected
  1262. * @since 4.9.008 (2010-04-03)
  1263. */
  1264. protected $textstrokewidth = 0;
  1265. /**
  1266. * Current stroke color.
  1267. * @protected
  1268. * @since 4.9.008 (2010-04-03)
  1269. */
  1270. protected $strokecolor;
  1271. /**
  1272. * Default unit of measure for document.
  1273. * @protected
  1274. * @since 5.0.000 (2010-04-22)
  1275. */
  1276. protected $pdfunit = 'mm';
  1277. /**
  1278. * Boolean flag true when we are on TOC (Table Of Content) page.
  1279. * @protected
  1280. */
  1281. protected $tocpage = false;
  1282. /**
  1283. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1284. * @protected
  1285. * @since 5.0.000 (2010-04-26)
  1286. */
  1287. protected $rasterize_vector_images = false;
  1288. /**
  1289. * Boolean flag: if true enables font subsetting by default.
  1290. * @protected
  1291. * @since 5.3.002 (2010-06-07)
  1292. */
  1293. protected $font_subsetting = true;
  1294. /**
  1295. * Array of default graphic settings.
  1296. * @protected
  1297. * @since 5.5.008 (2010-07-02)
  1298. */
  1299. protected $default_graphic_vars = array();
  1300. /**
  1301. * Array of XObjects.
  1302. * @protected
  1303. * @since 5.8.014 (2010-08-23)
  1304. */
  1305. protected $xobjects = array();
  1306. /**
  1307. * Boolean value true when we are inside an XObject.
  1308. * @protected
  1309. * @since 5.8.017 (2010-08-24)
  1310. */
  1311. protected $inxobj = false;
  1312. /**
  1313. * Current XObject ID.
  1314. * @protected
  1315. * @since 5.8.017 (2010-08-24)
  1316. */
  1317. protected $xobjid = '';
  1318. /**
  1319. * Percentage of character stretching.
  1320. * @protected
  1321. * @since 5.9.000 (2010-09-29)
  1322. */
  1323. protected $font_stretching = 100;
  1324. /**
  1325. * Increases or decreases the space between characters in a text by the specified amount (tracking).
  1326. * @protected
  1327. * @since 5.9.000 (2010-09-29)
  1328. */
  1329. protected $font_spacing = 0;
  1330. /**
  1331. * Array of no-write regions.
  1332. * ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right)
  1333. * @protected
  1334. * @since 5.9.003 (2010-10-14)
  1335. */
  1336. protected $page_regions = array();
  1337. /**
  1338. * Boolean value true when page region check is active.
  1339. * @protected
  1340. */
  1341. protected $check_page_regions = true;
  1342. /**
  1343. * Array of PDF layers data.
  1344. * @protected
  1345. * @since 5.9.102 (2011-07-13)
  1346. */
  1347. protected $pdflayers = array();
  1348. /**
  1349. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1350. * @protected
  1351. * @since 5.9.097 (2011-06-23)
  1352. */
  1353. protected $dests = array();
  1354. /**
  1355. * Object ID for Named Destinations
  1356. * @protected
  1357. * @since 5.9.097 (2011-06-23)
  1358. */
  1359. protected $n_dests;
  1360. /**
  1361. * Embedded Files Names
  1362. * @protected
  1363. * @since 5.9.204 (2013-01-23)
  1364. */
  1365. protected $efnames = array();
  1366. /**
  1367. * Directory used for the last SVG image.
  1368. * @protected
  1369. * @since 5.0.000 (2010-05-05)
  1370. */
  1371. protected $svgdir = '';
  1372. /**
  1373. * Deafult unit of measure for SVG.
  1374. * @protected
  1375. * @since 5.0.000 (2010-05-02)
  1376. */
  1377. protected $svgunit = 'px';
  1378. /**
  1379. * Array of SVG gradients.
  1380. * @protected
  1381. * @since 5.0.000 (2010-05-02)
  1382. */
  1383. protected $svggradients = array();
  1384. /**
  1385. * ID of last SVG gradient.
  1386. * @protected
  1387. * @since 5.0.000 (2010-05-02)
  1388. */
  1389. protected $svggradientid = 0;
  1390. /**
  1391. * Boolean value true when in SVG defs group.
  1392. * @protected
  1393. * @since 5.0.000 (2010-05-02)
  1394. */
  1395. protected $svgdefsmode = false;
  1396. /**
  1397. * Array of SVG defs.
  1398. * @protected
  1399. * @since 5.0.000 (2010-05-02)
  1400. */
  1401. protected $svgdefs = array();
  1402. /**
  1403. * Boolean value true when in SVG clipPath tag.
  1404. * @protected
  1405. * @since 5.0.000 (2010-04-26)
  1406. */
  1407. protected $svgclipmode = false;
  1408. /**
  1409. * Array of SVG clipPath commands.
  1410. * @protected
  1411. * @since 5.0.000 (2010-05-02)
  1412. */
  1413. protected $svgclippaths = array();
  1414. /**
  1415. * Array of SVG clipPath tranformation matrix.
  1416. * @protected
  1417. * @since 5.8.022 (2010-08-31)
  1418. */
  1419. protected $svgcliptm = array();
  1420. /**
  1421. * ID of last SVG clipPath.
  1422. * @protected
  1423. * @since 5.0.000 (2010-05-02)
  1424. */
  1425. protected $svgclipid = 0;
  1426. /**
  1427. * SVG text.
  1428. * @protected
  1429. * @since 5.0.000 (2010-05-02)
  1430. */
  1431. protected $svgtext = '';
  1432. /**
  1433. * SVG text properties.
  1434. * @protected
  1435. * @since 5.8.013 (2010-08-23)
  1436. */
  1437. protected $svgtextmode = array();
  1438. /**
  1439. * Array of SVG properties.
  1440. * @protected
  1441. * @since 5.0.000 (2010-05-02)
  1442. */
  1443. protected $svgstyles = array(array(
  1444. 'alignment-baseline' => 'auto',
  1445. 'baseline-shift' => 'baseline',
  1446. 'clip' => 'auto',
  1447. 'clip-path' => 'none',
  1448. 'clip-rule' => 'nonzero',
  1449. 'color' => 'black',
  1450. 'color-interpolation' => 'sRGB',
  1451. 'color-interpolation-filters' => 'linearRGB',
  1452. 'color-profile' => 'auto',
  1453. 'color-rendering' => 'auto',
  1454. 'cursor' => 'auto',
  1455. 'direction' => 'ltr',
  1456. 'display' => 'inline',
  1457. 'dominant-baseline' => 'auto',
  1458. 'enable-background' => 'accumulate',
  1459. 'fill' => 'black',
  1460. 'fill-opacity' => 1,
  1461. 'fill-rule' => 'nonzero',
  1462. 'filter' => 'none',
  1463. 'flood-color' => 'black',
  1464. 'flood-opacity' => 1,
  1465. 'font' => '',
  1466. 'font-family' => 'helvetica',
  1467. 'font-size' => 'medium',
  1468. 'font-size-adjust' => 'none',
  1469. 'font-stretch' => 'normal',
  1470. 'font-style' => 'normal',
  1471. 'font-variant' => 'normal',
  1472. 'font-weight' => 'normal',
  1473. 'glyph-orientation-horizontal' => '0deg',
  1474. 'glyph-orientation-vertical' => 'auto',
  1475. 'image-rendering' => 'auto',
  1476. 'kerning' => 'auto',
  1477. 'letter-spacing' => 'normal',
  1478. 'lighting-color' => 'white',
  1479. 'marker' => '',
  1480. 'marker-end' => 'none',
  1481. 'marker-mid' => 'none',
  1482. 'marker-start' => 'none',
  1483. 'mask' => 'none',
  1484. 'opacity' => 1,
  1485. 'overflow' => 'auto',
  1486. 'pointer-events' => 'visiblePainted',
  1487. 'shape-rendering' => 'auto',
  1488. 'stop-color' => 'black',
  1489. 'stop-opacity' => 1,
  1490. 'stroke' => 'none',
  1491. 'stroke-dasharray' => 'none',
  1492. 'stroke-dashoffset' => 0,
  1493. 'stroke-linecap' => 'butt',
  1494. 'stroke-linejoin' => 'miter',
  1495. 'stroke-miterlimit' => 4,
  1496. 'stroke-opacity' => 1,
  1497. 'stroke-width' => 1,
  1498. 'text-anchor' => 'start',
  1499. 'text-decoration' => 'none',
  1500. 'text-rendering' => 'auto',
  1501. 'unicode-bidi' => 'normal',
  1502. 'visibility' => 'visible',
  1503. 'word-spacing' => 'normal',
  1504. 'writing-mode' => 'lr-tb',
  1505. 'text-color' => 'black',
  1506. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1507. ));
  1508. /**
  1509. * If true force sRGB color profile for all document.
  1510. * @protected
  1511. * @since 5.9.121 (2011-09-28)
  1512. */
  1513. protected $force_srgb = false;
  1514. /**
  1515. * If true set the document to PDF/A mode.
  1516. * @protected
  1517. * @since 5.9.121 (2011-09-27)
  1518. */
  1519. protected $pdfa_mode = false;
  1520. /**
  1521. * version of PDF/A mode (1 - 3).
  1522. * @protected
  1523. * @since 6.2.26 (2019-03-12)
  1524. */
  1525. protected $pdfa_version = 1;
  1526. /**
  1527. * Document creation date-time
  1528. * @protected
  1529. * @since 5.9.152 (2012-03-22)
  1530. */
  1531. protected $doc_creation_timestamp;
  1532. /**
  1533. * Document modification date-time
  1534. * @protected
  1535. * @since 5.9.152 (2012-03-22)
  1536. */
  1537. protected $doc_modification_timestamp;
  1538. /**
  1539. * Custom XMP data.
  1540. * @protected
  1541. * @since 5.9.128 (2011-10-06)
  1542. */
  1543. protected $custom_xmp = '';
  1544. /**
  1545. * Custom XMP RDF data.
  1546. * @protected
  1547. * @since 6.3.0 (2019-09-19)
  1548. */
  1549. protected $custom_xmp_rdf = '';
  1550. /**
  1551. * Overprint mode array.
  1552. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1553. * @protected
  1554. * @since 5.9.152 (2012-03-23)
  1555. */
  1556. protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
  1557. /**
  1558. * Alpha mode array.
  1559. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1560. * @protected
  1561. * @since 5.9.152 (2012-03-23)
  1562. */
  1563. protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
  1564. /**
  1565. * Define the page boundaries boxes to be set on document.
  1566. * @protected
  1567. * @since 5.9.152 (2012-03-23)
  1568. */
  1569. protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  1570. /**
  1571. * If true print TCPDF meta link.
  1572. * @protected
  1573. * @since 5.9.152 (2012-03-23)
  1574. */
  1575. protected $tcpdflink = true;
  1576. /**
  1577. * Cache array for computed GD gamma values.
  1578. * @protected
  1579. * @since 5.9.1632 (2012-06-05)
  1580. */
  1581. protected $gdgammacache = array();
  1582. //------------------------------------------------------------
  1583. // METHODS
  1584. //------------------------------------------------------------
  1585. /**
  1586. * This is the class constructor.
  1587. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
  1588. *
  1589. * IMPORTANT: Please note that this method sets the mb_internal_encoding to ASCII, so if you are using the mbstring module functions with TCPDF you need to correctly set/unset the mb_internal_encoding when needed.
  1590. *
  1591. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
  1592. * @param $unit (string) User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
  1593. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  1594. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1595. * @param $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.
  1596. * @param $diskcache (boolean) DEPRECATED FEATURE
  1597. * @param $pdfa (integer) If not false, set the document to PDF/A mode and the good version (1 or 3).
  1598. * @public
  1599. * @see getPageSizeFromFormat(), setPageFormat()
  1600. */
  1601. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1602. /* Set internal character encoding to ASCII */
  1603. if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
  1604. $this->internal_encoding = mb_internal_encoding();
  1605. mb_internal_encoding('ASCII');
  1606. }
  1607. // set file ID for trailer
  1608. $serformat = (is_array($format) ? json_encode($format) : $format);
  1609. $this->file_id = md5(TCPDF_STATIC::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
  1610. $this->font_obj_ids = array();
  1611. $this->page_obj_id = array();
  1612. $this->form_obj_id = array();
  1613. // set pdf/a mode
  1614. if ($pdfa != false) {
  1615. $this->pdfa_mode = true;
  1616. $this->pdfa_version = $pdfa; // 1 or 3
  1617. } else
  1618. $this->pdfa_mode = false;
  1619. $this->force_srgb = false;
  1620. // set language direction
  1621. $this->rtl = false;
  1622. $this->tmprtl = false;
  1623. // some checks
  1624. $this->_dochecks();
  1625. // initialization of properties
  1626. $this->isunicode = $unicode;
  1627. $this->page = 0;
  1628. $this->transfmrk[0] = array();
  1629. $this->pagedim = array();
  1630. $this->n = 2;
  1631. $this->buffer = '';
  1632. $this->pages = array();
  1633. $this->state = 0;
  1634. $this->fonts = array();
  1635. $this->FontFiles = array();
  1636. $this->diffs = array();
  1637. $this->images = array();
  1638. $this->links = array();
  1639. $this->gradients = array();
  1640. $this->InFooter = false;
  1641. $this->lasth = 0;
  1642. $this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  1643. $this->FontStyle = '';
  1644. $this->FontSizePt = 12;
  1645. $this->underline = false;
  1646. $this->overline = false;
  1647. $this->linethrough = false;
  1648. $this->DrawColor = '0 G';
  1649. $this->FillColor = '0 g';
  1650. $this->TextColor = '0 g';
  1651. $this->ColorFlag = false;
  1652. $this->pdflayers = array();
  1653. // encryption values
  1654. $this->encrypted = false;
  1655. $this->last_enc_key = '';
  1656. // standard Unicode fonts
  1657. $this->CoreFonts = array(
  1658. 'courier'=>'Courier',
  1659. 'courierB'=>'Courier-Bold',
  1660. 'courierI'=>'Courier-Oblique',
  1661. 'courierBI'=>'Courier-BoldOblique',
  1662. 'helvetica'=>'Helvetica',
  1663. 'helveticaB'=>'Helvetica-Bold',
  1664. 'helveticaI'=>'Helvetica-Oblique',
  1665. 'helveticaBI'=>'Helvetica-BoldOblique',
  1666. 'times'=>'Times-Roman',
  1667. 'timesB'=>'Times-Bold',
  1668. 'timesI'=>'Times-Italic',
  1669. 'timesBI'=>'Times-BoldItalic',
  1670. 'symbol'=>'Symbol',
  1671. 'zapfdingbats'=>'ZapfDingbats'
  1672. );
  1673. // set scale factor
  1674. $this->setPageUnit($unit);
  1675. // set page format and orientation
  1676. $this->setPageFormat($format, $orientation);
  1677. // page margins (1 cm)
  1678. $margin = 28.35 / $this->k;
  1679. $this->SetMargins($margin, $margin);
  1680. $this->clMargin = $this->lMargin;
  1681. $this->crMargin = $this->rMargin;
  1682. // internal cell padding
  1683. $cpadding = $margin / 10;
  1684. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1685. // cell margins
  1686. $this->setCellMargins(0, 0, 0, 0);
  1687. // line width (0.2 mm)
  1688. $this->LineWidth = 0.57 / $this->k;
  1689. $this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
  1690. $this->linestyleCap = '0 J';
  1691. $this->linestyleJoin = '0 j';
  1692. $this->linestyleDash = '[] 0 d';
  1693. // automatic page break
  1694. $this->SetAutoPageBreak(true, (2 * $margin));
  1695. // full width display mode
  1696. $this->SetDisplayMode('fullwidth');
  1697. // compression
  1698. $this->SetCompression();
  1699. // set default PDF version number
  1700. $this->setPDFVersion();
  1701. $this->tcpdflink = true;
  1702. $this->encoding = $encoding;
  1703. $this->HREF = array();
  1704. $this->getFontsList();
  1705. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1706. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1707. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1708. $this->extgstates = array();
  1709. $this->setTextShadow();
  1710. // signature
  1711. $this->sign = false;
  1712. $this->tsa_timestamp = false;
  1713. $this->tsa_data = array();
  1714. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
  1715. $this->empty_signature_appearance = array();
  1716. // user's rights
  1717. $this->ur['enabled'] = false;
  1718. $this->ur['document'] = '/FullSave';
  1719. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1720. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1721. $this->ur['signature'] = '/Modify';
  1722. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1723. $this->ur['formex'] = '';
  1724. // set default JPEG quality
  1725. $this->jpeg_quality = 75;
  1726. // initialize some settings
  1727. TCPDF_FONTS::utf8Bidi(array(), '', false, $this->isunicode, $this->CurrentFont);
  1728. // set default font
  1729. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1730. $this->setHeaderFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1731. $this->setFooterFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1732. // check if PCRE Unicode support is enabled
  1733. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1734. // PCRE unicode support is turned ON
  1735. // \s : any whitespace character
  1736. // \p{Z} : any separator
  1737. // \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  1738. // \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  1739. //$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
  1740. $this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
  1741. } else {
  1742. // PCRE unicode support is turned OFF
  1743. $this->setSpacesRE('/[^\S\xa0]/');
  1744. }
  1745. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1746. // set document creation and modification timestamp
  1747. $this->doc_creation_timestamp = time();
  1748. $this->doc_modification_timestamp = $this->doc_creation_timestamp;
  1749. // get default graphic vars
  1750. $this->default_graphic_vars = $this->getGraphicVars();
  1751. $this->header_xobj_autoreset = false;
  1752. $this->custom_xmp = '';
  1753. $this->custom_xmp_rdf = '';
  1754. // Call cleanup method after script execution finishes or exit() is called.
  1755. // NOTE: This will not be executed if the process is killed with a SIGTERM or SIGKILL signal.
  1756. register_shutdown_function(array($this, '_destroy'), true);
  1757. }
  1758. /**
  1759. * Default destructor.
  1760. * @public
  1761. * @since 1.53.0.TC016
  1762. */
  1763. public function __destruct() {
  1764. // cleanup
  1765. $this->_destroy(true);
  1766. }
  1767. /**
  1768. * Set the units of measure for the document.
  1769. * @param $unit (string) User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
  1770. * @public
  1771. * @since 3.0.015 (2008-06-06)
  1772. */
  1773. public function setPageUnit($unit) {
  1774. $unit = strtolower($unit);
  1775. //Set scale factor
  1776. switch ($unit) {
  1777. // points
  1778. case 'px':
  1779. case 'pt': {
  1780. $this->k = 1;
  1781. break;
  1782. }
  1783. // millimeters
  1784. case 'mm': {
  1785. $this->k = $this->dpi / 25.4;
  1786. break;
  1787. }
  1788. // centimeters
  1789. case 'cm': {
  1790. $this->k = $this->dpi / 2.54;
  1791. break;
  1792. }
  1793. // inches
  1794. case 'in': {
  1795. $this->k = $this->dpi;
  1796. break;
  1797. }
  1798. // unsupported unit
  1799. default : {
  1800. $this->Error('Incorrect unit: '.$unit);
  1801. break;
  1802. }
  1803. }
  1804. $this->pdfunit = $unit;
  1805. if (isset($this->CurOrientation)) {
  1806. $this->setPageOrientation($this->CurOrientation);
  1807. }
  1808. }
  1809. /**
  1810. * Change the format of the current page
  1811. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numbers (width, height) or an array containing the following measures and options:<ul>
  1812. * <li>['format'] = page format name (one of the above);</li>
  1813. * <li>['Rotate'] : The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li>
  1814. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  1815. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  1816. * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
  1817. * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
  1818. * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
  1819. * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
  1820. * <li>['CropBox'] : the visible region of default user space:</li>
  1821. * <li>['CropBox']['llx'] : lower-left x coordinate</li>
  1822. * <li>['CropBox']['lly'] : lower-left y coordinate</li>
  1823. * <li>['CropBox']['urx'] : upper-right x coordinate</li>
  1824. * <li>['CropBox']['ury'] : upper-right y coordinate</li>
  1825. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  1826. * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
  1827. * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
  1828. * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
  1829. * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
  1830. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  1831. * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
  1832. * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
  1833. * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
  1834. * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
  1835. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  1836. * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
  1837. * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
  1838. * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
  1839. * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
  1840. * <li>['BoxColorInfo'] :specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for each of the possible page boundaries other than the MediaBox:</li>
  1841. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  1842. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  1843. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  1844. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  1845. * <li>['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation</li>
  1846. * <li>['trans']['Dur'] : The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li>
  1847. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  1848. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  1849. * <li>['trans']['Dm'] : (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li>
  1850. * <li>['trans']['M'] : (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li>
  1851. * <li>['trans']['Di'] : (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li>
  1852. * <li>['trans']['SS'] : (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0.</li>
  1853. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  1854. * </ul>
  1855. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  1856. * <li>P or Portrait (default)</li>
  1857. * <li>L or Landscape</li>
  1858. * <li>'' (empty string) for automatic orientation</li>
  1859. * </ul>
  1860. * @protected
  1861. * @since 3.0.015 (2008-06-06)
  1862. * @see getPageSizeFromFormat()
  1863. */
  1864. protected function setPageFormat($format, $orientation='P') {
  1865. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  1866. // remove inherited values
  1867. unset($this->pagedim[$this->page]);
  1868. }
  1869. if (is_string($format)) {
  1870. // get page measures from format name
  1871. $pf = TCPDF_STATIC::getPageSizeFromFormat($format);
  1872. $this->fwPt = $pf[0];
  1873. $this->fhPt = $pf[1];
  1874. } else {
  1875. // the boundaries of the physical medium on which the page shall be displayed or printed
  1876. if (isset($format['MediaBox'])) {
  1877. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false, $this->k, $this->pagedim);
  1878. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  1879. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  1880. } else {
  1881. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  1882. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  1883. } else {
  1884. if (!isset($format['format'])) {
  1885. // default value
  1886. $format['format'] = 'A4';
  1887. }
  1888. $pf = TCPDF_STATIC::getPageSizeFromFormat($format['format']);
  1889. }
  1890. $this->fwPt = $pf[0];
  1891. $this->fhPt = $pf[1];
  1892. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1893. }
  1894. // the visible region of default user space
  1895. if (isset($format['CropBox'])) {
  1896. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false, $this->k, $this->pagedim);
  1897. }
  1898. // the region to which the contents of the page shall be clipped when output in a production environment
  1899. if (isset($format['BleedBox'])) {
  1900. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false, $this->k, $this->pagedim);
  1901. }
  1902. // the intended dimensions of the finished page after trimming
  1903. if (isset($format['TrimBox'])) {
  1904. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false, $this->k, $this->pagedim);
  1905. }
  1906. // the page's meaningful content (including potential white space)
  1907. if (isset($format['ArtBox'])) {
  1908. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false, $this->k, $this->pagedim);
  1909. }
  1910. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  1911. if (isset($format['BoxColorInfo'])) {
  1912. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  1913. }
  1914. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  1915. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  1916. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  1917. }
  1918. if (isset($format['PZ'])) {
  1919. // The page's preferred zoom (magnification) factor
  1920. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  1921. }
  1922. if (isset($format['trans'])) {
  1923. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  1924. if (isset($format['trans']['Dur'])) {
  1925. // The page's display duration
  1926. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  1927. }
  1928. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  1929. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  1930. // The transition style that shall be used when moving to this page from another during a presentation
  1931. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  1932. $valid_effect = array('Split', 'Blinds');
  1933. $valid_vals = array('H', 'V');
  1934. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  1935. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  1936. }
  1937. $valid_effect = array('Split', 'Box', 'Fly');
  1938. $valid_vals = array('I', 'O');
  1939. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  1940. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  1941. }
  1942. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  1943. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  1944. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  1945. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  1946. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  1947. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  1948. }
  1949. }
  1950. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  1951. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  1952. }
  1953. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  1954. $this->pagedim[$this->page]['trans']['B'] = 'true';
  1955. }
  1956. } else {
  1957. $this->pagedim[$this->page]['trans']['S'] = 'R';
  1958. }
  1959. if (isset($format['trans']['D'])) {
  1960. // The duration of the transition effect, in seconds
  1961. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  1962. } else {
  1963. $this->pagedim[$this->page]['trans']['D'] = 1;
  1964. }
  1965. }
  1966. }
  1967. $this->setPageOrientation($orientation);
  1968. }
  1969. /**
  1970. * Set page orientation.
  1971. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
  1972. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  1973. * @param $bottommargin (float) bottom margin of the page.
  1974. * @public
  1975. * @since 3.0.015 (2008-06-06)
  1976. */
  1977. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  1978. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  1979. // the boundaries of the physical medium on which the page shall be displayed or printed
  1980. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1981. }
  1982. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  1983. // the visible region of default user space
  1984. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $this->pagedim[$this->page]['MediaBox']['llx'], $this->pagedim[$this->page]['MediaBox']['lly'], $this->pagedim[$this->page]['MediaBox']['urx'], $this->pagedim[$this->page]['MediaBox']['ury'], true, $this->k, $this->pagedim);
  1985. }
  1986. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  1987. // the region to which the contents of the page shall be clipped when output in a production environment
  1988. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1989. }
  1990. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  1991. // the intended dimensions of the finished page after trimming
  1992. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1993. }
  1994. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  1995. // the page's meaningful content (including potential white space)
  1996. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1997. }
  1998. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  1999. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2000. $this->pagedim[$this->page]['Rotate'] = 0;
  2001. }
  2002. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2003. // The page's preferred zoom (magnification) factor
  2004. $this->pagedim[$this->page]['PZ'] = 1;
  2005. }
  2006. if ($this->fwPt > $this->fhPt) {
  2007. // landscape
  2008. $default_orientation = 'L';
  2009. } else {
  2010. // portrait
  2011. $default_orientation = 'P';
  2012. }
  2013. $valid_orientations = array('P', 'L');
  2014. if (empty($orientation)) {
  2015. $orientation = $default_orientation;
  2016. } else {
  2017. $orientation = strtoupper($orientation[0]);
  2018. }
  2019. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2020. $this->CurOrientation = $orientation;
  2021. $this->wPt = $this->fhPt;
  2022. $this->hPt = $this->fwPt;
  2023. } else {
  2024. $this->CurOrientation = $default_orientation;
  2025. $this->wPt = $this->fwPt;
  2026. $this->hPt = $this->fhPt;
  2027. }
  2028. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2029. // swap X and Y coordinates (change page orientation)
  2030. $this->pagedim = TCPDF_STATIC::swapPageBoxCoordinates($this->page, $this->pagedim);
  2031. }
  2032. $this->w = ($this->wPt / $this->k);
  2033. $this->h = ($this->hPt / $this->k);
  2034. if (TCPDF_STATIC::empty_string($autopagebreak)) {
  2035. if (isset($this->AutoPageBreak)) {
  2036. $autopagebreak = $this->AutoPageBreak;
  2037. } else {
  2038. $autopagebreak = true;
  2039. }
  2040. }
  2041. if (TCPDF_STATIC::empty_string($bottommargin)) {
  2042. if (isset($this->bMargin)) {
  2043. $bottommargin = $this->bMargin;
  2044. } else {
  2045. // default value = 2 cm
  2046. $bottommargin = 2 * 28.35 / $this->k;
  2047. }
  2048. }
  2049. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2050. // store page dimensions
  2051. $this->pagedim[$this->page]['w'] = $this->wPt;
  2052. $this->pagedim[$this->page]['h'] = $this->hPt;
  2053. $this->pagedim[$this->page]['wk'] = $this->w;
  2054. $this->pagedim[$this->page]['hk'] = $this->h;
  2055. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2056. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2057. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2058. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2059. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2060. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2061. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2062. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2063. }
  2064. /**
  2065. * Set regular expression to detect withespaces or word separators.
  2066. * The pattern delimiter must be the forward-slash character "/".
  2067. * Some example patterns are:
  2068. * <pre>
  2069. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2070. * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
  2071. * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
  2072. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2073. * \s : any whitespace character
  2074. * \p{Z} : any separator
  2075. * \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  2076. * \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  2077. * </pre>
  2078. * @param $re (string) regular expression (leave empty for default).
  2079. * @public
  2080. * @since 4.6.016 (2009-06-15)
  2081. */
  2082. public function setSpacesRE($re='/[^\S\xa0]/') {
  2083. $this->re_spaces = $re;
  2084. $re_parts = explode('/', $re);
  2085. // get pattern parts
  2086. $this->re_space = array();
  2087. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2088. $this->re_space['p'] = $re_parts[1];
  2089. } else {
  2090. $this->re_space['p'] = '[\s]';
  2091. }
  2092. // set pattern modifiers
  2093. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2094. $this->re_space['m'] = $re_parts[2];
  2095. } else {
  2096. $this->re_space['m'] = '';
  2097. }
  2098. }
  2099. /**
  2100. * Enable or disable Right-To-Left language mode
  2101. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2102. * @param $resetx (Boolean) if true reset the X position on direction change.
  2103. * @public
  2104. * @since 2.0.000 (2008-01-03)
  2105. */
  2106. public function setRTL($enable, $resetx=true) {
  2107. $enable = $enable ? true : false;
  2108. $resetx = ($resetx AND ($enable != $this->rtl));
  2109. $this->rtl = $enable;
  2110. $this->tmprtl = false;
  2111. if ($resetx) {
  2112. $this->Ln(0);
  2113. }
  2114. }
  2115. /**
  2116. * Return the RTL status
  2117. * @return boolean
  2118. * @public
  2119. * @since 4.0.012 (2008-07-24)
  2120. */
  2121. public function getRTL() {
  2122. return $this->rtl;
  2123. }
  2124. /**
  2125. * Force temporary RTL language direction
  2126. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2127. * @public
  2128. * @since 2.1.000 (2008-01-09)
  2129. */
  2130. public function setTempRTL($mode) {
  2131. $newmode = false;
  2132. switch (strtoupper($mode)) {
  2133. case 'LTR':
  2134. case 'L': {
  2135. if ($this->rtl) {
  2136. $newmode = 'L';
  2137. }
  2138. break;
  2139. }
  2140. case 'RTL':
  2141. case 'R': {
  2142. if (!$this->rtl) {
  2143. $newmode = 'R';
  2144. }
  2145. break;
  2146. }
  2147. case false:
  2148. default: {
  2149. $newmode = false;
  2150. break;
  2151. }
  2152. }
  2153. $this->tmprtl = $newmode;
  2154. }
  2155. /**
  2156. * Return the current temporary RTL status
  2157. * @return boolean
  2158. * @public
  2159. * @since 4.8.014 (2009-11-04)
  2160. */
  2161. public function isRTLTextDir() {
  2162. return ($this->rtl OR ($this->tmprtl == 'R'));
  2163. }
  2164. /**
  2165. * Set the last cell height.
  2166. * @param $h (float) cell height.
  2167. * @author Nicola Asuni
  2168. * @public
  2169. * @since 1.53.0.TC034
  2170. */
  2171. public function setLastH($h) {
  2172. $this->lasth = $h;
  2173. }
  2174. /**
  2175. * Return the cell height
  2176. * @param $fontsize (int) Font size in internal units
  2177. * @param $padding (boolean) If true add cell padding
  2178. * @public
  2179. */
  2180. public function getCellHeight($fontsize, $padding=TRUE) {
  2181. $height = ($fontsize * $this->cell_height_ratio);
  2182. if ($padding) {
  2183. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  2184. }
  2185. return round($height, 6);
  2186. }
  2187. /**
  2188. * Reset the last cell height.
  2189. * @public
  2190. * @since 5.9.000 (2010-10-03)
  2191. */
  2192. public function resetLastH() {
  2193. $this->lasth = $this->getCellHeight($this->FontSize);
  2194. }
  2195. /**
  2196. * Get the last cell height.
  2197. * @return last cell height
  2198. * @public
  2199. * @since 4.0.017 (2008-08-05)
  2200. */
  2201. public function getLastH() {
  2202. return $this->lasth;
  2203. }
  2204. /**
  2205. * Set the adjusting factor to convert pixels to user units.
  2206. * @param $scale (float) adjusting factor to convert pixels to user units.
  2207. * @author Nicola Asuni
  2208. * @public
  2209. * @since 1.5.2
  2210. */
  2211. public function setImageScale($scale) {
  2212. $this->imgscale = $scale;
  2213. }
  2214. /**
  2215. * Returns the adjusting factor to convert pixels to user units.
  2216. * @return float adjusting factor to convert pixels to user units.
  2217. * @author Nicola Asuni
  2218. * @public
  2219. * @since 1.5.2
  2220. */
  2221. public function getImageScale() {
  2222. return $this->imgscale;
  2223. }
  2224. /**
  2225. * Returns an array of page dimensions:
  2226. * <ul><li>$this->pagedim[$this->page]['w'] = page width in points</li><li>$this->pagedim[$this->page]['h'] = height in points</li><li>$this->pagedim[$this->page]['wk'] = page width in user units</li><li>$this->pagedim[$this->page]['hk'] = page height in user units</li><li>$this->pagedim[$this->page]['tm'] = top margin</li><li>$this->pagedim[$this->page]['bm'] = bottom margin</li><li>$this->pagedim[$this->page]['lm'] = left margin</li><li>$this->pagedim[$this->page]['rm'] = right margin</li><li>$this->pagedim[$this->page]['pb'] = auto page break</li><li>$this->pagedim[$this->page]['or'] = page orientation</li><li>$this->pagedim[$this->page]['olm'] = original left margin</li><li>$this->pagedim[$this->page]['orm'] = original right margin</li><li>$this->pagedim[$this->page]['Rotate'] = The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li><li>$this->pagedim[$this->page]['PZ'] = The page's preferred zoom (magnification) factor.</li><li>$this->pagedim[$this->page]['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation<ul><li>$this->pagedim[$this->page]['trans']['Dur'] = The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li><li>$this->pagedim[$this->page]['trans']['S'] = transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li><li>$this->pagedim[$this->page]['trans']['D'] = The duration of the transition effect, in seconds.</li><li>$this->pagedim[$this->page]['trans']['Dm'] = (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li><li>$this->pagedim[$this->page]['trans']['M'] = (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li><li>$this->pagedim[$this->page]['trans']['Di'] = (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li><li>$this->pagedim[$this->page]['trans']['SS'] = (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0. </li><li>$this->pagedim[$this->page]['trans']['B'] = (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li></ul></li><li>$this->pagedim[$this->page]['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed<ul><li>$this->pagedim[$this->page]['MediaBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['CropBox'] : the visible region of default user space<ul><li>$this->pagedim[$this->page]['CropBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment<ul><li>$this->pagedim[$this->page]['BleedBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['TrimBox'] : the intended dimensions of the finished page after trimming<ul><li>$this->pagedim[$this->page]['TrimBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['ArtBox'] : the extent of the page's meaningful content<ul><li>$this->pagedim[$this->page]['ArtBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['ury'] = upper-right y coordinate in points</li></ul></li></ul>
  2227. * @param $pagenum (int) page number (empty = current page)
  2228. * @return array of page dimensions.
  2229. * @author Nicola Asuni
  2230. * @public
  2231. * @since 4.5.027 (2009-03-16)
  2232. */
  2233. public function getPageDimensions($pagenum='') {
  2234. if (empty($pagenum)) {
  2235. $pagenum = $this->page;
  2236. }
  2237. return $this->pagedim[$pagenum];
  2238. }
  2239. /**
  2240. * Returns the page width in units.
  2241. * @param $pagenum (int) page number (empty = current page)
  2242. * @return int page width.
  2243. * @author Nicola Asuni
  2244. * @public
  2245. * @since 1.5.2
  2246. * @see getPageDimensions()
  2247. */
  2248. public function getPageWidth($pagenum='') {
  2249. if (empty($pagenum)) {
  2250. return $this->w;
  2251. }
  2252. return $this->pagedim[$pagenum]['w'];
  2253. }
  2254. /**
  2255. * Returns the page height in units.
  2256. * @param $pagenum (int) page number (empty = current page)
  2257. * @return int page height.
  2258. * @author Nicola Asuni
  2259. * @public
  2260. * @since 1.5.2
  2261. * @see getPageDimensions()
  2262. */
  2263. public function getPageHeight($pagenum='') {
  2264. if (empty($pagenum)) {
  2265. return $this->h;
  2266. }
  2267. return $this->pagedim[$pagenum]['h'];
  2268. }
  2269. /**
  2270. * Returns the page break margin.
  2271. * @param $pagenum (int) page number (empty = current page)
  2272. * @return int page break margin.
  2273. * @author Nicola Asuni
  2274. * @public
  2275. * @since 1.5.2
  2276. * @see getPageDimensions()
  2277. */
  2278. public function getBreakMargin($pagenum='') {
  2279. if (empty($pagenum)) {
  2280. return $this->bMargin;
  2281. }
  2282. return $this->pagedim[$pagenum]['bm'];
  2283. }
  2284. /**
  2285. * Returns the scale factor (number of points in user unit).
  2286. * @return int scale factor.
  2287. * @author Nicola Asuni
  2288. * @public
  2289. * @since 1.5.2
  2290. */
  2291. public function getScaleFactor() {
  2292. return $this->k;
  2293. }
  2294. /**
  2295. * Defines the left, top and right margins.
  2296. * @param $left (float) Left margin.
  2297. * @param $top (float) Top margin.
  2298. * @param $right (float) Right margin. Default value is the left one.
  2299. * @param $keepmargins (boolean) if true overwrites the default page margins
  2300. * @public
  2301. * @since 1.0
  2302. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  2303. */
  2304. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  2305. //Set left, top and right margins
  2306. $this->lMargin = $left;
  2307. $this->tMargin = $top;
  2308. if ($right == -1) {
  2309. $right = $left;
  2310. }
  2311. $this->rMargin = $right;
  2312. if ($keepmargins) {
  2313. // overwrite original values
  2314. $this->original_lMargin = $this->lMargin;
  2315. $this->original_rMargin = $this->rMargin;
  2316. }
  2317. }
  2318. /**
  2319. * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
  2320. * @param $margin (float) The margin.
  2321. * @public
  2322. * @since 1.4
  2323. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2324. */
  2325. public function SetLeftMargin($margin) {
  2326. //Set left margin
  2327. $this->lMargin = $margin;
  2328. if (($this->page > 0) AND ($this->x < $margin)) {
  2329. $this->x = $margin;
  2330. }
  2331. }
  2332. /**
  2333. * Defines the top margin. The method can be called before creating the first page.
  2334. * @param $margin (float) The margin.
  2335. * @public
  2336. * @since 1.5
  2337. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2338. */
  2339. public function SetTopMargin($margin) {
  2340. //Set top margin
  2341. $this->tMargin = $margin;
  2342. if (($this->page > 0) AND ($this->y < $margin)) {
  2343. $this->y = $margin;
  2344. }
  2345. }
  2346. /**
  2347. * Defines the right margin. The method can be called before creating the first page.
  2348. * @param $margin (float) The margin.
  2349. * @public
  2350. * @since 1.5
  2351. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  2352. */
  2353. public function SetRightMargin($margin) {
  2354. $this->rMargin = $margin;
  2355. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  2356. $this->x = $this->w - $margin;
  2357. }
  2358. }
  2359. /**
  2360. * Set the same internal Cell padding for top, right, bottom, left-
  2361. * @param $pad (float) internal padding.
  2362. * @public
  2363. * @since 2.1.000 (2008-01-09)
  2364. * @see getCellPaddings(), setCellPaddings()
  2365. */
  2366. public function SetCellPadding($pad) {
  2367. if ($pad >= 0) {
  2368. $this->cell_padding['L'] = $pad;
  2369. $this->cell_padding['T'] = $pad;
  2370. $this->cell_padding['R'] = $pad;
  2371. $this->cell_padding['B'] = $pad;
  2372. }
  2373. }
  2374. /**
  2375. * Set the internal Cell paddings.
  2376. * @param $left (float) left padding
  2377. * @param $top (float) top padding
  2378. * @param $right (float) right padding
  2379. * @param $bottom (float) bottom padding
  2380. * @public
  2381. * @since 5.9.000 (2010-10-03)
  2382. * @see getCellPaddings(), SetCellPadding()
  2383. */
  2384. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  2385. if (($left !== '') AND ($left >= 0)) {
  2386. $this->cell_padding['L'] = $left;
  2387. }
  2388. if (($top !== '') AND ($top >= 0)) {
  2389. $this->cell_padding['T'] = $top;
  2390. }
  2391. if (($right !== '') AND ($right >= 0)) {
  2392. $this->cell_padding['R'] = $right;
  2393. }
  2394. if (($bottom !== '') AND ($bottom >= 0)) {
  2395. $this->cell_padding['B'] = $bottom;
  2396. }
  2397. }
  2398. /**
  2399. * Get the internal Cell padding array.
  2400. * @return array of padding values
  2401. * @public
  2402. * @since 5.9.000 (2010-10-03)
  2403. * @see setCellPaddings(), SetCellPadding()
  2404. */
  2405. public function getCellPaddings() {
  2406. return $this->cell_padding;
  2407. }
  2408. /**
  2409. * Set the internal Cell margins.
  2410. * @param $left (float) left margin
  2411. * @param $top (float) top margin
  2412. * @param $right (float) right margin
  2413. * @param $bottom (float) bottom margin
  2414. * @public
  2415. * @since 5.9.000 (2010-10-03)
  2416. * @see getCellMargins()
  2417. */
  2418. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  2419. if (($left !== '') AND ($left >= 0)) {
  2420. $this->cell_margin['L'] = $left;
  2421. }
  2422. if (($top !== '') AND ($top >= 0)) {
  2423. $this->cell_margin['T'] = $top;
  2424. }
  2425. if (($right !== '') AND ($right >= 0)) {
  2426. $this->cell_margin['R'] = $right;
  2427. }
  2428. if (($bottom !== '') AND ($bottom >= 0)) {
  2429. $this->cell_margin['B'] = $bottom;
  2430. }
  2431. }
  2432. /**
  2433. * Get the internal Cell margin array.
  2434. * @return array of margin values
  2435. * @public
  2436. * @since 5.9.000 (2010-10-03)
  2437. * @see setCellMargins()
  2438. */
  2439. public function getCellMargins() {
  2440. return $this->cell_margin;
  2441. }
  2442. /**
  2443. * Adjust the internal Cell padding array to take account of the line width.
  2444. * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  2445. * @return array of adjustments
  2446. * @public
  2447. * @since 5.9.000 (2010-10-03)
  2448. */
  2449. protected function adjustCellPadding($brd=0) {
  2450. if (empty($brd)) {
  2451. return;
  2452. }
  2453. if (is_string($brd)) {
  2454. // convert string to array
  2455. $slen = strlen($brd);
  2456. $newbrd = array();
  2457. for ($i = 0; $i < $slen; ++$i) {
  2458. $newbrd[$brd[$i]] = true;
  2459. }
  2460. $brd = $newbrd;
  2461. } elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
  2462. $brd = array('LRTB' => true);
  2463. }
  2464. if (!is_array($brd)) {
  2465. return;
  2466. }
  2467. // store current cell padding
  2468. $cp = $this->cell_padding;
  2469. // select border mode
  2470. if (isset($brd['mode'])) {
  2471. $mode = $brd['mode'];
  2472. unset($brd['mode']);
  2473. } else {
  2474. $mode = 'normal';
  2475. }
  2476. // process borders
  2477. foreach ($brd as $border => $style) {
  2478. $line_width = $this->LineWidth;
  2479. if (is_array($style) AND isset($style['width'])) {
  2480. // get border width
  2481. $line_width = $style['width'];
  2482. }
  2483. $adj = 0; // line width inside the cell
  2484. switch ($mode) {
  2485. case 'ext': {
  2486. $adj = 0;
  2487. break;
  2488. }
  2489. case 'int': {
  2490. $adj = $line_width;
  2491. break;
  2492. }
  2493. case 'normal':
  2494. default: {
  2495. $adj = ($line_width / 2);
  2496. break;
  2497. }
  2498. }
  2499. // correct internal cell padding if required to avoid overlap between text and lines
  2500. if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
  2501. $this->cell_padding['T'] = $adj;
  2502. }
  2503. if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
  2504. $this->cell_padding['R'] = $adj;
  2505. }
  2506. if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
  2507. $this->cell_padding['B'] = $adj;
  2508. }
  2509. if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
  2510. $this->cell_padding['L'] = $adj;
  2511. }
  2512. }
  2513. return array('T' => ($this->cell_padding['T'] - $cp['T']), 'R' => ($this->cell_padding['R'] - $cp['R']), 'B' => ($this->cell_padding['B'] - $cp['B']), 'L' => ($this->cell_padding['L'] - $cp['L']));
  2514. }
  2515. /**
  2516. * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
  2517. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  2518. * @param $margin (float) Distance from the bottom of the page.
  2519. * @public
  2520. * @since 1.0
  2521. * @see Cell(), MultiCell(), AcceptPageBreak()
  2522. */
  2523. public function SetAutoPageBreak($auto, $margin=0) {
  2524. $this->AutoPageBreak = $auto ? true : false;
  2525. $this->bMargin = $margin;
  2526. $this->PageBreakTrigger = $this->h - $margin;
  2527. }
  2528. /**
  2529. * Return the auto-page-break mode (true or false).
  2530. * @return boolean auto-page-break mode
  2531. * @public
  2532. * @since 5.9.088
  2533. */
  2534. public function getAutoPageBreak() {
  2535. return $this->AutoPageBreak;
  2536. }
  2537. /**
  2538. * Defines the way the document is to be displayed by the viewer.
  2539. * @param $zoom (mixed) The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
  2540. * @param $layout (string) The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
  2541. * @param $mode (string) A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
  2542. * @public
  2543. * @since 1.2
  2544. */
  2545. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  2546. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  2547. $this->ZoomMode = $zoom;
  2548. } else {
  2549. $this->Error('Incorrect zoom display mode: '.$zoom);
  2550. }
  2551. $this->LayoutMode = TCPDF_STATIC::getPageLayoutMode($layout);
  2552. $this->PageMode = TCPDF_STATIC::getPageMode($mode);
  2553. }
  2554. /**
  2555. * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
  2556. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  2557. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  2558. * @public
  2559. * @since 1.4
  2560. */
  2561. public function SetCompression($compress=true) {
  2562. $this->compress = false;
  2563. if (function_exists('gzcompress')) {
  2564. if ($compress) {
  2565. if ( !$this->pdfa_mode) {
  2566. $this->compress = true;
  2567. }
  2568. }
  2569. }
  2570. }
  2571. /**
  2572. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  2573. * @param $mode (boolean) If true force sRGB output intent.
  2574. * @public
  2575. * @since 5.9.121 (2011-09-28)
  2576. */
  2577. public function setSRGBmode($mode=false) {
  2578. $this->force_srgb = $mode ? true : false;
  2579. }
  2580. /**
  2581. * Turn on/off Unicode mode for document information dictionary (meta tags).
  2582. * This has effect only when unicode mode is set to false.
  2583. * @param $unicode (boolean) if true set the meta information in Unicode
  2584. * @since 5.9.027 (2010-12-01)
  2585. * @public
  2586. */
  2587. public function SetDocInfoUnicode($unicode=true) {
  2588. $this->docinfounicode = $unicode ? true : false;
  2589. }
  2590. /**
  2591. * Defines the title of the document.
  2592. * @param $title (string) The title.
  2593. * @public
  2594. * @since 1.2
  2595. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  2596. */
  2597. public function SetTitle($title) {
  2598. $this->title = $title;
  2599. }
  2600. /**
  2601. * Defines the subject of the document.
  2602. * @param $subject (string) The subject.
  2603. * @public
  2604. * @since 1.2
  2605. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  2606. */
  2607. public function SetSubject($subject) {
  2608. $this->subject = $subject;
  2609. }
  2610. /**
  2611. * Defines the author of the document.
  2612. * @param $author (string) The name of the author.
  2613. * @public
  2614. * @since 1.2
  2615. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  2616. */
  2617. public function SetAuthor($author) {
  2618. $this->author = $author;
  2619. }
  2620. /**
  2621. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  2622. * @param $keywords (string) The list of keywords.
  2623. * @public
  2624. * @since 1.2
  2625. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  2626. */
  2627. public function SetKeywords($keywords) {
  2628. $this->keywords = $keywords;
  2629. }
  2630. /**
  2631. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  2632. * @param $creator (string) The name of the creator.
  2633. * @public
  2634. * @since 1.2
  2635. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  2636. */
  2637. public function SetCreator($creator) {
  2638. $this->creator = $creator;
  2639. }
  2640. /**
  2641. * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
  2642. * @param $msg (string) The error message
  2643. * @public
  2644. * @since 1.0
  2645. */
  2646. public function Error($msg) {
  2647. // unset all class variables
  2648. $this->_destroy(true);
  2649. if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR) {
  2650. die('<strong>TCPDF ERROR: </strong>'.$msg);
  2651. } else {
  2652. throw new Exception('TCPDF ERROR: '.$msg);
  2653. }
  2654. }
  2655. /**
  2656. * This method begins the generation of the PDF document.
  2657. * It is not necessary to call it explicitly because AddPage() does it automatically.
  2658. * Note: no page is created by this method
  2659. * @public
  2660. * @since 1.0
  2661. * @see AddPage(), Close()
  2662. */
  2663. public function Open() {
  2664. $this->state = 1;
  2665. }
  2666. /**
  2667. * Terminates the PDF document.
  2668. * It is not necessary to call this method explicitly because Output() does it automatically.
  2669. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  2670. * @public
  2671. * @since 1.0
  2672. * @see Open(), Output()
  2673. */
  2674. public function Close() {
  2675. if ($this->state == 3) {
  2676. return;
  2677. }
  2678. if ($this->page == 0) {
  2679. $this->AddPage();
  2680. }
  2681. $this->endLayer();
  2682. if ($this->tcpdflink) {
  2683. // save current graphic settings
  2684. $gvars = $this->getGraphicVars();
  2685. $this->setEqualColumns();
  2686. $this->lastpage(true);
  2687. $this->SetAutoPageBreak(false);
  2688. $this->x = 0;
  2689. $this->y = $this->h - (1 / $this->k);
  2690. $this->lMargin = 0;
  2691. $this->_outSaveGraphicsState();
  2692. $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  2693. $this->SetFont($font, '', 1);
  2694. $this->setTextRenderingMode(0, false, false);
  2695. $msg = "\x50\x6f\x77\x65\x72\x65\x64\x20\x62\x79\x20\x54\x43\x50\x44\x46\x20\x28\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29";
  2696. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  2697. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  2698. $this->_outRestoreGraphicsState();
  2699. // restore graphic settings
  2700. $this->setGraphicVars($gvars);
  2701. }
  2702. // close page
  2703. $this->endPage();
  2704. // close document
  2705. $this->_enddoc();
  2706. // unset all class variables (except critical ones)
  2707. $this->_destroy(false);
  2708. }
  2709. /**
  2710. * Move pointer at the specified document page and update page dimensions.
  2711. * @param $pnum (int) page number (1 ... numpages)
  2712. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2713. * @public
  2714. * @since 2.1.000 (2008-01-07)
  2715. * @see getPage(), lastpage(), getNumPages()
  2716. */
  2717. public function setPage($pnum, $resetmargins=false) {
  2718. if (($pnum == $this->page) AND ($this->state == 2)) {
  2719. return;
  2720. }
  2721. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  2722. $this->state = 2;
  2723. // save current graphic settings
  2724. //$gvars = $this->getGraphicVars();
  2725. $oldpage = $this->page;
  2726. $this->page = $pnum;
  2727. $this->wPt = $this->pagedim[$this->page]['w'];
  2728. $this->hPt = $this->pagedim[$this->page]['h'];
  2729. $this->w = $this->pagedim[$this->page]['wk'];
  2730. $this->h = $this->pagedim[$this->page]['hk'];
  2731. $this->tMargin = $this->pagedim[$this->page]['tm'];
  2732. $this->bMargin = $this->pagedim[$this->page]['bm'];
  2733. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  2734. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  2735. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  2736. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  2737. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  2738. // restore graphic settings
  2739. //$this->setGraphicVars($gvars);
  2740. if ($resetmargins) {
  2741. $this->lMargin = $this->pagedim[$this->page]['olm'];
  2742. $this->rMargin = $this->pagedim[$this->page]['orm'];
  2743. $this->SetY($this->tMargin);
  2744. } else {
  2745. // account for booklet mode
  2746. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  2747. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  2748. $this->lMargin += $deltam;
  2749. $this->rMargin -= $deltam;
  2750. }
  2751. }
  2752. } else {
  2753. $this->Error('Wrong page number on setPage() function: '.$pnum);
  2754. }
  2755. }
  2756. /**
  2757. * Reset pointer to the last document page.
  2758. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2759. * @public
  2760. * @since 2.0.000 (2008-01-04)
  2761. * @see setPage(), getPage(), getNumPages()
  2762. */
  2763. public function lastPage($resetmargins=false) {
  2764. $this->setPage($this->getNumPages(), $resetmargins);
  2765. }
  2766. /**
  2767. * Get current document page number.
  2768. * @return int page number
  2769. * @public
  2770. * @since 2.1.000 (2008-01-07)
  2771. * @see setPage(), lastpage(), getNumPages()
  2772. */
  2773. public function getPage() {
  2774. return $this->page;
  2775. }
  2776. /**
  2777. * Get the total number of insered pages.
  2778. * @return int number of pages
  2779. * @public
  2780. * @since 2.1.000 (2008-01-07)
  2781. * @see setPage(), getPage(), lastpage()
  2782. */
  2783. public function getNumPages() {
  2784. return $this->numpages;
  2785. }
  2786. /**
  2787. * Adds a new TOC (Table Of Content) page to the document.
  2788. * @param $orientation (string) page orientation.
  2789. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  2790. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2791. * @public
  2792. * @since 5.0.001 (2010-05-06)
  2793. * @see AddPage(), startPage(), endPage(), endTOCPage()
  2794. */
  2795. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  2796. $this->AddPage($orientation, $format, $keepmargins, true);
  2797. }
  2798. /**
  2799. * Terminate the current TOC (Table Of Content) page
  2800. * @public
  2801. * @since 5.0.001 (2010-05-06)
  2802. * @see AddPage(), startPage(), endPage(), addTOCPage()
  2803. */
  2804. public function endTOCPage() {
  2805. $this->endPage(true);
  2806. }
  2807. /**
  2808. * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled).
  2809. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  2810. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2811. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  2812. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2813. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  2814. * @public
  2815. * @since 1.0
  2816. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2817. */
  2818. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  2819. if ($this->inxobj) {
  2820. // we are inside an XObject template
  2821. return;
  2822. }
  2823. if (!isset($this->original_lMargin) OR $keepmargins) {
  2824. $this->original_lMargin = $this->lMargin;
  2825. }
  2826. if (!isset($this->original_rMargin) OR $keepmargins) {
  2827. $this->original_rMargin = $this->rMargin;
  2828. }
  2829. // terminate previous page
  2830. $this->endPage();
  2831. // start new page
  2832. $this->startPage($orientation, $format, $tocpage);
  2833. }
  2834. /**
  2835. * Terminate the current page
  2836. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  2837. * @public
  2838. * @since 4.2.010 (2008-11-14)
  2839. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  2840. */
  2841. public function endPage($tocpage=false) {
  2842. // check if page is already closed
  2843. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  2844. return;
  2845. }
  2846. // print page footer
  2847. $this->setFooter();
  2848. // close page
  2849. $this->_endpage();
  2850. // mark page as closed
  2851. $this->pageopen[$this->page] = false;
  2852. if ($tocpage) {
  2853. $this->tocpage = false;
  2854. }
  2855. }
  2856. /**
  2857. * Starts a new page to the document. The page must be closed using the endPage() function.
  2858. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  2859. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2860. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  2861. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  2862. * @since 4.2.010 (2008-11-14)
  2863. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2864. * @public
  2865. */
  2866. public function startPage($orientation='', $format='', $tocpage=false) {
  2867. if ($tocpage) {
  2868. $this->tocpage = true;
  2869. }
  2870. // move page numbers of documents to be attached
  2871. if ($this->tocpage) {
  2872. // move reference to unexistent pages (used for page attachments)
  2873. // adjust outlines
  2874. $tmpoutlines = $this->outlines;
  2875. foreach ($tmpoutlines as $key => $outline) {
  2876. if (!$outline['f'] AND ($outline['p'] > $this->numpages)) {
  2877. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  2878. }
  2879. }
  2880. // adjust dests
  2881. $tmpdests = $this->dests;
  2882. foreach ($tmpdests as $key => $dest) {
  2883. if (!$dest['f'] AND ($dest['p'] > $this->numpages)) {
  2884. $this->dests[$key]['p'] = ($dest['p'] + 1);
  2885. }
  2886. }
  2887. // adjust links
  2888. $tmplinks = $this->links;
  2889. foreach ($tmplinks as $key => $link) {
  2890. if (!$link['f'] AND ($link['p'] > $this->numpages)) {
  2891. $this->links[$key]['p'] = ($link['p'] + 1);
  2892. }
  2893. }
  2894. }
  2895. if ($this->numpages > $this->page) {
  2896. // this page has been already added
  2897. $this->setPage($this->page + 1);
  2898. $this->SetY($this->tMargin);
  2899. return;
  2900. }
  2901. // start a new page
  2902. if ($this->state == 0) {
  2903. $this->Open();
  2904. }
  2905. ++$this->numpages;
  2906. $this->swapMargins($this->booklet);
  2907. // save current graphic settings
  2908. $gvars = $this->getGraphicVars();
  2909. // start new page
  2910. $this->_beginpage($orientation, $format);
  2911. // mark page as open
  2912. $this->pageopen[$this->page] = true;
  2913. // restore graphic settings
  2914. $this->setGraphicVars($gvars);
  2915. // mark this point
  2916. $this->setPageMark();
  2917. // print page header
  2918. $this->setHeader();
  2919. // restore graphic settings
  2920. $this->setGraphicVars($gvars);
  2921. // mark this point
  2922. $this->setPageMark();
  2923. // print table header (if any)
  2924. $this->setTableHeader();
  2925. // set mark for empty page check
  2926. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  2927. }
  2928. /**
  2929. * Set start-writing mark on current page stream used to put borders and fills.
  2930. * Borders and fills are always created after content and inserted on the position marked by this method.
  2931. * This function must be called after calling Image() function for a background image.
  2932. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  2933. * @public
  2934. * @since 4.0.016 (2008-07-30)
  2935. */
  2936. public function setPageMark() {
  2937. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  2938. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  2939. $this->setContentMark();
  2940. }
  2941. /**
  2942. * Set start-writing mark on selected page.
  2943. * Borders and fills are always created after content and inserted on the position marked by this method.
  2944. * @param $page (int) page number (default is the current page)
  2945. * @protected
  2946. * @since 4.6.021 (2009-07-20)
  2947. */
  2948. protected function setContentMark($page=0) {
  2949. if ($page <= 0) {
  2950. $page = $this->page;
  2951. }
  2952. if (isset($this->footerlen[$page])) {
  2953. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  2954. } else {
  2955. $this->cntmrk[$page] = $this->pagelen[$page];
  2956. }
  2957. }
  2958. /**
  2959. * Set header data.
  2960. * @param $ln (string) header image logo
  2961. * @param $lw (string) header image logo width in mm
  2962. * @param $ht (string) string to print as title on document header
  2963. * @param $hs (string) string to print on document header
  2964. * @param $tc (array) RGB array color for text.
  2965. * @param $lc (array) RGB array color for line.
  2966. * @public
  2967. */
  2968. public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
  2969. $this->header_logo = $ln;
  2970. $this->header_logo_width = $lw;
  2971. $this->header_title = $ht;
  2972. $this->header_string = $hs;
  2973. $this->header_text_color = $tc;
  2974. $this->header_line_color = $lc;
  2975. }
  2976. /**
  2977. * Set footer data.
  2978. * @param $tc (array) RGB array color for text.
  2979. * @param $lc (array) RGB array color for line.
  2980. * @public
  2981. */
  2982. public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
  2983. $this->footer_text_color = $tc;
  2984. $this->footer_line_color = $lc;
  2985. }
  2986. /**
  2987. * Returns header data:
  2988. * <ul><li>$ret['logo'] = logo image</li><li>$ret['logo_width'] = width of the image logo in user units</li><li>$ret['title'] = header title</li><li>$ret['string'] = header description string</li></ul>
  2989. * @return array()
  2990. * @public
  2991. * @since 4.0.012 (2008-07-24)
  2992. */
  2993. public function getHeaderData() {
  2994. $ret = array();
  2995. $ret['logo'] = $this->header_logo;
  2996. $ret['logo_width'] = $this->header_logo_width;
  2997. $ret['title'] = $this->header_title;
  2998. $ret['string'] = $this->header_string;
  2999. $ret['text_color'] = $this->header_text_color;
  3000. $ret['line_color'] = $this->header_line_color;
  3001. return $ret;
  3002. }
  3003. /**
  3004. * Set header margin.
  3005. * (minimum distance between header and top page margin)
  3006. * @param $hm (int) distance in user units
  3007. * @public
  3008. */
  3009. public function setHeaderMargin($hm=10) {
  3010. $this->header_margin = $hm;
  3011. }
  3012. /**
  3013. * Returns header margin in user units.
  3014. * @return float
  3015. * @since 4.0.012 (2008-07-24)
  3016. * @public
  3017. */
  3018. public function getHeaderMargin() {
  3019. return $this->header_margin;
  3020. }
  3021. /**
  3022. * Set footer margin.
  3023. * (minimum distance between footer and bottom page margin)
  3024. * @param $fm (int) distance in user units
  3025. * @public
  3026. */
  3027. public function setFooterMargin($fm=10) {
  3028. $this->footer_margin = $fm;
  3029. }
  3030. /**
  3031. * Returns footer margin in user units.
  3032. * @return float
  3033. * @since 4.0.012 (2008-07-24)
  3034. * @public
  3035. */
  3036. public function getFooterMargin() {
  3037. return $this->footer_margin;
  3038. }
  3039. /**
  3040. * Set a flag to print page header.
  3041. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3042. * @public
  3043. */
  3044. public function setPrintHeader($val=true) {
  3045. $this->print_header = $val ? true : false;
  3046. }
  3047. /**
  3048. * Set a flag to print page footer.
  3049. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3050. * @public
  3051. */
  3052. public function setPrintFooter($val=true) {
  3053. $this->print_footer = $val ? true : false;
  3054. }
  3055. /**
  3056. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3057. * @return float
  3058. * @public
  3059. */
  3060. public function getImageRBX() {
  3061. return $this->img_rb_x;
  3062. }
  3063. /**
  3064. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3065. * @return float
  3066. * @public
  3067. */
  3068. public function getImageRBY() {
  3069. return $this->img_rb_y;
  3070. }
  3071. /**
  3072. * Reset the xobject template used by Header() method.
  3073. * @public
  3074. */
  3075. public function resetHeaderTemplate() {
  3076. $this->header_xobjid = false;
  3077. }
  3078. /**
  3079. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3080. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3081. * @public
  3082. */
  3083. public function setHeaderTemplateAutoreset($val=true) {
  3084. $this->header_xobj_autoreset = $val ? true : false;
  3085. }
  3086. /**
  3087. * This method is used to render the page header.
  3088. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3089. * @public
  3090. */
  3091. public function Header() {
  3092. if ($this->header_xobjid === false) {
  3093. // start a new XObject Template
  3094. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3095. $headerfont = $this->getHeaderFont();
  3096. $headerdata = $this->getHeaderData();
  3097. $this->y = $this->header_margin;
  3098. if ($this->rtl) {
  3099. $this->x = $this->w - $this->original_rMargin;
  3100. } else {
  3101. $this->x = $this->original_lMargin;
  3102. }
  3103. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3104. $imgtype = TCPDF_IMAGES::getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3105. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3106. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3107. } elseif ($imgtype == 'svg') {
  3108. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3109. } else {
  3110. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3111. }
  3112. $imgy = $this->getImageRBY();
  3113. } else {
  3114. $imgy = $this->y;
  3115. }
  3116. $cell_height = $this->getCellHeight($headerfont[2] / $this->k);
  3117. // set starting margin for text data cell
  3118. if ($this->getRTL()) {
  3119. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3120. } else {
  3121. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3122. }
  3123. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3124. $this->SetTextColorArray($this->header_text_color);
  3125. // header title
  3126. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3127. $this->SetX($header_x);
  3128. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3129. // header string
  3130. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3131. $this->SetX($header_x);
  3132. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3133. // print an ending header line
  3134. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
  3135. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3136. if ($this->rtl) {
  3137. $this->SetX($this->original_rMargin);
  3138. } else {
  3139. $this->SetX($this->original_lMargin);
  3140. }
  3141. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3142. $this->endTemplate();
  3143. }
  3144. // print header template
  3145. $x = 0;
  3146. $dx = 0;
  3147. if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
  3148. // adjust margins for booklet mode
  3149. $dx = ($this->original_lMargin - $this->original_rMargin);
  3150. }
  3151. if ($this->rtl) {
  3152. $x = $this->w + $dx;
  3153. } else {
  3154. $x = 0 + $dx;
  3155. }
  3156. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  3157. if ($this->header_xobj_autoreset) {
  3158. // reset header xobject template at each page
  3159. $this->header_xobjid = false;
  3160. }
  3161. }
  3162. /**
  3163. * This method is used to render the page footer.
  3164. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3165. * @public
  3166. */
  3167. public function Footer() {
  3168. $cur_y = $this->y;
  3169. $this->SetTextColorArray($this->footer_text_color);
  3170. //set style for cell border
  3171. $line_width = (0.85 / $this->k);
  3172. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
  3173. //print document barcode
  3174. $barcode = $this->getBarcode();
  3175. if (!empty($barcode)) {
  3176. $this->Ln($line_width);
  3177. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  3178. $style = array(
  3179. 'position' => $this->rtl?'R':'L',
  3180. 'align' => $this->rtl?'R':'L',
  3181. 'stretch' => false,
  3182. 'fitwidth' => true,
  3183. 'cellfitalign' => '',
  3184. 'border' => false,
  3185. 'padding' => 0,
  3186. 'fgcolor' => array(0,0,0),
  3187. 'bgcolor' => false,
  3188. 'text' => false
  3189. );
  3190. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  3191. }
  3192. $w_page = isset($this->l['w_page']) ? $this->l['w_page'].' ' : '';
  3193. if (empty($this->pagegroups)) {
  3194. $pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  3195. } else {
  3196. $pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  3197. }
  3198. $this->SetY($cur_y);
  3199. //Print page number
  3200. if ($this->getRTL()) {
  3201. $this->SetX($this->original_rMargin);
  3202. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  3203. } else {
  3204. $this->SetX($this->original_lMargin);
  3205. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  3206. }
  3207. }
  3208. /**
  3209. * This method is used to render the page header.
  3210. * @protected
  3211. * @since 4.0.012 (2008-07-24)
  3212. */
  3213. protected function setHeader() {
  3214. if (!$this->print_header OR ($this->state != 2)) {
  3215. return;
  3216. }
  3217. $this->InHeader = true;
  3218. $this->setGraphicVars($this->default_graphic_vars);
  3219. $temp_thead = $this->thead;
  3220. $temp_theadMargins = $this->theadMargins;
  3221. $lasth = $this->lasth;
  3222. $newline = $this->newline;
  3223. $this->_outSaveGraphicsState();
  3224. $this->rMargin = $this->original_rMargin;
  3225. $this->lMargin = $this->original_lMargin;
  3226. $this->SetCellPadding(0);
  3227. //set current position
  3228. if ($this->rtl) {
  3229. $this->SetXY($this->original_rMargin, $this->header_margin);
  3230. } else {
  3231. $this->SetXY($this->original_lMargin, $this->header_margin);
  3232. }
  3233. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  3234. $this->Header();
  3235. //restore position
  3236. if ($this->rtl) {
  3237. $this->SetXY($this->original_rMargin, $this->tMargin);
  3238. } else {
  3239. $this->SetXY($this->original_lMargin, $this->tMargin);
  3240. }
  3241. $this->_outRestoreGraphicsState();
  3242. $this->lasth = $lasth;
  3243. $this->thead = $temp_thead;
  3244. $this->theadMargins = $temp_theadMargins;
  3245. $this->newline = $newline;
  3246. $this->InHeader = false;
  3247. }
  3248. /**
  3249. * This method is used to render the page footer.
  3250. * @protected
  3251. * @since 4.0.012 (2008-07-24)
  3252. */
  3253. protected function setFooter() {
  3254. if ($this->state != 2) {
  3255. return;
  3256. }
  3257. $this->InFooter = true;
  3258. // save current graphic settings
  3259. $gvars = $this->getGraphicVars();
  3260. // mark this point
  3261. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  3262. $this->_out("\n");
  3263. if ($this->print_footer) {
  3264. $this->setGraphicVars($this->default_graphic_vars);
  3265. $this->current_column = 0;
  3266. $this->num_columns = 1;
  3267. $temp_thead = $this->thead;
  3268. $temp_theadMargins = $this->theadMargins;
  3269. $lasth = $this->lasth;
  3270. $this->_outSaveGraphicsState();
  3271. $this->rMargin = $this->original_rMargin;
  3272. $this->lMargin = $this->original_lMargin;
  3273. $this->SetCellPadding(0);
  3274. //set current position
  3275. $footer_y = $this->h - $this->footer_margin;
  3276. if ($this->rtl) {
  3277. $this->SetXY($this->original_rMargin, $footer_y);
  3278. } else {
  3279. $this->SetXY($this->original_lMargin, $footer_y);
  3280. }
  3281. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  3282. $this->Footer();
  3283. //restore position
  3284. if ($this->rtl) {
  3285. $this->SetXY($this->original_rMargin, $this->tMargin);
  3286. } else {
  3287. $this->SetXY($this->original_lMargin, $this->tMargin);
  3288. }
  3289. $this->_outRestoreGraphicsState();
  3290. $this->lasth = $lasth;
  3291. $this->thead = $temp_thead;
  3292. $this->theadMargins = $temp_theadMargins;
  3293. }
  3294. // restore graphic settings
  3295. $this->setGraphicVars($gvars);
  3296. $this->current_column = $gvars['current_column'];
  3297. $this->num_columns = $gvars['num_columns'];
  3298. // calculate footer length
  3299. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  3300. $this->InFooter = false;
  3301. }
  3302. /**
  3303. * Check if we are on the page body (excluding page header and footer).
  3304. * @return true if we are not in page header nor in page footer, false otherwise.
  3305. * @protected
  3306. * @since 5.9.091 (2011-06-15)
  3307. */
  3308. protected function inPageBody() {
  3309. return (($this->InHeader === false) AND ($this->InFooter === false));
  3310. }
  3311. /**
  3312. * This method is used to render the table header on new page (if any).
  3313. * @protected
  3314. * @since 4.5.030 (2009-03-25)
  3315. */
  3316. protected function setTableHeader() {
  3317. if ($this->num_columns > 1) {
  3318. // multi column mode
  3319. return;
  3320. }
  3321. if (isset($this->theadMargins['top'])) {
  3322. // restore the original top-margin
  3323. $this->tMargin = $this->theadMargins['top'];
  3324. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3325. $this->y = $this->tMargin;
  3326. }
  3327. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  3328. // set margins
  3329. $prev_lMargin = $this->lMargin;
  3330. $prev_rMargin = $this->rMargin;
  3331. $prev_cell_padding = $this->cell_padding;
  3332. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  3333. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  3334. $this->cell_padding = $this->theadMargins['cell_padding'];
  3335. if ($this->rtl) {
  3336. $this->x = $this->w - $this->rMargin;
  3337. } else {
  3338. $this->x = $this->lMargin;
  3339. }
  3340. // account for special "cell" mode
  3341. if ($this->theadMargins['cell']) {
  3342. if ($this->rtl) {
  3343. $this->x -= $this->cell_padding['R'];
  3344. } else {
  3345. $this->x += $this->cell_padding['L'];
  3346. }
  3347. }
  3348. $gvars = $this->getGraphicVars();
  3349. if (!empty($this->theadMargins['gvars'])) {
  3350. // set the correct graphic style
  3351. $this->setGraphicVars($this->theadMargins['gvars']);
  3352. $this->rMargin = $gvars['rMargin'];
  3353. $this->lMargin = $gvars['lMargin'];
  3354. }
  3355. // print table header
  3356. $this->writeHTML($this->thead, false, false, false, false, '');
  3357. $this->setGraphicVars($gvars);
  3358. // set new top margin to skip the table headers
  3359. if (!isset($this->theadMargins['top'])) {
  3360. $this->theadMargins['top'] = $this->tMargin;
  3361. }
  3362. // store end of header position
  3363. if (!isset($this->columns[0]['th'])) {
  3364. $this->columns[0]['th'] = array();
  3365. }
  3366. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  3367. $this->tMargin = $this->y;
  3368. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3369. $this->lasth = 0;
  3370. $this->lMargin = $prev_lMargin;
  3371. $this->rMargin = $prev_rMargin;
  3372. $this->cell_padding = $prev_cell_padding;
  3373. }
  3374. }
  3375. /**
  3376. * Returns the current page number.
  3377. * @return int page number
  3378. * @public
  3379. * @since 1.0
  3380. * @see getAliasNbPages()
  3381. */
  3382. public function PageNo() {
  3383. return $this->page;
  3384. }
  3385. /**
  3386. * Returns the array of spot colors.
  3387. * @return (array) Spot colors array.
  3388. * @public
  3389. * @since 6.0.038 (2013-09-30)
  3390. */
  3391. public function getAllSpotColors() {
  3392. return $this->spot_colors;
  3393. }
  3394. /**
  3395. * Defines a new spot color.
  3396. * It can be expressed in RGB components or gray scale.
  3397. * The method can be called before the first page is created and the value is retained from page to page.
  3398. * @param $name (string) Full name of the spot color.
  3399. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  3400. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  3401. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  3402. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  3403. * @public
  3404. * @since 4.0.024 (2008-09-12)
  3405. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3406. */
  3407. public function AddSpotColor($name, $c, $m, $y, $k) {
  3408. if (!isset($this->spot_colors[$name])) {
  3409. $i = (1 + count($this->spot_colors));
  3410. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  3411. }
  3412. }
  3413. /**
  3414. * Set the spot color for the specified type ('draw', 'fill', 'text').
  3415. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3416. * @param $name (string) Name of the spot color.
  3417. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3418. * @return (string) PDF color command.
  3419. * @public
  3420. * @since 5.9.125 (2011-10-03)
  3421. */
  3422. public function setSpotColor($type, $name, $tint=100) {
  3423. $spotcolor = TCPDF_COLORS::getSpotColor($name, $this->spot_colors);
  3424. if ($spotcolor === false) {
  3425. $this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
  3426. }
  3427. $tint = (max(0, min(100, $tint)) / 100);
  3428. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  3429. switch ($type) {
  3430. case 'draw': {
  3431. $pdfcolor .= sprintf('CS %F SCN', $tint);
  3432. $this->DrawColor = $pdfcolor;
  3433. $this->strokecolor = $spotcolor;
  3434. break;
  3435. }
  3436. case 'fill': {
  3437. $pdfcolor .= sprintf('cs %F scn', $tint);
  3438. $this->FillColor = $pdfcolor;
  3439. $this->bgcolor = $spotcolor;
  3440. break;
  3441. }
  3442. case 'text': {
  3443. $pdfcolor .= sprintf('cs %F scn', $tint);
  3444. $this->TextColor = $pdfcolor;
  3445. $this->fgcolor = $spotcolor;
  3446. break;
  3447. }
  3448. }
  3449. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3450. if ($this->state == 2) {
  3451. $this->_out($pdfcolor);
  3452. }
  3453. if ($this->inxobj) {
  3454. // we are inside an XObject template
  3455. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  3456. }
  3457. return $pdfcolor;
  3458. }
  3459. /**
  3460. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  3461. * @param $name (string) Name of the spot color.
  3462. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3463. * @public
  3464. * @since 4.0.024 (2008-09-12)
  3465. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3466. */
  3467. public function SetDrawSpotColor($name, $tint=100) {
  3468. $this->setSpotColor('draw', $name, $tint);
  3469. }
  3470. /**
  3471. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  3472. * @param $name (string) Name of the spot color.
  3473. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3474. * @public
  3475. * @since 4.0.024 (2008-09-12)
  3476. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  3477. */
  3478. public function SetFillSpotColor($name, $tint=100) {
  3479. $this->setSpotColor('fill', $name, $tint);
  3480. }
  3481. /**
  3482. * Defines the spot color used for text.
  3483. * @param $name (string) Name of the spot color.
  3484. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3485. * @public
  3486. * @since 4.0.024 (2008-09-12)
  3487. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  3488. */
  3489. public function SetTextSpotColor($name, $tint=100) {
  3490. $this->setSpotColor('text', $name, $tint);
  3491. }
  3492. /**
  3493. * Set the color array for the specified type ('draw', 'fill', 'text').
  3494. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3495. * The method can be called before the first page is created and the value is retained from page to page.
  3496. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3497. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  3498. * @param $ret (boolean) If true do not send the PDF command.
  3499. * @return (string) The PDF command or empty string.
  3500. * @public
  3501. * @since 3.1.000 (2008-06-11)
  3502. */
  3503. public function setColorArray($type, $color, $ret=false) {
  3504. if (is_array($color)) {
  3505. $color = array_values($color);
  3506. // component: grey, RGB red or CMYK cyan
  3507. $c = isset($color[0]) ? $color[0] : -1;
  3508. // component: RGB green or CMYK magenta
  3509. $m = isset($color[1]) ? $color[1] : -1;
  3510. // component: RGB blue or CMYK yellow
  3511. $y = isset($color[2]) ? $color[2] : -1;
  3512. // component: CMYK black
  3513. $k = isset($color[3]) ? $color[3] : -1;
  3514. // color name
  3515. $name = isset($color[4]) ? $color[4] : '';
  3516. if ($c >= 0) {
  3517. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  3518. }
  3519. }
  3520. return '';
  3521. }
  3522. /**
  3523. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  3524. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3525. * The method can be called before the first page is created and the value is retained from page to page.
  3526. * @param $color (array) Array of colors (1, 3 or 4 values).
  3527. * @param $ret (boolean) If true do not send the PDF command.
  3528. * @return string the PDF command
  3529. * @public
  3530. * @since 3.1.000 (2008-06-11)
  3531. * @see SetDrawColor()
  3532. */
  3533. public function SetDrawColorArray($color, $ret=false) {
  3534. return $this->setColorArray('draw', $color, $ret);
  3535. }
  3536. /**
  3537. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  3538. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3539. * The method can be called before the first page is created and the value is retained from page to page.
  3540. * @param $color (array) Array of colors (1, 3 or 4 values).
  3541. * @param $ret (boolean) If true do not send the PDF command.
  3542. * @public
  3543. * @since 3.1.000 (2008-6-11)
  3544. * @see SetFillColor()
  3545. */
  3546. public function SetFillColorArray($color, $ret=false) {
  3547. return $this->setColorArray('fill', $color, $ret);
  3548. }
  3549. /**
  3550. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  3551. * The method can be called before the first page is created and the value is retained from page to page.
  3552. * @param $color (array) Array of colors (1, 3 or 4 values).
  3553. * @param $ret (boolean) If true do not send the PDF command.
  3554. * @public
  3555. * @since 3.1.000 (2008-6-11)
  3556. * @see SetFillColor()
  3557. */
  3558. public function SetTextColorArray($color, $ret=false) {
  3559. return $this->setColorArray('text', $color, $ret);
  3560. }
  3561. /**
  3562. * Defines the color used by the specified type ('draw', 'fill', 'text').
  3563. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3564. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3565. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3566. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3567. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3568. * @param $ret (boolean) If true do not send the command.
  3569. * @param $name (string) spot color name (if any)
  3570. * @return (string) The PDF command or empty string.
  3571. * @public
  3572. * @since 5.9.125 (2011-10-03)
  3573. */
  3574. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3575. // set default values
  3576. if (!is_numeric($col1)) {
  3577. $col1 = 0;
  3578. }
  3579. if (!is_numeric($col2)) {
  3580. $col2 = -1;
  3581. }
  3582. if (!is_numeric($col3)) {
  3583. $col3 = -1;
  3584. }
  3585. if (!is_numeric($col4)) {
  3586. $col4 = -1;
  3587. }
  3588. // set color by case
  3589. $suffix = '';
  3590. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  3591. // Grey scale
  3592. $col1 = max(0, min(255, $col1));
  3593. $intcolor = array('G' => $col1);
  3594. $pdfcolor = sprintf('%F ', ($col1 / 255));
  3595. $suffix = 'g';
  3596. } elseif ($col4 == -1) {
  3597. // RGB
  3598. $col1 = max(0, min(255, $col1));
  3599. $col2 = max(0, min(255, $col2));
  3600. $col3 = max(0, min(255, $col3));
  3601. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  3602. $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  3603. $suffix = 'rg';
  3604. } else {
  3605. $col1 = max(0, min(100, $col1));
  3606. $col2 = max(0, min(100, $col2));
  3607. $col3 = max(0, min(100, $col3));
  3608. $col4 = max(0, min(100, $col4));
  3609. if (empty($name)) {
  3610. // CMYK
  3611. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  3612. $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  3613. $suffix = 'k';
  3614. } else {
  3615. // SPOT COLOR
  3616. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  3617. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  3618. $pdfcolor = $this->setSpotColor($type, $name, 100);
  3619. }
  3620. }
  3621. switch ($type) {
  3622. case 'draw': {
  3623. $pdfcolor .= strtoupper($suffix);
  3624. $this->DrawColor = $pdfcolor;
  3625. $this->strokecolor = $intcolor;
  3626. break;
  3627. }
  3628. case 'fill': {
  3629. $pdfcolor .= $suffix;
  3630. $this->FillColor = $pdfcolor;
  3631. $this->bgcolor = $intcolor;
  3632. break;
  3633. }
  3634. case 'text': {
  3635. $pdfcolor .= $suffix;
  3636. $this->TextColor = $pdfcolor;
  3637. $this->fgcolor = $intcolor;
  3638. break;
  3639. }
  3640. }
  3641. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3642. if (($type != 'text') AND ($this->state == 2)) {
  3643. if (!$ret) {
  3644. $this->_out($pdfcolor);
  3645. }
  3646. return $pdfcolor;
  3647. }
  3648. return '';
  3649. }
  3650. /**
  3651. * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
  3652. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3653. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3654. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3655. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3656. * @param $ret (boolean) If true do not send the command.
  3657. * @param $name (string) spot color name (if any)
  3658. * @return string the PDF command
  3659. * @public
  3660. * @since 1.3
  3661. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  3662. */
  3663. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3664. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  3665. }
  3666. /**
  3667. * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
  3668. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3669. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3670. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3671. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3672. * @param $ret (boolean) If true do not send the command.
  3673. * @param $name (string) Spot color name (if any).
  3674. * @return (string) The PDF command.
  3675. * @public
  3676. * @since 1.3
  3677. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  3678. */
  3679. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3680. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  3681. }
  3682. /**
  3683. * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
  3684. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3685. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3686. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3687. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3688. * @param $ret (boolean) If true do not send the command.
  3689. * @param $name (string) Spot color name (if any).
  3690. * @return (string) Empty string.
  3691. * @public
  3692. * @since 1.3
  3693. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  3694. */
  3695. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3696. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  3697. }
  3698. /**
  3699. * Returns the length of a string in user unit. A font must be selected.<br>
  3700. * @param $s (string) The string whose length is to be computed
  3701. * @param $fontname (string) Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
  3702. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-through</li><li>O: overline</li></ul> or any combination. The default value is regular.
  3703. * @param $fontsize (float) Font size in points. The default value is the current size.
  3704. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3705. * @return mixed int total string length or array of characted widths
  3706. * @author Nicola Asuni
  3707. * @public
  3708. * @since 1.2
  3709. */
  3710. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3711. return $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont), $s, $this->tmprtl, $this->isunicode, $this->CurrentFont), $fontname, $fontstyle, $fontsize, $getarray);
  3712. }
  3713. /**
  3714. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  3715. * @param $sa (string) The array of chars whose total length is to be computed
  3716. * @param $fontname (string) Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
  3717. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular.
  3718. * @param $fontsize (float) Font size in points. The default value is the current size.
  3719. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3720. * @return mixed int total string length or array of characted widths
  3721. * @author Nicola Asuni
  3722. * @public
  3723. * @since 2.4.000 (2008-03-06)
  3724. */
  3725. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3726. // store current values
  3727. if (!TCPDF_STATIC::empty_string($fontname)) {
  3728. $prev_FontFamily = $this->FontFamily;
  3729. $prev_FontStyle = $this->FontStyle;
  3730. $prev_FontSizePt = $this->FontSizePt;
  3731. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  3732. }
  3733. // convert UTF-8 array to Latin1 if required
  3734. if ($this->isunicode AND (!$this->isUnicodeFont())) {
  3735. $sa = TCPDF_FONTS::UTF8ArrToLatin1Arr($sa);
  3736. }
  3737. $w = 0; // total width
  3738. $wa = array(); // array of characters widths
  3739. foreach ($sa as $ck => $char) {
  3740. // character width
  3741. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  3742. $wa[] = $cw;
  3743. $w += $cw;
  3744. }
  3745. // restore previous values
  3746. if (!TCPDF_STATIC::empty_string($fontname)) {
  3747. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  3748. }
  3749. if ($getarray) {
  3750. return $wa;
  3751. }
  3752. return $w;
  3753. }
  3754. /**
  3755. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
  3756. * @param $char (int) The char code whose length is to be returned
  3757. * @param $notlast (boolean) If false ignore the font-spacing.
  3758. * @return float char width
  3759. * @author Nicola Asuni
  3760. * @public
  3761. * @since 2.4.000 (2008-03-06)
  3762. */
  3763. public function GetCharWidth($char, $notlast=true) {
  3764. // get raw width
  3765. $chw = $this->getRawCharWidth($char);
  3766. if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
  3767. // increase/decrease font spacing
  3768. $chw += $this->font_spacing;
  3769. }
  3770. if ($this->font_stretching != 100) {
  3771. // fixed stretching mode
  3772. $chw *= ($this->font_stretching / 100);
  3773. }
  3774. return $chw;
  3775. }
  3776. /**
  3777. * Returns the length of the char in user unit for the current font.
  3778. * @param $char (int) The char code whose length is to be returned
  3779. * @return float char width
  3780. * @author Nicola Asuni
  3781. * @public
  3782. * @since 5.9.000 (2010-09-28)
  3783. */
  3784. public function getRawCharWidth($char) {
  3785. if ($char == 173) {
  3786. // SHY character will not be printed
  3787. return (0);
  3788. }
  3789. if (isset($this->CurrentFont['cw'][$char])) {
  3790. $w = $this->CurrentFont['cw'][$char];
  3791. } elseif (isset($this->CurrentFont['dw'])) {
  3792. // default width
  3793. $w = $this->CurrentFont['dw'];
  3794. } elseif (isset($this->CurrentFont['cw'][32])) {
  3795. // default width
  3796. $w = $this->CurrentFont['cw'][32];
  3797. } else {
  3798. $w = 600;
  3799. }
  3800. return $this->getAbsFontMeasure($w);
  3801. }
  3802. /**
  3803. * Returns the numbero of characters in a string.
  3804. * @param $s (string) The input string.
  3805. * @return int number of characters
  3806. * @public
  3807. * @since 2.0.0001 (2008-01-07)
  3808. */
  3809. public function GetNumChars($s) {
  3810. if ($this->isUnicodeFont()) {
  3811. return count(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont));
  3812. }
  3813. return strlen($s);
  3814. }
  3815. /**
  3816. * Fill the list of available fonts ($this->fontlist).
  3817. * @protected
  3818. * @since 4.0.013 (2008-07-28)
  3819. */
  3820. protected function getFontsList() {
  3821. if (($fontsdir = opendir(TCPDF_FONTS::_getfontpath())) !== false) {
  3822. while (($file = readdir($fontsdir)) !== false) {
  3823. if (substr($file, -4) == '.php') {
  3824. array_push($this->fontlist, strtolower(basename($file, '.php')));
  3825. }
  3826. }
  3827. closedir($fontsdir);
  3828. }
  3829. }
  3830. /**
  3831. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  3832. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  3833. * The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
  3834. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  3835. * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
  3836. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  3837. * @return array containing the font data, or false in case of error.
  3838. * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
  3839. * @public
  3840. * @since 1.5
  3841. * @see SetFont(), setFontSubsetting()
  3842. */
  3843. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  3844. if ($subset === 'default') {
  3845. $subset = $this->font_subsetting;
  3846. }
  3847. if ($this->pdfa_mode) {
  3848. $subset = false;
  3849. }
  3850. if (TCPDF_STATIC::empty_string($family)) {
  3851. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  3852. $family = $this->FontFamily;
  3853. } else {
  3854. $this->Error('Empty font family');
  3855. }
  3856. }
  3857. // move embedded styles on $style
  3858. if (substr($family, -1) == 'I') {
  3859. $style .= 'I';
  3860. $family = substr($family, 0, -1);
  3861. }
  3862. if (substr($family, -1) == 'B') {
  3863. $style .= 'B';
  3864. $family = substr($family, 0, -1);
  3865. }
  3866. // normalize family name
  3867. $family = strtolower($family);
  3868. if ((!$this->isunicode) AND ($family == 'arial')) {
  3869. $family = 'helvetica';
  3870. }
  3871. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  3872. $style = '';
  3873. }
  3874. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  3875. // all fonts must be embedded
  3876. $family = 'pdfa'.$family;
  3877. }
  3878. $tempstyle = strtoupper($style);
  3879. $style = '';
  3880. // underline
  3881. if (strpos($tempstyle, 'U') !== false) {
  3882. $this->underline = true;
  3883. } else {
  3884. $this->underline = false;
  3885. }
  3886. // line-through (deleted)
  3887. if (strpos($tempstyle, 'D') !== false) {
  3888. $this->linethrough = true;
  3889. } else {
  3890. $this->linethrough = false;
  3891. }
  3892. // overline
  3893. if (strpos($tempstyle, 'O') !== false) {
  3894. $this->overline = true;
  3895. } else {
  3896. $this->overline = false;
  3897. }
  3898. // bold
  3899. if (strpos($tempstyle, 'B') !== false) {
  3900. $style .= 'B';
  3901. }
  3902. // oblique
  3903. if (strpos($tempstyle, 'I') !== false) {
  3904. $style .= 'I';
  3905. }
  3906. $bistyle = $style;
  3907. $fontkey = $family.$style;
  3908. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  3909. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  3910. // check if the font has been already added
  3911. $fb = $this->getFontBuffer($fontkey);
  3912. if ($fb !== false) {
  3913. if ($this->inxobj) {
  3914. // we are inside an XObject template
  3915. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  3916. }
  3917. return $fontdata;
  3918. }
  3919. // get specified font directory (if any)
  3920. $fontdir = false;
  3921. if (!TCPDF_STATIC::empty_string($fontfile)) {
  3922. $fontdir = dirname($fontfile);
  3923. if (TCPDF_STATIC::empty_string($fontdir) OR ($fontdir == '.')) {
  3924. $fontdir = '';
  3925. } else {
  3926. $fontdir .= '/';
  3927. }
  3928. }
  3929. // true when the font style variation is missing
  3930. $missing_style = false;
  3931. // search and include font file
  3932. if (TCPDF_STATIC::empty_string($fontfile) OR (!@TCPDF_STATIC::file_exists($fontfile))) {
  3933. // build a standard filenames for specified font
  3934. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  3935. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3936. if (TCPDF_STATIC::empty_string($fontfile)) {
  3937. $missing_style = true;
  3938. // try to remove the style part
  3939. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  3940. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3941. }
  3942. }
  3943. // include font file
  3944. if (!TCPDF_STATIC::empty_string($fontfile) AND (@TCPDF_STATIC::file_exists($fontfile))) {
  3945. include($fontfile);
  3946. } else {
  3947. $this->Error('Could not include font definition file: '.$family.'');
  3948. }
  3949. // check font parameters
  3950. if ((!isset($type)) OR (!isset($cw))) {
  3951. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  3952. }
  3953. // SET default parameters
  3954. if (!isset($file) OR TCPDF_STATIC::empty_string($file)) {
  3955. $file = '';
  3956. }
  3957. if (!isset($enc) OR TCPDF_STATIC::empty_string($enc)) {
  3958. $enc = '';
  3959. }
  3960. if (!isset($cidinfo) OR TCPDF_STATIC::empty_string($cidinfo)) {
  3961. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  3962. $cidinfo['uni2cid'] = array();
  3963. }
  3964. if (!isset($ctg) OR TCPDF_STATIC::empty_string($ctg)) {
  3965. $ctg = '';
  3966. }
  3967. if (!isset($desc) OR TCPDF_STATIC::empty_string($desc)) {
  3968. $desc = array();
  3969. }
  3970. if (!isset($up) OR TCPDF_STATIC::empty_string($up)) {
  3971. $up = -100;
  3972. }
  3973. if (!isset($ut) OR TCPDF_STATIC::empty_string($ut)) {
  3974. $ut = 50;
  3975. }
  3976. if (!isset($cw) OR TCPDF_STATIC::empty_string($cw)) {
  3977. $cw = array();
  3978. }
  3979. if (!isset($dw) OR TCPDF_STATIC::empty_string($dw)) {
  3980. // set default width
  3981. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  3982. $dw = $desc['MissingWidth'];
  3983. } elseif (isset($cw[32])) {
  3984. $dw = $cw[32];
  3985. } else {
  3986. $dw = 600;
  3987. }
  3988. }
  3989. ++$this->numfonts;
  3990. if ($type == 'core') {
  3991. $name = $this->CoreFonts[$fontkey];
  3992. $subset = false;
  3993. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  3994. $subset = false;
  3995. } elseif ($type == 'TrueTypeUnicode') {
  3996. $enc = 'Identity-H';
  3997. } elseif ($type == 'cidfont0') {
  3998. if ($this->pdfa_mode) {
  3999. $this->Error('All fonts must be embedded in PDF/A mode!');
  4000. }
  4001. } else {
  4002. $this->Error('Unknow font type: '.$type.'');
  4003. }
  4004. // set name if unset
  4005. if (!isset($name) OR empty($name)) {
  4006. $name = $fontkey;
  4007. }
  4008. // create artificial font style variations if missing (only works with non-embedded fonts)
  4009. if (($type != 'core') AND $missing_style) {
  4010. // style variations
  4011. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4012. $name .= $styles[$bistyle];
  4013. // artificial bold
  4014. if (strpos($bistyle, 'B') !== false) {
  4015. if (isset($desc['StemV'])) {
  4016. // from normal to bold
  4017. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4018. } else {
  4019. // bold
  4020. $desc['StemV'] = 123;
  4021. }
  4022. }
  4023. // artificial italic
  4024. if (strpos($bistyle, 'I') !== false) {
  4025. if (isset($desc['ItalicAngle'])) {
  4026. $desc['ItalicAngle'] -= 11;
  4027. } else {
  4028. $desc['ItalicAngle'] = -11;
  4029. }
  4030. if (isset($desc['Flags'])) {
  4031. $desc['Flags'] |= 64; //bit 7
  4032. } else {
  4033. $desc['Flags'] = 64;
  4034. }
  4035. }
  4036. }
  4037. // check if the array of characters bounding boxes is defined
  4038. if (!isset($cbbox)) {
  4039. $cbbox = array();
  4040. }
  4041. // initialize subsetchars
  4042. $subsetchars = array_fill(0, 255, true);
  4043. $this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'cbbox' => $cbbox, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars));
  4044. if ($this->inxobj) {
  4045. // we are inside an XObject template
  4046. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4047. }
  4048. if (isset($diff) AND (!empty($diff))) {
  4049. //Search existing encodings
  4050. $d = 0;
  4051. $nb = count($this->diffs);
  4052. for ($i=1; $i <= $nb; ++$i) {
  4053. if ($this->diffs[$i] == $diff) {
  4054. $d = $i;
  4055. break;
  4056. }
  4057. }
  4058. if ($d == 0) {
  4059. $d = $nb + 1;
  4060. $this->diffs[$d] = $diff;
  4061. }
  4062. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4063. }
  4064. if (!TCPDF_STATIC::empty_string($file)) {
  4065. if (!isset($this->FontFiles[$file])) {
  4066. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4067. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4068. } elseif ($type != 'core') {
  4069. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4070. }
  4071. } else {
  4072. // update fontkeys that are sharing this font file
  4073. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4074. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4075. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4076. }
  4077. }
  4078. }
  4079. return $fontdata;
  4080. }
  4081. /**
  4082. * Sets the font used to print character strings.
  4083. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4084. * The method can be called before the first page is created and the font is retained from page to page.
  4085. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4086. * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the K_PATH_FONTS constant</li></ul><br />
  4087. * @param $family (string) Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
  4088. * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
  4089. * @param $size (float) Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
  4090. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4091. * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
  4092. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4093. * @author Nicola Asuni
  4094. * @public
  4095. * @since 1.0
  4096. * @see AddFont(), SetFontSize()
  4097. */
  4098. public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
  4099. //Select a font; size given in points
  4100. if ($size === null) {
  4101. $size = $this->FontSizePt;
  4102. }
  4103. if ($size < 0) {
  4104. $size = 0;
  4105. }
  4106. // try to add font (if not already added)
  4107. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4108. $this->FontFamily = $fontdata['family'];
  4109. $this->FontStyle = $fontdata['style'];
  4110. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  4111. // save subset chars of the previous font
  4112. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4113. }
  4114. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4115. $this->SetFontSize($size, $out);
  4116. }
  4117. /**
  4118. * Defines the size of the current font.
  4119. * @param $size (float) The font size in points.
  4120. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4121. * @public
  4122. * @since 1.0
  4123. * @see SetFont()
  4124. */
  4125. public function SetFontSize($size, $out=true) {
  4126. $size = (float)$size;
  4127. // font size in points
  4128. $this->FontSizePt = $size;
  4129. // font size in user units
  4130. $this->FontSize = $size / $this->k;
  4131. // calculate some font metrics
  4132. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4133. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4134. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  4135. } else {
  4136. $font_height = $size * 1.219;
  4137. }
  4138. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  4139. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  4140. }
  4141. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  4142. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  4143. }
  4144. if (!isset($font_ascent) AND !isset($font_descent)) {
  4145. // core font
  4146. $font_ascent = 0.76 * $font_height;
  4147. $font_descent = $font_height - $font_ascent;
  4148. } elseif (!isset($font_descent)) {
  4149. $font_descent = $font_height - $font_ascent;
  4150. } elseif (!isset($font_ascent)) {
  4151. $font_ascent = $font_height - $font_descent;
  4152. }
  4153. $this->FontAscent = ($font_ascent / $this->k);
  4154. $this->FontDescent = ($font_descent / $this->k);
  4155. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i'])) AND ($this->state == 2)) {
  4156. $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  4157. }
  4158. }
  4159. /**
  4160. * Returns the bounding box of the current font in user units.
  4161. * @return array
  4162. * @public
  4163. * @since 5.9.152 (2012-03-23)
  4164. */
  4165. public function getFontBBox() {
  4166. $fbbox = array();
  4167. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4168. $tmpbbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4169. $fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
  4170. } else {
  4171. // Find max width
  4172. if (isset($this->CurrentFont['desc']['MaxWidth'])) {
  4173. $maxw = $this->getAbsFontMeasure(intval($this->CurrentFont['desc']['MaxWidth']));
  4174. } else {
  4175. $maxw = 0;
  4176. if (isset($this->CurrentFont['desc']['MissingWidth'])) {
  4177. $maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
  4178. }
  4179. if (isset($this->CurrentFont['desc']['AvgWidth'])) {
  4180. $maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
  4181. }
  4182. if (isset($this->CurrentFont['dw'])) {
  4183. $maxw = max($maxw, $this->CurrentFont['dw']);
  4184. }
  4185. foreach ($this->CurrentFont['cw'] as $char => $w) {
  4186. $maxw = max($maxw, $w);
  4187. }
  4188. if ($maxw == 0) {
  4189. $maxw = 600;
  4190. }
  4191. $maxw = $this->getAbsFontMeasure($maxw);
  4192. }
  4193. $fbbox = array(0, (0 - $this->FontDescent), $maxw, $this->FontAscent);
  4194. }
  4195. return $fbbox;
  4196. }
  4197. /**
  4198. * Convert a relative font measure into absolute value.
  4199. * @param $s (int) Font measure.
  4200. * @return float Absolute measure.
  4201. * @since 5.9.186 (2012-09-13)
  4202. */
  4203. public function getAbsFontMeasure($s) {
  4204. return ($s * $this->FontSize / 1000);
  4205. }
  4206. /**
  4207. * Returns the glyph bounding box of the specified character in the current font in user units.
  4208. * @param $char (int) Input character code.
  4209. * @return mixed array(xMin, yMin, xMax, yMax) or FALSE if not defined.
  4210. * @since 5.9.186 (2012-09-13)
  4211. */
  4212. public function getCharBBox($char) {
  4213. $c = intval($char);
  4214. if (isset($this->CurrentFont['cw'][$c])) {
  4215. // glyph is defined ... use zero width & height for glyphs without outlines
  4216. $result = array(0,0,0,0);
  4217. if (isset($this->CurrentFont['cbbox'][$c])) {
  4218. $result = $this->CurrentFont['cbbox'][$c];
  4219. }
  4220. return array_map(array($this,'getAbsFontMeasure'), $result);
  4221. }
  4222. return false;
  4223. }
  4224. /**
  4225. * Return the font descent value
  4226. * @param $font (string) font name
  4227. * @param $style (string) font style
  4228. * @param $size (float) The size (in points)
  4229. * @return int font descent
  4230. * @public
  4231. * @author Nicola Asuni
  4232. * @since 4.9.003 (2010-03-30)
  4233. */
  4234. public function getFontDescent($font, $style='', $size=0) {
  4235. $fontdata = $this->AddFont($font, $style);
  4236. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4237. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  4238. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  4239. } else {
  4240. $descent = (1.219 * 0.24 * $size);
  4241. }
  4242. return ($descent / $this->k);
  4243. }
  4244. /**
  4245. * Return the font ascent value.
  4246. * @param $font (string) font name
  4247. * @param $style (string) font style
  4248. * @param $size (float) The size (in points)
  4249. * @return int font ascent
  4250. * @public
  4251. * @author Nicola Asuni
  4252. * @since 4.9.003 (2010-03-30)
  4253. */
  4254. public function getFontAscent($font, $style='', $size=0) {
  4255. $fontdata = $this->AddFont($font, $style);
  4256. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4257. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  4258. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  4259. } else {
  4260. $ascent = 1.219 * 0.76 * $size;
  4261. }
  4262. return ($ascent / $this->k);
  4263. }
  4264. /**
  4265. * Return true in the character is present in the specified font.
  4266. * @param $char (mixed) Character to check (integer value or string)
  4267. * @param $font (string) Font name (family name).
  4268. * @param $style (string) Font style.
  4269. * @return (boolean) true if the char is defined, false otherwise.
  4270. * @public
  4271. * @since 5.9.153 (2012-03-28)
  4272. */
  4273. public function isCharDefined($char, $font='', $style='') {
  4274. if (is_string($char)) {
  4275. // get character code
  4276. $char = TCPDF_FONTS::UTF8StringToArray($char, $this->isunicode, $this->CurrentFont);
  4277. $char = $char[0];
  4278. }
  4279. if (TCPDF_STATIC::empty_string($font)) {
  4280. if (TCPDF_STATIC::empty_string($style)) {
  4281. return (isset($this->CurrentFont['cw'][intval($char)]));
  4282. }
  4283. $font = $this->FontFamily;
  4284. }
  4285. $fontdata = $this->AddFont($font, $style);
  4286. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4287. return (isset($fontinfo['cw'][intval($char)]));
  4288. }
  4289. /**
  4290. * Replace missing font characters on selected font with specified substitutions.
  4291. * @param $text (string) Text to process.
  4292. * @param $font (string) Font name (family name).
  4293. * @param $style (string) Font style.
  4294. * @param $subs (array) Array of possible character substitutions. The key is the character to check (integer value) and the value is a single intege value or an array of possible substitutes.
  4295. * @return (string) Processed text.
  4296. * @public
  4297. * @since 5.9.153 (2012-03-28)
  4298. */
  4299. public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
  4300. if (empty($subs)) {
  4301. return $text;
  4302. }
  4303. if (TCPDF_STATIC::empty_string($font)) {
  4304. $font = $this->FontFamily;
  4305. }
  4306. $fontdata = $this->AddFont($font, $style);
  4307. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4308. $uniarr = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  4309. foreach ($uniarr as $k => $chr) {
  4310. if (!isset($fontinfo['cw'][$chr])) {
  4311. // this character is missing on the selected font
  4312. if (isset($subs[$chr])) {
  4313. // we have available substitutions
  4314. if (is_array($subs[$chr])) {
  4315. foreach($subs[$chr] as $s) {
  4316. if (isset($fontinfo['cw'][$s])) {
  4317. $uniarr[$k] = $s;
  4318. break;
  4319. }
  4320. }
  4321. } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
  4322. $uniarr[$k] = $subs[$chr];
  4323. }
  4324. }
  4325. }
  4326. }
  4327. return TCPDF_FONTS::UniArrSubString(TCPDF_FONTS::UTF8ArrayToUniArray($uniarr, $this->isunicode));
  4328. }
  4329. /**
  4330. * Defines the default monospaced font.
  4331. * @param $font (string) Font name.
  4332. * @public
  4333. * @since 4.5.025
  4334. */
  4335. public function SetDefaultMonospacedFont($font) {
  4336. $this->default_monospaced_font = $font;
  4337. }
  4338. /**
  4339. * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
  4340. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  4341. * @public
  4342. * @since 1.5
  4343. * @see Cell(), Write(), Image(), Link(), SetLink()
  4344. */
  4345. public function AddLink() {
  4346. // create a new internal link
  4347. $n = count($this->links) + 1;
  4348. $this->links[$n] = array('p' => 0, 'y' => 0, 'f' => false);
  4349. return $n;
  4350. }
  4351. /**
  4352. * Defines the page and position a link points to.
  4353. * @param $link (int) The link identifier returned by AddLink()
  4354. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  4355. * @param $page (int|string) Number of target page; -1 indicates the current page (default value). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  4356. * @public
  4357. * @since 1.5
  4358. * @see AddLink()
  4359. */
  4360. public function SetLink($link, $y=0, $page=-1) {
  4361. $fixed = false;
  4362. if (!empty($page) AND is_string($page) AND ($page[0] == '*')) {
  4363. $page = intval(substr($page, 1));
  4364. // this page number will not be changed when moving/add/deleting pages
  4365. $fixed = true;
  4366. }
  4367. if ($page < 0) {
  4368. $page = $this->page;
  4369. }
  4370. if ($y == -1) {
  4371. $y = $this->y;
  4372. }
  4373. $this->links[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
  4374. }
  4375. /**
  4376. * Puts a link on a rectangular area of the page.
  4377. * Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
  4378. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4379. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4380. * @param $w (float) Width of the rectangle
  4381. * @param $h (float) Height of the rectangle
  4382. * @param $link (mixed) URL or identifier returned by AddLink()
  4383. * @param $spaces (int) number of spaces on the text to link
  4384. * @public
  4385. * @since 1.5
  4386. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  4387. */
  4388. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  4389. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  4390. }
  4391. /**
  4392. * Puts a markup annotation on a rectangular area of the page.
  4393. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  4394. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4395. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4396. * @param $w (float) Width of the rectangle
  4397. * @param $h (float) Height of the rectangle
  4398. * @param $text (string) annotation text or alternate content
  4399. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  4400. * @param $spaces (int) number of spaces on the text to link
  4401. * @public
  4402. * @since 4.0.018 (2008-08-06)
  4403. */
  4404. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  4405. if ($this->inxobj) {
  4406. // store parameters for later use on template
  4407. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  4408. return;
  4409. }
  4410. if ($x === '') {
  4411. $x = $this->x;
  4412. }
  4413. if ($y === '') {
  4414. $y = $this->y;
  4415. }
  4416. // check page for no-write regions and adapt page margins if necessary
  4417. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  4418. // recalculate coordinates to account for graphic transformations
  4419. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  4420. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  4421. $maxid = count($this->transfmatrix[$i]) - 1;
  4422. for ($j=$maxid; $j >= 0; --$j) {
  4423. $ctm = $this->transfmatrix[$i][$j];
  4424. if (isset($ctm['a'])) {
  4425. $x = $x * $this->k;
  4426. $y = ($this->h - $y) * $this->k;
  4427. $w = $w * $this->k;
  4428. $h = $h * $this->k;
  4429. // top left
  4430. $xt = $x;
  4431. $yt = $y;
  4432. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4433. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4434. // top right
  4435. $xt = $x + $w;
  4436. $yt = $y;
  4437. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4438. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4439. // bottom left
  4440. $xt = $x;
  4441. $yt = $y - $h;
  4442. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4443. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4444. // bottom right
  4445. $xt = $x + $w;
  4446. $yt = $y - $h;
  4447. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4448. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4449. // new coordinates (rectangle area)
  4450. $x = min($x1, $x2, $x3, $x4);
  4451. $y = max($y1, $y2, $y3, $y4);
  4452. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  4453. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  4454. $x = $x / $this->k;
  4455. $y = $this->h - ($y / $this->k);
  4456. }
  4457. }
  4458. }
  4459. }
  4460. if ($this->page <= 0) {
  4461. $page = 1;
  4462. } else {
  4463. $page = $this->page;
  4464. }
  4465. if (!isset($this->PageAnnots[$page])) {
  4466. $this->PageAnnots[$page] = array();
  4467. }
  4468. $this->PageAnnots[$page][] = array('n' => ++$this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  4469. if (!$this->pdfa_mode || ($this->pdfa_mode && $this->pdfa_version == 3)) {
  4470. if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC::empty_string($opt['FS']))
  4471. AND (@TCPDF_STATIC::file_exists($opt['FS']) OR TCPDF_STATIC::isValidURL($opt['FS']))
  4472. AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  4473. $this->embeddedfiles[basename($opt['FS'])] = array('f' => ++$this->n, 'n' => ++$this->n, 'file' => $opt['FS']);
  4474. }
  4475. }
  4476. // Add widgets annotation's icons
  4477. if (isset($opt['mk']['i']) AND @TCPDF_STATIC::file_exists($opt['mk']['i'])) {
  4478. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  4479. }
  4480. if (isset($opt['mk']['ri']) AND @TCPDF_STATIC::file_exists($opt['mk']['ri'])) {
  4481. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4482. }
  4483. if (isset($opt['mk']['ix']) AND @TCPDF_STATIC::file_exists($opt['mk']['ix'])) {
  4484. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4485. }
  4486. }
  4487. /**
  4488. * Embedd the attached files.
  4489. * @since 4.4.000 (2008-12-07)
  4490. * @protected
  4491. * @see Annotation()
  4492. */
  4493. protected function _putEmbeddedFiles() {
  4494. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  4495. // embedded files are not allowed in PDF/A mode version 1 and 2
  4496. return;
  4497. }
  4498. reset($this->embeddedfiles);
  4499. foreach ($this->embeddedfiles as $filename => $filedata) {
  4500. $data = TCPDF_STATIC::fileGetContents($filedata['file']);
  4501. if ($data !== FALSE) {
  4502. $rawsize = strlen($data);
  4503. if ($rawsize > 0) {
  4504. // update name tree
  4505. $this->efnames[$filename] = $filedata['f'].' 0 R';
  4506. // embedded file specification object
  4507. $out = $this->_getobj($filedata['f'])."\n";
  4508. $out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
  4509. $out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
  4510. $out .= ' /AFRelationship /Source';
  4511. $out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
  4512. $out .= "\n".'endobj';
  4513. $this->_out($out);
  4514. // embedded file object
  4515. $filter = '';
  4516. if ($this->compress) {
  4517. $data = gzcompress($data);
  4518. $filter = ' /Filter /FlateDecode';
  4519. }
  4520. if ($this->pdfa_version == 3) {
  4521. $filter = ' /Subtype /text#2Fxml';
  4522. }
  4523. $stream = $this->_getrawstream($data, $filedata['n']);
  4524. $out = $this->_getobj($filedata['n'])."\n";
  4525. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
  4526. $out .= ' stream'."\n".$stream."\n".'endstream';
  4527. $out .= "\n".'endobj';
  4528. $this->_out($out);
  4529. }
  4530. }
  4531. }
  4532. }
  4533. /**
  4534. * Prints a text cell at the specified position.
  4535. * This method allows to place a string precisely on the page.
  4536. * @param $x (float) Abscissa of the cell origin
  4537. * @param $y (float) Ordinate of the cell origin
  4538. * @param $txt (string) String to print
  4539. * @param $fstroke (int) outline size in user units (false = disable)
  4540. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  4541. * @param $ffill (boolean) if true fills the text
  4542. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  4543. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  4544. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  4545. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4546. * @param $link (mixed) URL or identifier returned by AddLink().
  4547. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  4548. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4549. * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
  4550. * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
  4551. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  4552. * @public
  4553. * @since 1.0
  4554. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  4555. */
  4556. public function Text($x, $y, $txt, $fstroke=false, $fclip=false, $ffill=true, $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M', $rtloff=false) {
  4557. $textrendermode = $this->textrendermode;
  4558. $textstrokewidth = $this->textstrokewidth;
  4559. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  4560. $this->SetXY($x, $y, $rtloff);
  4561. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  4562. // restore previous rendering mode
  4563. $this->textrendermode = $textrendermode;
  4564. $this->textstrokewidth = $textstrokewidth;
  4565. }
  4566. /**
  4567. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  4568. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  4569. * This method is called automatically and should not be called directly by the application.
  4570. * @return boolean
  4571. * @public
  4572. * @since 1.4
  4573. * @see SetAutoPageBreak()
  4574. */
  4575. public function AcceptPageBreak() {
  4576. if ($this->num_columns > 1) {
  4577. // multi column mode
  4578. if ($this->current_column < ($this->num_columns - 1)) {
  4579. // go to next column
  4580. $this->selectColumn($this->current_column + 1);
  4581. } elseif ($this->AutoPageBreak) {
  4582. // add a new page
  4583. $this->AddPage();
  4584. // set first column
  4585. $this->selectColumn(0);
  4586. }
  4587. // avoid page breaking from checkPageBreak()
  4588. return false;
  4589. }
  4590. return $this->AutoPageBreak;
  4591. }
  4592. /**
  4593. * Add page if needed.
  4594. * @param $h (float) Cell height. Default value: 0.
  4595. * @param $y (mixed) starting y position, leave empty for current position.
  4596. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  4597. * @return boolean true in case of page break, false otherwise.
  4598. * @since 3.2.000 (2008-07-01)
  4599. * @protected
  4600. */
  4601. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  4602. if (TCPDF_STATIC::empty_string($y)) {
  4603. $y = $this->y;
  4604. }
  4605. $current_page = $this->page;
  4606. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  4607. if ($addpage) {
  4608. //Automatic page break
  4609. $x = $this->x;
  4610. $this->AddPage($this->CurOrientation);
  4611. $this->y = $this->tMargin;
  4612. $oldpage = $this->page - 1;
  4613. if ($this->rtl) {
  4614. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  4615. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  4616. } else {
  4617. $this->x = $x;
  4618. }
  4619. } else {
  4620. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  4621. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  4622. } else {
  4623. $this->x = $x;
  4624. }
  4625. }
  4626. }
  4627. return true;
  4628. }
  4629. if ($current_page != $this->page) {
  4630. // account for columns mode
  4631. return true;
  4632. }
  4633. return false;
  4634. }
  4635. /**
  4636. * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
  4637. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4638. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4639. * @param $h (float) Cell height. Default value: 0.
  4640. * @param $txt (string) String to print. Default value: empty string.
  4641. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  4642. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul> Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  4643. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  4644. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4645. * @param $link (mixed) URL or identifier returned by AddLink().
  4646. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  4647. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4648. * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
  4649. * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
  4650. * @public
  4651. * @since 1.0
  4652. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  4653. */
  4654. public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {
  4655. $prev_cell_margin = $this->cell_margin;
  4656. $prev_cell_padding = $this->cell_padding;
  4657. $this->adjustCellPadding($border);
  4658. if (!$ignore_min_height) {
  4659. $min_cell_height = $this->getCellHeight($this->FontSize);
  4660. if ($h < $min_cell_height) {
  4661. $h = $min_cell_height;
  4662. }
  4663. }
  4664. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  4665. // apply text shadow if enabled
  4666. if ($this->txtshadow['enabled']) {
  4667. // save data
  4668. $x = $this->x;
  4669. $y = $this->y;
  4670. $bc = $this->bgcolor;
  4671. $fc = $this->fgcolor;
  4672. $sc = $this->strokecolor;
  4673. $alpha = $this->alpha;
  4674. // print shadow
  4675. $this->x += $this->txtshadow['depth_w'];
  4676. $this->y += $this->txtshadow['depth_h'];
  4677. $this->SetFillColorArray($this->txtshadow['color']);
  4678. $this->SetTextColorArray($this->txtshadow['color']);
  4679. $this->SetDrawColorArray($this->txtshadow['color']);
  4680. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4681. $this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
  4682. }
  4683. if ($this->state == 2) {
  4684. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4685. }
  4686. //restore data
  4687. $this->x = $x;
  4688. $this->y = $y;
  4689. $this->SetFillColorArray($bc);
  4690. $this->SetTextColorArray($fc);
  4691. $this->SetDrawColorArray($sc);
  4692. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4693. $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
  4694. }
  4695. }
  4696. if ($this->state == 2) {
  4697. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4698. }
  4699. $this->cell_padding = $prev_cell_padding;
  4700. $this->cell_margin = $prev_cell_margin;
  4701. }
  4702. /**
  4703. * Returns the PDF string code to print a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
  4704. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4705. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4706. * @param $h (float) Cell height. Default value: 0.
  4707. * @param $txt (string) String to print. Default value: empty string.
  4708. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  4709. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  4710. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  4711. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4712. * @param $link (mixed) URL or identifier returned by AddLink().
  4713. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  4714. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4715. * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
  4716. * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>M : middle</li><li>B : bottom</li></ul>
  4717. * @return string containing cell code
  4718. * @protected
  4719. * @since 1.0
  4720. * @see Cell()
  4721. */
  4722. protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {
  4723. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  4724. $txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);
  4725. $prev_cell_margin = $this->cell_margin;
  4726. $prev_cell_padding = $this->cell_padding;
  4727. $txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);
  4728. $rs = ''; //string to be returned
  4729. $this->adjustCellPadding($border);
  4730. if (!$ignore_min_height) {
  4731. $min_cell_height = $this->getCellHeight($this->FontSize);
  4732. if ($h < $min_cell_height) {
  4733. $h = $min_cell_height;
  4734. }
  4735. }
  4736. $k = $this->k;
  4737. // check page for no-write regions and adapt page margins if necessary
  4738. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  4739. if ($this->rtl) {
  4740. $x = $this->x - $this->cell_margin['R'];
  4741. } else {
  4742. $x = $this->x + $this->cell_margin['L'];
  4743. }
  4744. $y = $this->y + $this->cell_margin['T'];
  4745. $prev_font_stretching = $this->font_stretching;
  4746. $prev_font_spacing = $this->font_spacing;
  4747. // cell vertical alignment
  4748. switch ($calign) {
  4749. case 'A': {
  4750. // font top
  4751. switch ($valign) {
  4752. case 'T': {
  4753. // top
  4754. $y -= $this->cell_padding['T'];
  4755. break;
  4756. }
  4757. case 'B': {
  4758. // bottom
  4759. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  4760. break;
  4761. }
  4762. default:
  4763. case 'C':
  4764. case 'M': {
  4765. // center
  4766. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  4767. break;
  4768. }
  4769. }
  4770. break;
  4771. }
  4772. case 'L': {
  4773. // font baseline
  4774. switch ($valign) {
  4775. case 'T': {
  4776. // top
  4777. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  4778. break;
  4779. }
  4780. case 'B': {
  4781. // bottom
  4782. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  4783. break;
  4784. }
  4785. default:
  4786. case 'C':
  4787. case 'M': {
  4788. // center
  4789. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  4790. break;
  4791. }
  4792. }
  4793. break;
  4794. }
  4795. case 'D': {
  4796. // font bottom
  4797. switch ($valign) {
  4798. case 'T': {
  4799. // top
  4800. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  4801. break;
  4802. }
  4803. case 'B': {
  4804. // bottom
  4805. $y -= ($h - $this->cell_padding['B']);
  4806. break;
  4807. }
  4808. default:
  4809. case 'C':
  4810. case 'M': {
  4811. // center
  4812. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  4813. break;
  4814. }
  4815. }
  4816. break;
  4817. }
  4818. case 'B': {
  4819. // cell bottom
  4820. $y -= $h;
  4821. break;
  4822. }
  4823. case 'C':
  4824. case 'M': {
  4825. // cell center
  4826. $y -= ($h / 2);
  4827. break;
  4828. }
  4829. default:
  4830. case 'T': {
  4831. // cell top
  4832. break;
  4833. }
  4834. }
  4835. // text vertical alignment
  4836. switch ($valign) {
  4837. case 'T': {
  4838. // top
  4839. $yt = $y + $this->cell_padding['T'];
  4840. break;
  4841. }
  4842. case 'B': {
  4843. // bottom
  4844. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  4845. break;
  4846. }
  4847. default:
  4848. case 'C':
  4849. case 'M': {
  4850. // center
  4851. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  4852. break;
  4853. }
  4854. }
  4855. $basefonty = $yt + $this->FontAscent;
  4856. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  4857. if ($this->rtl) {
  4858. $w = $x - $this->lMargin;
  4859. } else {
  4860. $w = $this->w - $this->rMargin - $x;
  4861. }
  4862. }
  4863. $s = '';
  4864. // fill and borders
  4865. if (is_string($border) AND (strlen($border) == 4)) {
  4866. // full border
  4867. $border = 1;
  4868. }
  4869. if ($fill OR ($border == 1)) {
  4870. if ($fill) {
  4871. $op = ($border == 1) ? 'B' : 'f';
  4872. } else {
  4873. $op = 'S';
  4874. }
  4875. if ($this->rtl) {
  4876. $xk = (($x - $w) * $k);
  4877. } else {
  4878. $xk = ($x * $k);
  4879. }
  4880. $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  4881. }
  4882. // draw borders
  4883. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  4884. if ($txt != '') {
  4885. $txt2 = $txt;
  4886. if ($this->isunicode) {
  4887. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  4888. $txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);
  4889. } else {
  4890. $unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values
  4891. $unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);
  4892. // replace thai chars (if any)
  4893. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  4894. // number of chars
  4895. $numchars = count($unicode);
  4896. // po pla, for far, for fan
  4897. $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
  4898. // do chada, to patak
  4899. $lowtail = array(0x0e0e, 0x0e0f);
  4900. // mai hun arkad, sara i, sara ii, sara ue, sara uee
  4901. $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
  4902. // mai ek, mai tho, mai tri, mai chattawa, karan
  4903. $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
  4904. // sara u, sara uu, pinthu
  4905. $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
  4906. $output = array();
  4907. for ($i = 0; $i < $numchars; $i++) {
  4908. if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
  4909. $ch0 = $unicode[$i];
  4910. $ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
  4911. $ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
  4912. $chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
  4913. if (in_array($ch0, $tonemark)) {
  4914. if ($chn == 0x0e33) {
  4915. // sara um
  4916. if (in_array($ch1, $longtail)) {
  4917. // tonemark at upper left
  4918. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4919. } else {
  4920. // tonemark at upper right (normal position)
  4921. $output[] = $ch0;
  4922. }
  4923. } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
  4924. // tonemark at lower left
  4925. $output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
  4926. } elseif (in_array($ch1, $upvowel)) {
  4927. if (in_array($ch2, $longtail)) {
  4928. // tonemark at upper left
  4929. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4930. } else {
  4931. // tonemark at upper right (normal position)
  4932. $output[] = $ch0;
  4933. }
  4934. } else {
  4935. // tonemark at lower right
  4936. $output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
  4937. }
  4938. } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
  4939. // add lower left nikhahit and sara aa
  4940. if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
  4941. $output[] = 0xf711;
  4942. $this->CurrentFont['subsetchars'][0xf711] = true;
  4943. $output[] = 0x0e32;
  4944. $this->CurrentFont['subsetchars'][0x0e32] = true;
  4945. } else {
  4946. $output[] = $ch0;
  4947. }
  4948. } elseif (in_array($ch1, $longtail)) {
  4949. if ($ch0 == 0x0e31) {
  4950. // lower left mai hun arkad
  4951. $output[] = $this->replaceChar($ch0, 0xf710);
  4952. } elseif (in_array($ch0, $upvowel)) {
  4953. // lower left
  4954. $output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
  4955. } elseif ($ch0 == 0x0e47) {
  4956. // lower left mai tai koo
  4957. $output[] = $this->replaceChar($ch0, 0xf712);
  4958. } else {
  4959. // normal character
  4960. $output[] = $ch0;
  4961. }
  4962. } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
  4963. // lower vowel
  4964. $output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
  4965. } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
  4966. // yo ying without lower part
  4967. $output[] = $this->replaceChar($ch0, 0xf70f);
  4968. } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
  4969. // tho santan without lower part
  4970. $output[] = $this->replaceChar($ch0, 0xf700);
  4971. } else {
  4972. $output[] = $ch0;
  4973. }
  4974. } else {
  4975. // non-thai character
  4976. $output[] = $unicode[$i];
  4977. }
  4978. }
  4979. $unicode = $output;
  4980. // update font subsetchars
  4981. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4982. } // end of K_THAI_TOPCHARS
  4983. $txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);
  4984. }
  4985. }
  4986. $txt2 = TCPDF_STATIC::_escape($txt2);
  4987. // get current text width (considering general font stretching and spacing)
  4988. $txwidth = $this->GetStringWidth($txt);
  4989. $width = $txwidth;
  4990. // check for stretch mode
  4991. if ($stretch > 0) {
  4992. // calculate ratio between cell width and text width
  4993. if ($width <= 0) {
  4994. $ratio = 1;
  4995. } else {
  4996. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  4997. }
  4998. // check if stretching is required
  4999. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5000. // the text will be stretched to fit cell width
  5001. if ($stretch > 2) {
  5002. // set new character spacing
  5003. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5004. } else {
  5005. // set new horizontal stretching
  5006. $this->font_stretching *= $ratio;
  5007. }
  5008. // recalculate text width (the text fills the entire cell)
  5009. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5010. // reset alignment
  5011. $align = '';
  5012. }
  5013. }
  5014. if ($this->font_stretching != 100) {
  5015. // apply font stretching
  5016. $rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
  5017. }
  5018. if ($this->font_spacing != 0) {
  5019. // increase/decrease font spacing
  5020. $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
  5021. }
  5022. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5023. $s .= 'q '.$this->TextColor.' ';
  5024. }
  5025. // rendering mode
  5026. $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
  5027. // count number of spaces
  5028. $ns = substr_count($txt, chr(32));
  5029. // Justification
  5030. $spacewidth = 0;
  5031. if (($align == 'J') AND ($ns > 0)) {
  5032. if ($this->isUnicodeFont()) {
  5033. // get string width without spaces
  5034. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5035. // calculate average space width
  5036. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);
  5037. if ($this->font_stretching != 100) {
  5038. // word spacing is affected by stretching
  5039. $spacewidth /= ($this->font_stretching / 100);
  5040. }
  5041. // set word position to be used with TJ operator
  5042. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
  5043. $unicode_justification = true;
  5044. } else {
  5045. // get string width
  5046. $width = $txwidth;
  5047. // new space width
  5048. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5049. if ($this->font_stretching != 100) {
  5050. // word spacing (Tw) is affected by stretching
  5051. $spacewidth /= ($this->font_stretching / 100);
  5052. }
  5053. // set word spacing
  5054. $rs .= sprintf('BT %F Tw ET ', $spacewidth);
  5055. }
  5056. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5057. }
  5058. // replace carriage return characters
  5059. $txt2 = str_replace("\r", ' ', $txt2);
  5060. switch ($align) {
  5061. case 'C': {
  5062. $dx = ($w - $width) / 2;
  5063. break;
  5064. }
  5065. case 'R': {
  5066. if ($this->rtl) {
  5067. $dx = $this->cell_padding['R'];
  5068. } else {
  5069. $dx = $w - $width - $this->cell_padding['R'];
  5070. }
  5071. break;
  5072. }
  5073. case 'L': {
  5074. if ($this->rtl) {
  5075. $dx = $w - $width - $this->cell_padding['L'];
  5076. } else {
  5077. $dx = $this->cell_padding['L'];
  5078. }
  5079. break;
  5080. }
  5081. case 'J':
  5082. default: {
  5083. if ($this->rtl) {
  5084. $dx = $this->cell_padding['R'];
  5085. } else {
  5086. $dx = $this->cell_padding['L'];
  5087. }
  5088. break;
  5089. }
  5090. }
  5091. if ($this->rtl) {
  5092. $xdx = $x - $dx - $width;
  5093. } else {
  5094. $xdx = $x + $dx;
  5095. }
  5096. $xdk = $xdx * $k;
  5097. // print text
  5098. $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5099. if (isset($uniblock)) {
  5100. // print overlapping characters as separate string
  5101. $xshift = 0; // horizontal shift
  5102. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5103. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5104. foreach ($uniblock as $uk => $uniarr) {
  5105. if (($uk % 2) == 0) {
  5106. // x space to skip
  5107. if ($spacewidth != 0) {
  5108. // justification shift
  5109. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5110. }
  5111. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5112. } else {
  5113. // character to print
  5114. $topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);
  5115. $topchr = TCPDF_STATIC::_escape($topchr);
  5116. $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5117. }
  5118. }
  5119. }
  5120. if ($this->underline) {
  5121. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5122. }
  5123. if ($this->linethrough) {
  5124. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5125. }
  5126. if ($this->overline) {
  5127. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5128. }
  5129. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5130. $s .= ' Q';
  5131. }
  5132. if ($link) {
  5133. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5134. }
  5135. }
  5136. // output cell
  5137. if ($s) {
  5138. // output cell
  5139. $rs .= $s;
  5140. if ($this->font_spacing != 0) {
  5141. // reset font spacing mode
  5142. $rs .= ' BT 0 Tc ET';
  5143. }
  5144. if ($this->font_stretching != 100) {
  5145. // reset font stretching mode
  5146. $rs .= ' BT 100 Tz ET';
  5147. }
  5148. }
  5149. // reset word spacing
  5150. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  5151. $rs .= ' BT 0 Tw ET';
  5152. }
  5153. // reset stretching and spacing
  5154. $this->font_stretching = $prev_font_stretching;
  5155. $this->font_spacing = $prev_font_spacing;
  5156. $this->lasth = $h;
  5157. if ($ln > 0) {
  5158. //Go to the beginning of the next line
  5159. $this->y = $y + $h + $this->cell_margin['B'];
  5160. if ($ln == 1) {
  5161. if ($this->rtl) {
  5162. $this->x = $this->w - $this->rMargin;
  5163. } else {
  5164. $this->x = $this->lMargin;
  5165. }
  5166. }
  5167. } else {
  5168. // go left or right by case
  5169. if ($this->rtl) {
  5170. $this->x = $x - $w - $this->cell_margin['L'];
  5171. } else {
  5172. $this->x = $x + $w + $this->cell_margin['R'];
  5173. }
  5174. }
  5175. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  5176. $rs = $gstyles.$rs;
  5177. $this->cell_padding = $prev_cell_padding;
  5178. $this->cell_margin = $prev_cell_margin;
  5179. return $rs;
  5180. }
  5181. /**
  5182. * Replace a char if is defined on the current font.
  5183. * @param $oldchar (int) Integer code (unicode) of the character to replace.
  5184. * @param $newchar (int) Integer code (unicode) of the new character.
  5185. * @return int the replaced char or the old char in case the new char i not defined
  5186. * @protected
  5187. * @since 5.9.167 (2012-06-22)
  5188. */
  5189. protected function replaceChar($oldchar, $newchar) {
  5190. if ($this->isCharDefined($newchar)) {
  5191. // add the new char on the subset list
  5192. $this->CurrentFont['subsetchars'][$newchar] = true;
  5193. // return the new character
  5194. return $newchar;
  5195. }
  5196. // return the old char
  5197. return $oldchar;
  5198. }
  5199. /**
  5200. * Returns the code to draw the cell border
  5201. * @param $x (float) X coordinate.
  5202. * @param $y (float) Y coordinate.
  5203. * @param $w (float) Cell width.
  5204. * @param $h (float) Cell height.
  5205. * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5206. * @return string containing cell border code
  5207. * @protected
  5208. * @see SetLineStyle()
  5209. * @since 5.7.000 (2010-08-02)
  5210. */
  5211. protected function getCellBorder($x, $y, $w, $h, $brd) {
  5212. $s = ''; // string to be returned
  5213. if (empty($brd)) {
  5214. return $s;
  5215. }
  5216. if ($brd == 1) {
  5217. $brd = array('LRTB' => true);
  5218. }
  5219. // calculate coordinates for border
  5220. $k = $this->k;
  5221. if ($this->rtl) {
  5222. $xeL = ($x - $w) * $k;
  5223. $xeR = $x * $k;
  5224. } else {
  5225. $xeL = $x * $k;
  5226. $xeR = ($x + $w) * $k;
  5227. }
  5228. $yeL = (($this->h - ($y + $h)) * $k);
  5229. $yeT = (($this->h - $y) * $k);
  5230. $xeT = $xeL;
  5231. $xeB = $xeR;
  5232. $yeR = $yeT;
  5233. $yeB = $yeL;
  5234. if (is_string($brd)) {
  5235. // convert string to array
  5236. $slen = strlen($brd);
  5237. $newbrd = array();
  5238. for ($i = 0; $i < $slen; ++$i) {
  5239. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  5240. }
  5241. $brd = $newbrd;
  5242. }
  5243. if (isset($brd['mode'])) {
  5244. $mode = $brd['mode'];
  5245. unset($brd['mode']);
  5246. } else {
  5247. $mode = 'normal';
  5248. }
  5249. foreach ($brd as $border => $style) {
  5250. if (is_array($style) AND !empty($style)) {
  5251. // apply border style
  5252. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  5253. $s .= $this->SetLineStyle($style, true)."\n";
  5254. }
  5255. switch ($mode) {
  5256. case 'ext': {
  5257. $off = (($this->LineWidth / 2) * $k);
  5258. $xL = $xeL - $off;
  5259. $xR = $xeR + $off;
  5260. $yT = $yeT + $off;
  5261. $yL = $yeL - $off;
  5262. $xT = $xL;
  5263. $xB = $xR;
  5264. $yR = $yT;
  5265. $yB = $yL;
  5266. $w += $this->LineWidth;
  5267. $h += $this->LineWidth;
  5268. break;
  5269. }
  5270. case 'int': {
  5271. $off = ($this->LineWidth / 2) * $k;
  5272. $xL = $xeL + $off;
  5273. $xR = $xeR - $off;
  5274. $yT = $yeT - $off;
  5275. $yL = $yeL + $off;
  5276. $xT = $xL;
  5277. $xB = $xR;
  5278. $yR = $yT;
  5279. $yB = $yL;
  5280. $w -= $this->LineWidth;
  5281. $h -= $this->LineWidth;
  5282. break;
  5283. }
  5284. case 'normal':
  5285. default: {
  5286. $xL = $xeL;
  5287. $xT = $xeT;
  5288. $xB = $xeB;
  5289. $xR = $xeR;
  5290. $yL = $yeL;
  5291. $yT = $yeT;
  5292. $yB = $yeB;
  5293. $yR = $yeR;
  5294. break;
  5295. }
  5296. }
  5297. // draw borders by case
  5298. if (strlen($border) == 4) {
  5299. $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  5300. } elseif (strlen($border) == 3) {
  5301. if (strpos($border,'B') === false) { // LTR
  5302. $s .= sprintf('%F %F m ', $xL, $yL);
  5303. $s .= sprintf('%F %F l ', $xT, $yT);
  5304. $s .= sprintf('%F %F l ', $xR, $yR);
  5305. $s .= sprintf('%F %F l ', $xB, $yB);
  5306. $s .= 'S ';
  5307. } elseif (strpos($border,'L') === false) { // TRB
  5308. $s .= sprintf('%F %F m ', $xT, $yT);
  5309. $s .= sprintf('%F %F l ', $xR, $yR);
  5310. $s .= sprintf('%F %F l ', $xB, $yB);
  5311. $s .= sprintf('%F %F l ', $xL, $yL);
  5312. $s .= 'S ';
  5313. } elseif (strpos($border,'T') === false) { // RBL
  5314. $s .= sprintf('%F %F m ', $xR, $yR);
  5315. $s .= sprintf('%F %F l ', $xB, $yB);
  5316. $s .= sprintf('%F %F l ', $xL, $yL);
  5317. $s .= sprintf('%F %F l ', $xT, $yT);
  5318. $s .= 'S ';
  5319. } elseif (strpos($border,'R') === false) { // BLT
  5320. $s .= sprintf('%F %F m ', $xB, $yB);
  5321. $s .= sprintf('%F %F l ', $xL, $yL);
  5322. $s .= sprintf('%F %F l ', $xT, $yT);
  5323. $s .= sprintf('%F %F l ', $xR, $yR);
  5324. $s .= 'S ';
  5325. }
  5326. } elseif (strlen($border) == 2) {
  5327. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  5328. $s .= sprintf('%F %F m ', $xL, $yL);
  5329. $s .= sprintf('%F %F l ', $xT, $yT);
  5330. $s .= sprintf('%F %F l ', $xR, $yR);
  5331. $s .= 'S ';
  5332. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  5333. $s .= sprintf('%F %F m ', $xT, $yT);
  5334. $s .= sprintf('%F %F l ', $xR, $yR);
  5335. $s .= sprintf('%F %F l ', $xB, $yB);
  5336. $s .= 'S ';
  5337. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  5338. $s .= sprintf('%F %F m ', $xR, $yR);
  5339. $s .= sprintf('%F %F l ', $xB, $yB);
  5340. $s .= sprintf('%F %F l ', $xL, $yL);
  5341. $s .= 'S ';
  5342. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  5343. $s .= sprintf('%F %F m ', $xB, $yB);
  5344. $s .= sprintf('%F %F l ', $xL, $yL);
  5345. $s .= sprintf('%F %F l ', $xT, $yT);
  5346. $s .= 'S ';
  5347. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  5348. $s .= sprintf('%F %F m ', $xL, $yL);
  5349. $s .= sprintf('%F %F l ', $xT, $yT);
  5350. $s .= 'S ';
  5351. $s .= sprintf('%F %F m ', $xR, $yR);
  5352. $s .= sprintf('%F %F l ', $xB, $yB);
  5353. $s .= 'S ';
  5354. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  5355. $s .= sprintf('%F %F m ', $xT, $yT);
  5356. $s .= sprintf('%F %F l ', $xR, $yR);
  5357. $s .= 'S ';
  5358. $s .= sprintf('%F %F m ', $xB, $yB);
  5359. $s .= sprintf('%F %F l ', $xL, $yL);
  5360. $s .= 'S ';
  5361. }
  5362. } else { // strlen($border) == 1
  5363. if (strpos($border,'L') !== false) { // L
  5364. $s .= sprintf('%F %F m ', $xL, $yL);
  5365. $s .= sprintf('%F %F l ', $xT, $yT);
  5366. $s .= 'S ';
  5367. } elseif (strpos($border,'T') !== false) { // T
  5368. $s .= sprintf('%F %F m ', $xT, $yT);
  5369. $s .= sprintf('%F %F l ', $xR, $yR);
  5370. $s .= 'S ';
  5371. } elseif (strpos($border,'R') !== false) { // R
  5372. $s .= sprintf('%F %F m ', $xR, $yR);
  5373. $s .= sprintf('%F %F l ', $xB, $yB);
  5374. $s .= 'S ';
  5375. } elseif (strpos($border,'B') !== false) { // B
  5376. $s .= sprintf('%F %F m ', $xB, $yB);
  5377. $s .= sprintf('%F %F l ', $xL, $yL);
  5378. $s .= 'S ';
  5379. }
  5380. }
  5381. if (is_array($style) AND !empty($style)) {
  5382. // reset border style to previous value
  5383. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  5384. }
  5385. }
  5386. return $s;
  5387. }
  5388. /**
  5389. * This method allows printing text with line breaks.
  5390. * They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
  5391. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  5392. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5393. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  5394. * @param $txt (string) String to print
  5395. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5396. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul>
  5397. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5398. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
  5399. * @param $x (float) x position in user units
  5400. * @param $y (float) y position in user units
  5401. * @param $reseth (boolean) if true reset the last cell height (default true).
  5402. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  5403. * @param $ishtml (boolean) INTERNAL USE ONLY -- set to true if $txt is HTML content (default = false). Never set this parameter to true, use instead writeHTMLCell() or writeHTML() methods.
  5404. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  5405. * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
  5406. * @param $valign (string) Vertical alignment of text (requires $maxh = $h > 0). Possible values are:<ul><li>T: TOP</li><li>M: middle</li><li>B: bottom</li></ul>. This feature works only when $ishtml=false and the cell must fit in a single page.
  5407. * @param $fitcell (boolean) if true attempt to fit all the text within the cell by reducing the font size (do not work in HTML mode). $maxh must be greater than 0 and equal to $h.
  5408. * @return int Return the number of cells or 1 for html mode.
  5409. * @public
  5410. * @since 1.3
  5411. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  5412. */
  5413. public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false) {
  5414. $prev_cell_margin = $this->cell_margin;
  5415. $prev_cell_padding = $this->cell_padding;
  5416. // adjust internal padding
  5417. $this->adjustCellPadding($border);
  5418. $mc_padding = $this->cell_padding;
  5419. $mc_margin = $this->cell_margin;
  5420. $this->cell_padding['T'] = 0;
  5421. $this->cell_padding['B'] = 0;
  5422. $this->setCellMargins(0, 0, 0, 0);
  5423. if (TCPDF_STATIC::empty_string($this->lasth) OR $reseth) {
  5424. // reset row height
  5425. $this->resetLastH();
  5426. }
  5427. if (!TCPDF_STATIC::empty_string($y)) {
  5428. $this->SetY($y); // set y in order to convert negative y values to positive ones
  5429. }
  5430. $y = $this->GetY();
  5431. $resth = 0;
  5432. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  5433. // spit cell in more pages/columns
  5434. $newh = ($this->PageBreakTrigger - $y);
  5435. $resth = ($h - $newh); // cell to be printed on the next page/column
  5436. $h = $newh;
  5437. }
  5438. // get current page number
  5439. $startpage = $this->page;
  5440. // get current column
  5441. $startcolumn = $this->current_column;
  5442. if (!TCPDF_STATIC::empty_string($x)) {
  5443. $this->SetX($x);
  5444. } else {
  5445. $x = $this->GetX();
  5446. }
  5447. // check page for no-write regions and adapt page margins if necessary
  5448. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  5449. // apply margins
  5450. $oy = $y + $mc_margin['T'];
  5451. if ($this->rtl) {
  5452. $ox = ($this->w - $x - $mc_margin['R']);
  5453. } else {
  5454. $ox = ($x + $mc_margin['L']);
  5455. }
  5456. $this->x = $ox;
  5457. $this->y = $oy;
  5458. // set width
  5459. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5460. if ($this->rtl) {
  5461. $w = ($this->x - $this->lMargin - $mc_margin['L']);
  5462. } else {
  5463. $w = ($this->w - $this->x - $this->rMargin - $mc_margin['R']);
  5464. }
  5465. }
  5466. // store original margin values
  5467. $lMargin = $this->lMargin;
  5468. $rMargin = $this->rMargin;
  5469. if ($this->rtl) {
  5470. $this->rMargin = ($this->w - $this->x);
  5471. $this->lMargin = ($this->x - $w);
  5472. } else {
  5473. $this->lMargin = ($this->x);
  5474. $this->rMargin = ($this->w - $this->x - $w);
  5475. }
  5476. $this->clMargin = $this->lMargin;
  5477. $this->crMargin = $this->rMargin;
  5478. if ($autopadding) {
  5479. // add top padding
  5480. $this->y += $mc_padding['T'];
  5481. }
  5482. if ($ishtml) { // ******* Write HTML text
  5483. $this->writeHTML($txt, true, false, $reseth, true, $align);
  5484. $nl = 1;
  5485. } else { // ******* Write simple text
  5486. $prev_FontSizePt = $this->FontSizePt;
  5487. if ($fitcell) {
  5488. // ajust height values
  5489. $tobottom = ($this->h - $this->y - $this->bMargin - $this->cell_padding['T'] - $this->cell_padding['B']);
  5490. $h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
  5491. }
  5492. // vertical alignment
  5493. if ($maxh > 0) {
  5494. // get text height
  5495. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5496. if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt > 1)) {
  5497. // try to reduce font size to fit text on cell (use a quick search algorithm)
  5498. $fmin = 1;
  5499. $fmax = $this->FontSizePt;
  5500. $diff_epsilon = (1 / $this->k); // one point (min resolution)
  5501. $maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
  5502. while ($maxit >= 0) {
  5503. $fmid = (($fmax + $fmin) / 2);
  5504. $this->SetFontSize($fmid, false);
  5505. $this->resetLastH();
  5506. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5507. $diff = ($maxh - $text_height);
  5508. if ($diff >= 0) {
  5509. if ($diff <= $diff_epsilon) {
  5510. break;
  5511. }
  5512. $fmin = $fmid;
  5513. } else {
  5514. $fmax = $fmid;
  5515. }
  5516. --$maxit;
  5517. }
  5518. if ($maxit < 0) {
  5519. // premature exit, we get the minimum font value to fit the cell
  5520. $this->SetFontSize($fmin);
  5521. $this->resetLastH();
  5522. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5523. } else {
  5524. $this->SetFontSize($fmid);
  5525. $this->resetLastH();
  5526. }
  5527. }
  5528. if ($text_height < $maxh) {
  5529. if ($valign == 'M') {
  5530. // text vertically centered
  5531. $this->y += (($maxh - $text_height) / 2);
  5532. } elseif ($valign == 'B') {
  5533. // text vertically aligned on bottom
  5534. $this->y += ($maxh - $text_height);
  5535. }
  5536. }
  5537. }
  5538. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  5539. if ($fitcell) {
  5540. // restore font size
  5541. $this->SetFontSize($prev_FontSizePt);
  5542. }
  5543. }
  5544. if ($autopadding) {
  5545. // add bottom padding
  5546. $this->y += $mc_padding['B'];
  5547. }
  5548. // Get end-of-text Y position
  5549. $currentY = $this->y;
  5550. // get latest page number
  5551. $endpage = $this->page;
  5552. if ($resth > 0) {
  5553. $skip = ($endpage - $startpage);
  5554. $tmpresth = $resth;
  5555. while ($tmpresth > 0) {
  5556. if ($skip <= 0) {
  5557. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  5558. $this->checkPageBreak($this->PageBreakTrigger + 1);
  5559. }
  5560. if ($this->num_columns > 1) {
  5561. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  5562. } else {
  5563. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  5564. }
  5565. --$skip;
  5566. }
  5567. $currentY = $this->y;
  5568. $endpage = $this->page;
  5569. }
  5570. // get latest column
  5571. $endcolumn = $this->current_column;
  5572. if ($this->num_columns == 0) {
  5573. $this->num_columns = 1;
  5574. }
  5575. // disable page regions check
  5576. $check_page_regions = $this->check_page_regions;
  5577. $this->check_page_regions = false;
  5578. // get border modes
  5579. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  5580. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  5581. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  5582. // design borders around HTML cells.
  5583. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  5584. $ccode = '';
  5585. $this->setPage($page);
  5586. if ($this->num_columns < 2) {
  5587. // single-column mode
  5588. $this->SetX($x);
  5589. $this->y = $this->tMargin;
  5590. }
  5591. // account for margin changes
  5592. if ($page > $startpage) {
  5593. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  5594. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  5595. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  5596. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  5597. }
  5598. }
  5599. if ($startpage == $endpage) {
  5600. // single page
  5601. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  5602. if ($column != $this->current_column) {
  5603. $this->selectColumn($column);
  5604. }
  5605. if ($this->rtl) {
  5606. $this->x -= $mc_margin['R'];
  5607. } else {
  5608. $this->x += $mc_margin['L'];
  5609. }
  5610. if ($startcolumn == $endcolumn) { // single column
  5611. $cborder = $border;
  5612. $h = max($h, ($currentY - $oy));
  5613. $this->y = $oy;
  5614. } elseif ($column == $startcolumn) { // first column
  5615. $cborder = $border_start;
  5616. $this->y = $oy;
  5617. $h = $this->h - $this->y - $this->bMargin;
  5618. } elseif ($column == $endcolumn) { // end column
  5619. $cborder = $border_end;
  5620. $h = $currentY - $this->y;
  5621. if ($resth > $h) {
  5622. $h = $resth;
  5623. }
  5624. } else { // middle column
  5625. $cborder = $border_middle;
  5626. $h = $this->h - $this->y - $this->bMargin;
  5627. $resth -= $h;
  5628. }
  5629. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5630. } // end for each column
  5631. } elseif ($page == $startpage) { // first page
  5632. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  5633. if ($column != $this->current_column) {
  5634. $this->selectColumn($column);
  5635. }
  5636. if ($this->rtl) {
  5637. $this->x -= $mc_margin['R'];
  5638. } else {
  5639. $this->x += $mc_margin['L'];
  5640. }
  5641. if ($column == $startcolumn) { // first column
  5642. $cborder = $border_start;
  5643. $this->y = $oy;
  5644. $h = $this->h - $this->y - $this->bMargin;
  5645. } else { // middle column
  5646. $cborder = $border_middle;
  5647. $h = $this->h - $this->y - $this->bMargin;
  5648. $resth -= $h;
  5649. }
  5650. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5651. } // end for each column
  5652. } elseif ($page == $endpage) { // last page
  5653. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  5654. if ($column != $this->current_column) {
  5655. $this->selectColumn($column);
  5656. }
  5657. if ($this->rtl) {
  5658. $this->x -= $mc_margin['R'];
  5659. } else {
  5660. $this->x += $mc_margin['L'];
  5661. }
  5662. if ($column == $endcolumn) {
  5663. // end column
  5664. $cborder = $border_end;
  5665. $h = $currentY - $this->y;
  5666. if ($resth > $h) {
  5667. $h = $resth;
  5668. }
  5669. } else {
  5670. // middle column
  5671. $cborder = $border_middle;
  5672. $h = $this->h - $this->y - $this->bMargin;
  5673. $resth -= $h;
  5674. }
  5675. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5676. } // end for each column
  5677. } else { // middle page
  5678. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  5679. $this->selectColumn($column);
  5680. if ($this->rtl) {
  5681. $this->x -= $mc_margin['R'];
  5682. } else {
  5683. $this->x += $mc_margin['L'];
  5684. }
  5685. $cborder = $border_middle;
  5686. $h = $this->h - $this->y - $this->bMargin;
  5687. $resth -= $h;
  5688. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5689. } // end for each column
  5690. }
  5691. if ($cborder OR $fill) {
  5692. $offsetlen = strlen($ccode);
  5693. // draw border and fill
  5694. if ($this->inxobj) {
  5695. // we are inside an XObject template
  5696. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  5697. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  5698. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  5699. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  5700. } else {
  5701. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  5702. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  5703. }
  5704. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  5705. $pstart = substr($pagebuff, 0, $pagemark);
  5706. $pend = substr($pagebuff, $pagemark);
  5707. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  5708. } else {
  5709. if (end($this->transfmrk[$this->page]) !== false) {
  5710. $pagemarkkey = key($this->transfmrk[$this->page]);
  5711. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  5712. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  5713. } elseif ($this->InFooter) {
  5714. $pagemark = $this->footerpos[$this->page];
  5715. $this->footerpos[$this->page] += $offsetlen;
  5716. } else {
  5717. $pagemark = $this->intmrk[$this->page];
  5718. $this->intmrk[$this->page] += $offsetlen;
  5719. }
  5720. $pagebuff = $this->getPageBuffer($this->page);
  5721. $pstart = substr($pagebuff, 0, $pagemark);
  5722. $pend = substr($pagebuff, $pagemark);
  5723. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  5724. }
  5725. }
  5726. } // end for each page
  5727. // restore page regions check
  5728. $this->check_page_regions = $check_page_regions;
  5729. // Get end-of-cell Y position
  5730. $currentY = $this->GetY();
  5731. // restore previous values
  5732. if ($this->num_columns > 1) {
  5733. $this->selectColumn();
  5734. } else {
  5735. // restore original margins
  5736. $this->lMargin = $lMargin;
  5737. $this->rMargin = $rMargin;
  5738. if ($this->page > $startpage) {
  5739. // check for margin variations between pages (i.e. booklet mode)
  5740. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  5741. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  5742. if (($dl != 0) OR ($dr != 0)) {
  5743. $this->lMargin += $dl;
  5744. $this->rMargin += $dr;
  5745. }
  5746. }
  5747. }
  5748. if ($ln > 0) {
  5749. //Go to the beginning of the next line
  5750. $this->SetY($currentY + $mc_margin['B']);
  5751. if ($ln == 2) {
  5752. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5753. }
  5754. } else {
  5755. // go left or right by case
  5756. $this->setPage($startpage);
  5757. $this->y = $y;
  5758. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5759. }
  5760. $this->setContentMark();
  5761. $this->cell_padding = $prev_cell_padding;
  5762. $this->cell_margin = $prev_cell_margin;
  5763. $this->clMargin = $this->lMargin;
  5764. $this->crMargin = $this->rMargin;
  5765. return $nl;
  5766. }
  5767. /**
  5768. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  5769. * @param $txt (string) String for calculating his height
  5770. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5771. * @param $reseth (boolean) if true reset the last cell height (default false).
  5772. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5773. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5774. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5775. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5776. * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
  5777. * @public
  5778. * @since 4.5.011
  5779. */
  5780. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5781. if ($txt === NULL) {
  5782. return 0;
  5783. }
  5784. if ($txt === '') {
  5785. // empty string
  5786. return 1;
  5787. }
  5788. // adjust internal padding
  5789. $prev_cell_padding = $this->cell_padding;
  5790. $prev_lasth = $this->lasth;
  5791. if (is_array($cellpadding)) {
  5792. $this->cell_padding = $cellpadding;
  5793. }
  5794. $this->adjustCellPadding($border);
  5795. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5796. if ($this->rtl) {
  5797. $w = $this->x - $this->lMargin;
  5798. } else {
  5799. $w = $this->w - $this->rMargin - $this->x;
  5800. }
  5801. }
  5802. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5803. if ($reseth) {
  5804. // reset row height
  5805. $this->resetLastH();
  5806. }
  5807. $lines = 1;
  5808. $sum = 0;
  5809. $chars = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont), $txt, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  5810. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  5811. $length = count($chars);
  5812. $lastSeparator = -1;
  5813. for ($i = 0; $i < $length; ++$i) {
  5814. $c = $chars[$i];
  5815. $charWidth = $charsWidth[$i];
  5816. if (($c != 160)
  5817. AND (($c == 173)
  5818. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  5819. OR (($c == 45)
  5820. AND ($i > 0) AND ($i < ($length - 1))
  5821. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i - 1)], $this->isunicode))
  5822. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  5823. )
  5824. )
  5825. ) {
  5826. $lastSeparator = $i;
  5827. }
  5828. if ((($sum + $charWidth) > $wmax) OR ($c == 10)) {
  5829. ++$lines;
  5830. if ($c == 10) {
  5831. $lastSeparator = -1;
  5832. $sum = 0;
  5833. } elseif ($lastSeparator != -1) {
  5834. $i = $lastSeparator;
  5835. $lastSeparator = -1;
  5836. $sum = 0;
  5837. } else {
  5838. $sum = $charWidth;
  5839. }
  5840. } else {
  5841. $sum += $charWidth;
  5842. }
  5843. }
  5844. if ($chars[($length - 1)] == 10) {
  5845. --$lines;
  5846. }
  5847. $this->cell_padding = $prev_cell_padding;
  5848. $this->lasth = $prev_lasth;
  5849. return $lines;
  5850. }
  5851. /**
  5852. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  5853. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  5854. * @pre
  5855. * // store current object
  5856. * $pdf->startTransaction();
  5857. * // store starting values
  5858. * $start_y = $pdf->GetY();
  5859. * $start_page = $pdf->getPage();
  5860. * // call your printing functions with your parameters
  5861. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5862. * $pdf->MultiCell($w=0, $h=0, $txt, $border=1, $align='L', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0);
  5863. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5864. * // get the new Y
  5865. * $end_y = $pdf->GetY();
  5866. * $end_page = $pdf->getPage();
  5867. * // calculate height
  5868. * $height = 0;
  5869. * if ($end_page == $start_page) {
  5870. * $height = $end_y - $start_y;
  5871. * } else {
  5872. * for ($page=$start_page; $page <= $end_page; ++$page) {
  5873. * $this->setPage($page);
  5874. * if ($page == $start_page) {
  5875. * // first page
  5876. * $height += $this->h - $start_y - $this->bMargin;
  5877. * } elseif ($page == $end_page) {
  5878. * // last page
  5879. * $height += $end_y - $this->tMargin;
  5880. * } else {
  5881. * $height += $this->h - $this->tMargin - $this->bMargin;
  5882. * }
  5883. * }
  5884. * }
  5885. * // restore previous object
  5886. * $pdf = $pdf->rollbackTransaction();
  5887. *
  5888. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5889. * @param $txt (string) String for calculating his height
  5890. * @param $reseth (boolean) if true reset the last cell height (default false).
  5891. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5892. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5893. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5894. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5895. * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
  5896. * @public
  5897. */
  5898. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5899. // adjust internal padding
  5900. $prev_cell_padding = $this->cell_padding;
  5901. $prev_lasth = $this->lasth;
  5902. if (is_array($cellpadding)) {
  5903. $this->cell_padding = $cellpadding;
  5904. }
  5905. $this->adjustCellPadding($border);
  5906. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  5907. $height = $this->getCellHeight(($lines * $this->FontSize), $autopadding);
  5908. $this->cell_padding = $prev_cell_padding;
  5909. $this->lasth = $prev_lasth;
  5910. return $height;
  5911. }
  5912. /**
  5913. * This method prints text from the current position.<br />
  5914. * @param $h (float) Line height
  5915. * @param $txt (string) String to print
  5916. * @param $link (mixed) URL or identifier returned by AddLink()
  5917. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5918. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  5919. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  5920. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  5921. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  5922. * @param $firstblock (boolean) if true the string is the starting of a line.
  5923. * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
  5924. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  5925. * @param $margin (array) margin array of the parent container
  5926. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  5927. * @public
  5928. * @since 1.5
  5929. */
  5930. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  5931. // check page for no-write regions and adapt page margins if necessary
  5932. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5933. if (strlen($txt) == 0) {
  5934. // fix empty text
  5935. $txt = ' ';
  5936. }
  5937. if ($margin === '') {
  5938. // set default margins
  5939. $margin = $this->cell_margin;
  5940. }
  5941. // remove carriage returns
  5942. $s = str_replace("\r", '', $txt);
  5943. // check if string contains arabic text
  5944. if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {
  5945. $arabic = true;
  5946. } else {
  5947. $arabic = false;
  5948. }
  5949. // check if string contains RTL text
  5950. if ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {
  5951. $rtlmode = true;
  5952. } else {
  5953. $rtlmode = false;
  5954. }
  5955. // get a char width
  5956. $chrwidth = $this->GetCharWidth(46); // dot character
  5957. // get array of unicode values
  5958. $chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);
  5959. // calculate maximum width for a single character on string
  5960. $chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
  5961. array_walk($chrw, array($this, 'getRawCharWidth'));
  5962. $maxchwidth = max($chrw);
  5963. // get array of chars
  5964. $uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);
  5965. // get the number of characters
  5966. $nb = count($chars);
  5967. // replacement for SHY character (minus symbol)
  5968. $shy_replacement = 45;
  5969. $shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);
  5970. // widht for SHY replacement
  5971. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  5972. // page width
  5973. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  5974. // calculate remaining line width ($w)
  5975. if ($this->rtl) {
  5976. $w = $this->x - $this->lMargin;
  5977. } else {
  5978. $w = $this->w - $this->rMargin - $this->x;
  5979. }
  5980. // max column width
  5981. $wmax = ($w - $wadj);
  5982. if (!$firstline) {
  5983. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  5984. }
  5985. if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
  5986. // the maximum width character do not fit on column
  5987. return '';
  5988. }
  5989. // minimum row height
  5990. $row_height = max($h, $this->getCellHeight($this->FontSize));
  5991. // max Y
  5992. $maxy = $this->y + $maxh - max($row_height, $h);
  5993. $start_page = $this->page;
  5994. $i = 0; // character position
  5995. $j = 0; // current starting position
  5996. $sep = -1; // position of the last blank space
  5997. $prevsep = $sep; // previous separator
  5998. $shy = false; // true if the last blank is a soft hypen (SHY)
  5999. $prevshy = $shy; // previous shy mode
  6000. $l = 0; // current string length
  6001. $nl = 0; //number of lines
  6002. $linebreak = false;
  6003. $pc = 0; // previous character
  6004. // for each character
  6005. while ($i < $nb) {
  6006. if (($maxh > 0) AND ($this->y > $maxy) ) {
  6007. break;
  6008. }
  6009. //Get the current character
  6010. $c = $chars[$i];
  6011. if ($c == 10) { // 10 = "\n" = new line
  6012. //Explicit line break
  6013. if ($align == 'J') {
  6014. if ($this->rtl) {
  6015. $talign = 'R';
  6016. } else {
  6017. $talign = 'L';
  6018. }
  6019. } else {
  6020. $talign = $align;
  6021. }
  6022. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6023. if ($firstline) {
  6024. $startx = $this->x;
  6025. $tmparr = array_slice($chars, $j, ($i - $j));
  6026. if ($rtlmode) {
  6027. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6028. }
  6029. $linew = $this->GetArrStringWidth($tmparr);
  6030. unset($tmparr);
  6031. if ($this->rtl) {
  6032. $this->endlinex = $startx - $linew;
  6033. } else {
  6034. $this->endlinex = $startx + $linew;
  6035. }
  6036. $w = $linew;
  6037. $tmpcellpadding = $this->cell_padding;
  6038. if ($maxh == 0) {
  6039. $this->SetCellPadding(0);
  6040. }
  6041. }
  6042. if ($firstblock AND $this->isRTLTextDir()) {
  6043. $tmpstr = $this->stringRightTrim($tmpstr);
  6044. }
  6045. // Skip newlines at the beginning of a page or column
  6046. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6047. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6048. }
  6049. unset($tmpstr);
  6050. if ($firstline) {
  6051. $this->cell_padding = $tmpcellpadding;
  6052. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6053. }
  6054. ++$nl;
  6055. $j = $i + 1;
  6056. $l = 0;
  6057. $sep = -1;
  6058. $prevsep = $sep;
  6059. $shy = false;
  6060. // account for margin changes
  6061. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6062. $this->AcceptPageBreak();
  6063. if ($this->rtl) {
  6064. $this->x -= $margin['R'];
  6065. } else {
  6066. $this->x += $margin['L'];
  6067. }
  6068. $this->lMargin += $margin['L'];
  6069. $this->rMargin += $margin['R'];
  6070. }
  6071. $w = $this->getRemainingWidth();
  6072. $wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
  6073. } else {
  6074. // 160 is the non-breaking space.
  6075. // 173 is SHY (Soft Hypen).
  6076. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6077. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6078. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6079. if (($c != 160)
  6080. AND (($c == 173)
  6081. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  6082. OR (($c == 45)
  6083. AND ($i < ($nb - 1))
  6084. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))
  6085. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  6086. )
  6087. )
  6088. ) {
  6089. // update last blank space position
  6090. $prevsep = $sep;
  6091. $sep = $i;
  6092. // check if is a SHY
  6093. if (($c == 173) OR ($c == 45)) {
  6094. $prevshy = $shy;
  6095. $shy = true;
  6096. if ($pc == 45) {
  6097. $tmp_shy_replacement_width = 0;
  6098. $tmp_shy_replacement_char = '';
  6099. } else {
  6100. $tmp_shy_replacement_width = $shy_replacement_width;
  6101. $tmp_shy_replacement_char = $shy_replacement_char;
  6102. }
  6103. } else {
  6104. $shy = false;
  6105. }
  6106. }
  6107. // update string length
  6108. if ($this->isUnicodeFont() AND ($arabic)) {
  6109. // with bidirectional algorithm some chars may be changed affecting the line length
  6110. // *** very slow ***
  6111. $l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));
  6112. } else {
  6113. $l += $this->GetCharWidth($c);
  6114. }
  6115. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {
  6116. if (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {
  6117. $sep = $prevsep;
  6118. $shy = $prevshy;
  6119. }
  6120. // we have reached the end of column
  6121. if ($sep == -1) {
  6122. // check if the line was already started
  6123. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
  6124. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
  6125. // print a void cell and go to next line
  6126. $this->Cell($w, $h, '', 0, 1);
  6127. $linebreak = true;
  6128. if ($firstline) {
  6129. return (TCPDF_FONTS::UniArrSubString($uchars, $j));
  6130. }
  6131. } else {
  6132. // truncate the word because do not fit on column
  6133. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6134. if ($firstline) {
  6135. $startx = $this->x;
  6136. $tmparr = array_slice($chars, $j, ($i - $j));
  6137. if ($rtlmode) {
  6138. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6139. }
  6140. $linew = $this->GetArrStringWidth($tmparr);
  6141. unset($tmparr);
  6142. if ($this->rtl) {
  6143. $this->endlinex = $startx - $linew;
  6144. } else {
  6145. $this->endlinex = $startx + $linew;
  6146. }
  6147. $w = $linew;
  6148. $tmpcellpadding = $this->cell_padding;
  6149. if ($maxh == 0) {
  6150. $this->SetCellPadding(0);
  6151. }
  6152. }
  6153. if ($firstblock AND $this->isRTLTextDir()) {
  6154. $tmpstr = $this->stringRightTrim($tmpstr);
  6155. }
  6156. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6157. unset($tmpstr);
  6158. if ($firstline) {
  6159. $this->cell_padding = $tmpcellpadding;
  6160. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6161. }
  6162. $j = $i;
  6163. --$i;
  6164. }
  6165. } else {
  6166. // word wrapping
  6167. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  6168. $endspace = 1;
  6169. } else {
  6170. $endspace = 0;
  6171. }
  6172. // check the length of the next string
  6173. $strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));
  6174. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));
  6175. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  6176. // truncate the word because do not fit on a full page width
  6177. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6178. if ($firstline) {
  6179. $startx = $this->x;
  6180. $tmparr = array_slice($chars, $j, ($i - $j));
  6181. if ($rtlmode) {
  6182. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6183. }
  6184. $linew = $this->GetArrStringWidth($tmparr);
  6185. unset($tmparr);
  6186. if ($this->rtl) {
  6187. $this->endlinex = ($startx - $linew);
  6188. } else {
  6189. $this->endlinex = ($startx + $linew);
  6190. }
  6191. $w = $linew;
  6192. $tmpcellpadding = $this->cell_padding;
  6193. if ($maxh == 0) {
  6194. $this->SetCellPadding(0);
  6195. }
  6196. }
  6197. if ($firstblock AND $this->isRTLTextDir()) {
  6198. $tmpstr = $this->stringRightTrim($tmpstr);
  6199. }
  6200. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6201. unset($tmpstr);
  6202. if ($firstline) {
  6203. $this->cell_padding = $tmpcellpadding;
  6204. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6205. }
  6206. $j = $i;
  6207. --$i;
  6208. } else {
  6209. // word wrapping
  6210. if ($shy) {
  6211. // add hypen (minus symbol) at the end of the line
  6212. $shy_width = $tmp_shy_replacement_width;
  6213. if ($this->rtl) {
  6214. $shy_char_left = $tmp_shy_replacement_char;
  6215. $shy_char_right = '';
  6216. } else {
  6217. $shy_char_left = '';
  6218. $shy_char_right = $tmp_shy_replacement_char;
  6219. }
  6220. } else {
  6221. $shy_width = 0;
  6222. $shy_char_left = '';
  6223. $shy_char_right = '';
  6224. }
  6225. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));
  6226. if ($firstline) {
  6227. $startx = $this->x;
  6228. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  6229. if ($rtlmode) {
  6230. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6231. }
  6232. $linew = $this->GetArrStringWidth($tmparr);
  6233. unset($tmparr);
  6234. if ($this->rtl) {
  6235. $this->endlinex = $startx - $linew - $shy_width;
  6236. } else {
  6237. $this->endlinex = $startx + $linew + $shy_width;
  6238. }
  6239. $w = $linew;
  6240. $tmpcellpadding = $this->cell_padding;
  6241. if ($maxh == 0) {
  6242. $this->SetCellPadding(0);
  6243. }
  6244. }
  6245. // print the line
  6246. if ($firstblock AND $this->isRTLTextDir()) {
  6247. $tmpstr = $this->stringRightTrim($tmpstr);
  6248. }
  6249. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  6250. unset($tmpstr);
  6251. if ($firstline) {
  6252. if ($chars[$sep] == 45) {
  6253. $endspace += 1;
  6254. }
  6255. // return the remaining text
  6256. $this->cell_padding = $tmpcellpadding;
  6257. return (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));
  6258. }
  6259. $i = $sep;
  6260. $sep = -1;
  6261. $shy = false;
  6262. $j = ($i + 1);
  6263. }
  6264. }
  6265. // account for margin changes
  6266. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6267. $this->AcceptPageBreak();
  6268. if ($this->rtl) {
  6269. $this->x -= $margin['R'];
  6270. } else {
  6271. $this->x += $margin['L'];
  6272. }
  6273. $this->lMargin += $margin['L'];
  6274. $this->rMargin += $margin['R'];
  6275. }
  6276. $w = $this->getRemainingWidth();
  6277. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6278. if ($linebreak) {
  6279. $linebreak = false;
  6280. } else {
  6281. ++$nl;
  6282. $l = 0;
  6283. }
  6284. }
  6285. }
  6286. // save last character
  6287. $pc = $c;
  6288. ++$i;
  6289. } // end while i < nb
  6290. // print last substring (if any)
  6291. if ($l > 0) {
  6292. switch ($align) {
  6293. case 'J':
  6294. case 'C': {
  6295. $w = $w;
  6296. break;
  6297. }
  6298. case 'L': {
  6299. if ($this->rtl) {
  6300. $w = $w;
  6301. } else {
  6302. $w = $l;
  6303. }
  6304. break;
  6305. }
  6306. case 'R': {
  6307. if ($this->rtl) {
  6308. $w = $l;
  6309. } else {
  6310. $w = $w;
  6311. }
  6312. break;
  6313. }
  6314. default: {
  6315. $w = $l;
  6316. break;
  6317. }
  6318. }
  6319. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);
  6320. if ($firstline) {
  6321. $startx = $this->x;
  6322. $tmparr = array_slice($chars, $j, ($nb - $j));
  6323. if ($rtlmode) {
  6324. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6325. }
  6326. $linew = $this->GetArrStringWidth($tmparr);
  6327. unset($tmparr);
  6328. if ($this->rtl) {
  6329. $this->endlinex = $startx - $linew;
  6330. } else {
  6331. $this->endlinex = $startx + $linew;
  6332. }
  6333. $w = $linew;
  6334. $tmpcellpadding = $this->cell_padding;
  6335. if ($maxh == 0) {
  6336. $this->SetCellPadding(0);
  6337. }
  6338. }
  6339. if ($firstblock AND $this->isRTLTextDir()) {
  6340. $tmpstr = $this->stringRightTrim($tmpstr);
  6341. }
  6342. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  6343. unset($tmpstr);
  6344. if ($firstline) {
  6345. $this->cell_padding = $tmpcellpadding;
  6346. return (TCPDF_FONTS::UniArrSubString($uchars, $nb));
  6347. }
  6348. ++$nl;
  6349. }
  6350. if ($firstline) {
  6351. return '';
  6352. }
  6353. return $nl;
  6354. }
  6355. /**
  6356. * Returns the remaining width between the current position and margins.
  6357. * @return int Return the remaining width
  6358. * @protected
  6359. */
  6360. protected function getRemainingWidth() {
  6361. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  6362. if ($this->rtl) {
  6363. return ($this->x - $this->lMargin);
  6364. } else {
  6365. return ($this->w - $this->rMargin - $this->x);
  6366. }
  6367. }
  6368. /**
  6369. * Set the block dimensions accounting for page breaks and page/column fitting
  6370. * @param $w (float) width
  6371. * @param $h (float) height
  6372. * @param $x (float) X coordinate
  6373. * @param $y (float) Y coodiante
  6374. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  6375. * @return array($w, $h, $x, $y)
  6376. * @protected
  6377. * @since 5.5.009 (2010-07-05)
  6378. */
  6379. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  6380. if ($w <= 0) {
  6381. // set maximum width
  6382. $w = ($this->w - $this->lMargin - $this->rMargin);
  6383. if ($w <= 0) {
  6384. $w = 1;
  6385. }
  6386. }
  6387. if ($h <= 0) {
  6388. // set maximum height
  6389. $h = ($this->PageBreakTrigger - $this->tMargin);
  6390. if ($h <= 0) {
  6391. $h = 1;
  6392. }
  6393. }
  6394. // resize the block to be vertically contained on a single page or single column
  6395. if ($fitonpage OR $this->AutoPageBreak) {
  6396. $ratio_wh = ($w / $h);
  6397. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  6398. $h = $this->PageBreakTrigger - $this->tMargin;
  6399. $w = ($h * $ratio_wh);
  6400. }
  6401. // resize the block to be horizontally contained on a single page or single column
  6402. if ($fitonpage) {
  6403. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  6404. if ($w > $maxw) {
  6405. $w = $maxw;
  6406. $h = ($w / $ratio_wh);
  6407. }
  6408. }
  6409. }
  6410. // Check whether we need a new page or new column first as this does not fit
  6411. $prev_x = $this->x;
  6412. $prev_y = $this->y;
  6413. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  6414. $y = $this->y;
  6415. if ($this->rtl) {
  6416. $x += ($prev_x - $this->x);
  6417. } else {
  6418. $x += ($this->x - $prev_x);
  6419. }
  6420. $this->newline = true;
  6421. }
  6422. // resize the block to be contained on the remaining available page or column space
  6423. if ($fitonpage) {
  6424. $ratio_wh = ($w / $h);
  6425. if (($y + $h) > $this->PageBreakTrigger) {
  6426. $h = $this->PageBreakTrigger - $y;
  6427. $w = ($h * $ratio_wh);
  6428. }
  6429. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  6430. $w = $this->w - $this->rMargin - $x;
  6431. $h = ($w / $ratio_wh);
  6432. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  6433. $w = $x - $this->lMargin;
  6434. $h = ($w / $ratio_wh);
  6435. }
  6436. }
  6437. return array($w, $h, $x, $y);
  6438. }
  6439. /**
  6440. * Puts an image in the page.
  6441. * The upper-left corner must be given.
  6442. * The dimensions can be specified in different ways:<ul>
  6443. * <li>explicit width and height (expressed in user unit)</li>
  6444. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  6445. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  6446. * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
  6447. * The format can be specified explicitly or inferred from the file extension.<br />
  6448. * It is possible to put a link on the image.<br />
  6449. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  6450. * @param $file (string) Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg').
  6451. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  6452. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  6453. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6454. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6455. * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  6456. * @param $link (mixed) URL or identifier returned by AddLink().
  6457. * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  6458. * @param $resize (mixed) If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
  6459. * @param $dpi (int) dot-per-inch resolution used on resize
  6460. * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  6461. * @param $ismask (boolean) true if this image is a mask, false otherwise
  6462. * @param $imgmask (mixed) image object returned by this function or false
  6463. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  6464. * @param $fitbox (mixed) If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom).
  6465. * @param $hidden (boolean) If true do not display the image.
  6466. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  6467. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  6468. * @param $altimgs (array) Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
  6469. * @return image information
  6470. * @public
  6471. * @since 1.1
  6472. */
  6473. public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false, $alt=false, $altimgs=array()) {
  6474. if ($this->state != 2) {
  6475. return;
  6476. }
  6477. if (strcmp($x, '') === 0) {
  6478. $x = $this->x;
  6479. }
  6480. if (strcmp($y, '') === 0) {
  6481. $y = $this->y;
  6482. }
  6483. // check page for no-write regions and adapt page margins if necessary
  6484. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  6485. $exurl = ''; // external streams
  6486. $imsize = FALSE;
  6487. // check if we are passing an image as file or string
  6488. if ($file[0] === '@') {
  6489. // image from string
  6490. $imgdata = substr($file, 1);
  6491. } else { // image file
  6492. if ($file[0] === '*') {
  6493. // image as external stream
  6494. $file = substr($file, 1);
  6495. $exurl = $file;
  6496. }
  6497. // check if file exist and it is valid
  6498. if (!@TCPDF_STATIC::file_exists($file)) {
  6499. return false;
  6500. }
  6501. if (($imsize = @getimagesize($file)) === FALSE) {
  6502. if (in_array($file, $this->imagekeys)) {
  6503. // get existing image data
  6504. $info = $this->getImageBuffer($file);
  6505. $imsize = array($info['w'], $info['h']);
  6506. } elseif (strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE) {
  6507. $imgdata = TCPDF_STATIC::fileGetContents($file);
  6508. }
  6509. }
  6510. }
  6511. if (!empty($imgdata)) {
  6512. // copy image to cache
  6513. $original_file = $file;
  6514. $file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6515. $fp = TCPDF_STATIC::fopenLocal($file, 'w');
  6516. if (!$fp) {
  6517. $this->Error('Unable to write file: '.$file);
  6518. }
  6519. fwrite($fp, $imgdata);
  6520. fclose($fp);
  6521. unset($imgdata);
  6522. $imsize = @getimagesize($file);
  6523. if ($imsize === FALSE) {
  6524. unlink($file);
  6525. $file = $original_file;
  6526. }
  6527. }
  6528. if ($imsize === FALSE) {
  6529. if (($w > 0) AND ($h > 0)) {
  6530. // get measures from specified data
  6531. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6532. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6533. $imsize = array($pw, $ph);
  6534. } else {
  6535. $this->Error('[Image] Unable to get the size of the image: '.$file);
  6536. }
  6537. }
  6538. // file hash
  6539. $filehash = md5($file);
  6540. // get original image width and height in pixels
  6541. list($pixw, $pixh) = $imsize;
  6542. // calculate image width and height on document
  6543. if (($w <= 0) AND ($h <= 0)) {
  6544. // convert image size to document unit
  6545. $w = $this->pixelsToUnits($pixw);
  6546. $h = $this->pixelsToUnits($pixh);
  6547. } elseif ($w <= 0) {
  6548. $w = $h * $pixw / $pixh;
  6549. } elseif ($h <= 0) {
  6550. $h = $w * $pixh / $pixw;
  6551. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  6552. if (strlen($fitbox) !== 2) {
  6553. // set default alignment
  6554. $fitbox = '--';
  6555. }
  6556. // scale image dimensions proportionally to fit within the ($w, $h) box
  6557. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  6558. // store current height
  6559. $oldh = $h;
  6560. // calculate new height
  6561. $h = $w * $pixh / $pixw;
  6562. // height difference
  6563. $hdiff = ($oldh - $h);
  6564. // vertical alignment
  6565. switch (strtoupper($fitbox[1])) {
  6566. case 'T': {
  6567. break;
  6568. }
  6569. case 'M': {
  6570. $y += ($hdiff / 2);
  6571. break;
  6572. }
  6573. case 'B': {
  6574. $y += $hdiff;
  6575. break;
  6576. }
  6577. }
  6578. } else {
  6579. // store current width
  6580. $oldw = $w;
  6581. // calculate new width
  6582. $w = $h * $pixw / $pixh;
  6583. // width difference
  6584. $wdiff = ($oldw - $w);
  6585. // horizontal alignment
  6586. switch (strtoupper($fitbox[0])) {
  6587. case 'L': {
  6588. if ($this->rtl) {
  6589. $x -= $wdiff;
  6590. }
  6591. break;
  6592. }
  6593. case 'C': {
  6594. if ($this->rtl) {
  6595. $x -= ($wdiff / 2);
  6596. } else {
  6597. $x += ($wdiff / 2);
  6598. }
  6599. break;
  6600. }
  6601. case 'R': {
  6602. if (!$this->rtl) {
  6603. $x += $wdiff;
  6604. }
  6605. break;
  6606. }
  6607. }
  6608. }
  6609. }
  6610. // fit the image on available space
  6611. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  6612. // calculate new minimum dimensions in pixels
  6613. $neww = round($w * $this->k * $dpi / $this->dpi);
  6614. $newh = round($h * $this->k * $dpi / $this->dpi);
  6615. // check if resize is necessary (resize is used only to reduce the image)
  6616. $newsize = ($neww * $newh);
  6617. $pixsize = ($pixw * $pixh);
  6618. if (intval($resize) == 2) {
  6619. $resize = true;
  6620. } elseif ($newsize >= $pixsize) {
  6621. $resize = false;
  6622. }
  6623. // check if image has been already added on document
  6624. $newimage = true;
  6625. if (in_array($file, $this->imagekeys)) {
  6626. $newimage = false;
  6627. // get existing image data
  6628. $info = $this->getImageBuffer($file);
  6629. if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
  6630. // check if the newer image is larger
  6631. $oldsize = ($info['w'] * $info['h']);
  6632. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6633. $newimage = true;
  6634. }
  6635. }
  6636. } elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
  6637. // create temp image file (without alpha channel)
  6638. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6639. // create temp alpha file
  6640. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6641. // check for cached images
  6642. if (in_array($tempfile_plain, $this->imagekeys)) {
  6643. // get existing image data
  6644. $info = $this->getImageBuffer($tempfile_plain);
  6645. // check if the newer image is larger
  6646. $oldsize = ($info['w'] * $info['h']);
  6647. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6648. $newimage = true;
  6649. } else {
  6650. $newimage = false;
  6651. // embed mask image
  6652. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6653. // embed image, masked with previously embedded mask
  6654. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6655. }
  6656. }
  6657. }
  6658. if ($newimage) {
  6659. //First use of image, get info
  6660. $type = strtolower($type);
  6661. if ($type == '') {
  6662. $type = TCPDF_IMAGES::getImageFileType($file, $imsize);
  6663. } elseif ($type == 'jpg') {
  6664. $type = 'jpeg';
  6665. }
  6666. $mqr = TCPDF_STATIC::get_mqr();
  6667. TCPDF_STATIC::set_mqr(false);
  6668. // Specific image handlers (defined on TCPDF_IMAGES CLASS)
  6669. $mtd = '_parse'.$type;
  6670. // GD image handler function
  6671. $gdfunction = 'imagecreatefrom'.$type;
  6672. $info = false;
  6673. if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  6674. // TCPDF image functions
  6675. $info = TCPDF_IMAGES::$mtd($file);
  6676. if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
  6677. AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
  6678. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  6679. }
  6680. }
  6681. if (($info === false) AND function_exists($gdfunction)) {
  6682. try {
  6683. // GD library
  6684. $img = $gdfunction($file);
  6685. if ($img !== false) {
  6686. if ($resize) {
  6687. $imgr = imagecreatetruecolor($neww, $newh);
  6688. if (($type == 'gif') OR ($type == 'png')) {
  6689. $imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
  6690. }
  6691. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  6692. $img = $imgr;
  6693. }
  6694. if (($type == 'gif') OR ($type == 'png')) {
  6695. $info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6696. } else {
  6697. $info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6698. }
  6699. }
  6700. } catch(Exception $e) {
  6701. $info = false;
  6702. }
  6703. }
  6704. if (($info === false) AND extension_loaded('imagick')) {
  6705. try {
  6706. // ImageMagick library
  6707. $img = new Imagick();
  6708. if ($type == 'svg') {
  6709. if ($file[0] === '@') {
  6710. // image from string
  6711. $svgimg = substr($file, 1);
  6712. } else {
  6713. // get SVG file content
  6714. $svgimg = TCPDF_STATIC::fileGetContents($file);
  6715. }
  6716. if ($svgimg !== FALSE) {
  6717. // get width and height
  6718. $regs = array();
  6719. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  6720. $svgtag = $regs[1];
  6721. $tmp = array();
  6722. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6723. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6724. $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
  6725. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  6726. } else {
  6727. $ow = $w;
  6728. }
  6729. $tmp = array();
  6730. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6731. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6732. $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
  6733. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  6734. } else {
  6735. $oh = $h;
  6736. }
  6737. $tmp = array();
  6738. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  6739. $vbw = ($ow * $this->imgscale * $this->k);
  6740. $vbh = ($oh * $this->imgscale * $this->k);
  6741. $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
  6742. $svgtag = $vbox.$svgtag;
  6743. }
  6744. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  6745. }
  6746. $img->readImageBlob($svgimg);
  6747. }
  6748. } else {
  6749. $img->readImage($file);
  6750. }
  6751. if ($resize) {
  6752. $img->resizeImage($neww, $newh, 10, 1, false);
  6753. }
  6754. $img->setCompressionQuality($this->jpeg_quality);
  6755. $img->setImageFormat('jpeg');
  6756. $tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6757. $img->writeImage($tempname);
  6758. $info = TCPDF_IMAGES::_parsejpeg($tempname);
  6759. unlink($tempname);
  6760. $img->destroy();
  6761. } catch(Exception $e) {
  6762. $info = false;
  6763. }
  6764. }
  6765. if ($info === false) {
  6766. // unable to process image
  6767. return;
  6768. }
  6769. TCPDF_STATIC::set_mqr($mqr);
  6770. if ($ismask) {
  6771. // force grayscale
  6772. $info['cs'] = 'DeviceGray';
  6773. }
  6774. if ($imgmask !== false) {
  6775. $info['masked'] = $imgmask;
  6776. }
  6777. if (!empty($exurl)) {
  6778. $info['exurl'] = $exurl;
  6779. }
  6780. // array of alternative images
  6781. $info['altimgs'] = $altimgs;
  6782. // add image to document
  6783. $info['i'] = $this->setImageBuffer($file, $info);
  6784. }
  6785. // set alignment
  6786. $this->img_rb_y = $y + $h;
  6787. // set alignment
  6788. if ($this->rtl) {
  6789. if ($palign == 'L') {
  6790. $ximg = $this->lMargin;
  6791. } elseif ($palign == 'C') {
  6792. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6793. } elseif ($palign == 'R') {
  6794. $ximg = $this->w - $this->rMargin - $w;
  6795. } else {
  6796. $ximg = $x - $w;
  6797. }
  6798. $this->img_rb_x = $ximg;
  6799. } else {
  6800. if ($palign == 'L') {
  6801. $ximg = $this->lMargin;
  6802. } elseif ($palign == 'C') {
  6803. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6804. } elseif ($palign == 'R') {
  6805. $ximg = $this->w - $this->rMargin - $w;
  6806. } else {
  6807. $ximg = $x;
  6808. }
  6809. $this->img_rb_x = $ximg + $w;
  6810. }
  6811. if ($ismask OR $hidden) {
  6812. // image is not displayed
  6813. return $info['i'];
  6814. }
  6815. $xkimg = $ximg * $this->k;
  6816. if (!$alt) {
  6817. // only non-alternative immages will be set
  6818. $this->_out(sprintf('q %F 0 0 %F %F %F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
  6819. }
  6820. if (!empty($border)) {
  6821. $bx = $this->x;
  6822. $by = $this->y;
  6823. $this->x = $ximg;
  6824. if ($this->rtl) {
  6825. $this->x += $w;
  6826. }
  6827. $this->y = $y;
  6828. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  6829. $this->x = $bx;
  6830. $this->y = $by;
  6831. }
  6832. if ($link) {
  6833. $this->Link($ximg, $y, $w, $h, $link, 0);
  6834. }
  6835. // set pointer to align the next text/objects
  6836. switch($align) {
  6837. case 'T': {
  6838. $this->y = $y;
  6839. $this->x = $this->img_rb_x;
  6840. break;
  6841. }
  6842. case 'M': {
  6843. $this->y = $y + round($h/2);
  6844. $this->x = $this->img_rb_x;
  6845. break;
  6846. }
  6847. case 'B': {
  6848. $this->y = $this->img_rb_y;
  6849. $this->x = $this->img_rb_x;
  6850. break;
  6851. }
  6852. case 'N': {
  6853. $this->SetY($this->img_rb_y);
  6854. break;
  6855. }
  6856. default:{
  6857. break;
  6858. }
  6859. }
  6860. $this->endlinex = $this->img_rb_x;
  6861. if ($this->inxobj) {
  6862. // we are inside an XObject template
  6863. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  6864. }
  6865. return $info['i'];
  6866. }
  6867. /**
  6868. * Extract info from a PNG image with alpha channel using the Imagick or GD library.
  6869. * @param $file (string) Name of the file containing the image.
  6870. * @param $x (float) Abscissa of the upper-left corner.
  6871. * @param $y (float) Ordinate of the upper-left corner.
  6872. * @param $wpx (float) Original width of the image in pixels.
  6873. * @param $hpx (float) original height of the image in pixels.
  6874. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6875. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6876. * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  6877. * @param $link (mixed) URL or identifier returned by AddLink().
  6878. * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  6879. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  6880. * @param $dpi (int) dot-per-inch resolution used on resize
  6881. * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  6882. * @param $filehash (string) File hash used to build unique file names.
  6883. * @author Nicola Asuni
  6884. * @protected
  6885. * @since 4.3.007 (2008-12-04)
  6886. * @see Image()
  6887. */
  6888. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  6889. // create temp images
  6890. if (empty($filehash)) {
  6891. $filehash = md5($file);
  6892. }
  6893. // create temp image file (without alpha channel)
  6894. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6895. // create temp alpha file
  6896. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6897. $parsed = false;
  6898. $parse_error = '';
  6899. // ImageMagick extension
  6900. if (($parsed === false) AND extension_loaded('imagick')) {
  6901. try {
  6902. // ImageMagick library
  6903. $img = new Imagick();
  6904. $img->readImage($file);
  6905. // clone image object
  6906. $imga = TCPDF_STATIC::objclone($img);
  6907. // extract alpha channel
  6908. if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
  6909. $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
  6910. } else {
  6911. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  6912. $img->negateImage(true);
  6913. }
  6914. $img->setImageFormat('png');
  6915. $img->writeImage($tempfile_alpha);
  6916. // remove alpha channel
  6917. if (method_exists($imga, 'setImageMatte')) {
  6918. $imga->setImageMatte(false);
  6919. } else {
  6920. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  6921. }
  6922. $imga->setImageFormat('png');
  6923. $imga->writeImage($tempfile_plain);
  6924. $parsed = true;
  6925. } catch (Exception $e) {
  6926. // Imagemagick fails, try with GD
  6927. $parse_error = 'Imagick library error: '.$e->getMessage();
  6928. }
  6929. }
  6930. // GD extension
  6931. if (($parsed === false) AND function_exists('imagecreatefrompng')) {
  6932. try {
  6933. // generate images
  6934. $img = imagecreatefrompng($file);
  6935. $imgalpha = imagecreate($wpx, $hpx);
  6936. // generate gray scale palette (0 -> 255)
  6937. for ($c = 0; $c < 256; ++$c) {
  6938. ImageColorAllocate($imgalpha, $c, $c, $c);
  6939. }
  6940. // extract alpha channel
  6941. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  6942. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  6943. $color = imagecolorat($img, $xpx, $ypx);
  6944. // get and correct gamma color
  6945. $alpha = $this->getGDgamma($img, $color);
  6946. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  6947. }
  6948. }
  6949. imagepng($imgalpha, $tempfile_alpha);
  6950. imagedestroy($imgalpha);
  6951. // extract image without alpha channel
  6952. $imgplain = imagecreatetruecolor($wpx, $hpx);
  6953. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  6954. imagepng($imgplain, $tempfile_plain);
  6955. imagedestroy($imgplain);
  6956. $parsed = true;
  6957. } catch (Exception $e) {
  6958. // GD fails
  6959. $parse_error = 'GD library error: '.$e->getMessage();
  6960. }
  6961. }
  6962. if ($parsed === false) {
  6963. if (empty($parse_error)) {
  6964. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  6965. } else {
  6966. $this->Error($parse_error);
  6967. }
  6968. }
  6969. // embed mask image
  6970. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6971. // embed image, masked with previously embedded mask
  6972. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6973. }
  6974. /**
  6975. * Get the GD-corrected PNG gamma value from alpha color
  6976. * @param $img (int) GD image Resource ID.
  6977. * @param $c (int) alpha color
  6978. * @protected
  6979. * @since 4.3.007 (2008-12-04)
  6980. */
  6981. protected function getGDgamma($img, $c) {
  6982. if (!isset($this->gdgammacache['#'.$c])) {
  6983. $colors = imagecolorsforindex($img, $c);
  6984. // GD alpha is only 7 bit (0 -> 127)
  6985. $this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
  6986. // correct gamma
  6987. $this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
  6988. // store the latest values on cache to improve performances
  6989. if (count($this->gdgammacache) > 8) {
  6990. // remove one element from the cache array
  6991. array_shift($this->gdgammacache);
  6992. }
  6993. }
  6994. return $this->gdgammacache['#'.$c];
  6995. }
  6996. /**
  6997. * Performs a line break.
  6998. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  6999. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  7000. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  7001. * @public
  7002. * @since 1.0
  7003. * @see Cell()
  7004. */
  7005. public function Ln($h='', $cell=false) {
  7006. if (($this->num_columns > 1) AND ($this->y == $this->columns[$this->current_column]['y']) AND isset($this->columns[$this->current_column]['x']) AND ($this->x == $this->columns[$this->current_column]['x'])) {
  7007. // revove vertical space from the top of the column
  7008. return;
  7009. }
  7010. if ($cell) {
  7011. if ($this->rtl) {
  7012. $cellpadding = $this->cell_padding['R'];
  7013. } else {
  7014. $cellpadding = $this->cell_padding['L'];
  7015. }
  7016. } else {
  7017. $cellpadding = 0;
  7018. }
  7019. if ($this->rtl) {
  7020. $this->x = $this->w - $this->rMargin - $cellpadding;
  7021. } else {
  7022. $this->x = $this->lMargin + $cellpadding;
  7023. }
  7024. if (is_string($h)) {
  7025. $h = $this->lasth;
  7026. }
  7027. $this->y += $h;
  7028. $this->newline = true;
  7029. }
  7030. /**
  7031. * Returns the relative X value of current position.
  7032. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  7033. * @return float
  7034. * @public
  7035. * @since 1.2
  7036. * @see SetX(), GetY(), SetY()
  7037. */
  7038. public function GetX() {
  7039. //Get x position
  7040. if ($this->rtl) {
  7041. return ($this->w - $this->x);
  7042. } else {
  7043. return $this->x;
  7044. }
  7045. }
  7046. /**
  7047. * Returns the absolute X value of current position.
  7048. * @return float
  7049. * @public
  7050. * @since 1.2
  7051. * @see SetX(), GetY(), SetY()
  7052. */
  7053. public function GetAbsX() {
  7054. return $this->x;
  7055. }
  7056. /**
  7057. * Returns the ordinate of the current position.
  7058. * @return float
  7059. * @public
  7060. * @since 1.0
  7061. * @see SetY(), GetX(), SetX()
  7062. */
  7063. public function GetY() {
  7064. return $this->y;
  7065. }
  7066. /**
  7067. * Defines the abscissa of the current position.
  7068. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  7069. * @param $x (float) The value of the abscissa in user units.
  7070. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7071. * @public
  7072. * @since 1.2
  7073. * @see GetX(), GetY(), SetY(), SetXY()
  7074. */
  7075. public function SetX($x, $rtloff=false) {
  7076. $x = floatval($x);
  7077. if (!$rtloff AND $this->rtl) {
  7078. if ($x >= 0) {
  7079. $this->x = $this->w - $x;
  7080. } else {
  7081. $this->x = abs($x);
  7082. }
  7083. } else {
  7084. if ($x >= 0) {
  7085. $this->x = $x;
  7086. } else {
  7087. $this->x = $this->w + $x;
  7088. }
  7089. }
  7090. if ($this->x < 0) {
  7091. $this->x = 0;
  7092. }
  7093. if ($this->x > $this->w) {
  7094. $this->x = $this->w;
  7095. }
  7096. }
  7097. /**
  7098. * Moves the current abscissa back to the left margin and sets the ordinate.
  7099. * If the passed value is negative, it is relative to the bottom of the page.
  7100. * @param $y (float) The value of the ordinate in user units.
  7101. * @param $resetx (bool) if true (default) reset the X position.
  7102. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7103. * @public
  7104. * @since 1.0
  7105. * @see GetX(), GetY(), SetY(), SetXY()
  7106. */
  7107. public function SetY($y, $resetx=true, $rtloff=false) {
  7108. $y = floatval($y);
  7109. if ($resetx) {
  7110. //reset x
  7111. if (!$rtloff AND $this->rtl) {
  7112. $this->x = $this->w - $this->rMargin;
  7113. } else {
  7114. $this->x = $this->lMargin;
  7115. }
  7116. }
  7117. if ($y >= 0) {
  7118. $this->y = $y;
  7119. } else {
  7120. $this->y = $this->h + $y;
  7121. }
  7122. if ($this->y < 0) {
  7123. $this->y = 0;
  7124. }
  7125. if ($this->y > $this->h) {
  7126. $this->y = $this->h;
  7127. }
  7128. }
  7129. /**
  7130. * Defines the abscissa and ordinate of the current position.
  7131. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  7132. * @param $x (float) The value of the abscissa.
  7133. * @param $y (float) The value of the ordinate.
  7134. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7135. * @public
  7136. * @since 1.2
  7137. * @see SetX(), SetY()
  7138. */
  7139. public function SetXY($x, $y, $rtloff=false) {
  7140. $this->SetY($y, false, $rtloff);
  7141. $this->SetX($x, $rtloff);
  7142. }
  7143. /**
  7144. * Set the absolute X coordinate of the current pointer.
  7145. * @param $x (float) The value of the abscissa in user units.
  7146. * @public
  7147. * @since 5.9.186 (2012-09-13)
  7148. * @see setAbsX(), setAbsY(), SetAbsXY()
  7149. */
  7150. public function SetAbsX($x) {
  7151. $this->x = floatval($x);
  7152. }
  7153. /**
  7154. * Set the absolute Y coordinate of the current pointer.
  7155. * @param $y (float) (float) The value of the ordinate in user units.
  7156. * @public
  7157. * @since 5.9.186 (2012-09-13)
  7158. * @see setAbsX(), setAbsY(), SetAbsXY()
  7159. */
  7160. public function SetAbsY($y) {
  7161. $this->y = floatval($y);
  7162. }
  7163. /**
  7164. * Set the absolute X and Y coordinates of the current pointer.
  7165. * @param $x (float) The value of the abscissa in user units.
  7166. * @param $y (float) (float) The value of the ordinate in user units.
  7167. * @public
  7168. * @since 5.9.186 (2012-09-13)
  7169. * @see setAbsX(), setAbsY(), SetAbsXY()
  7170. */
  7171. public function SetAbsXY($x, $y) {
  7172. $this->SetAbsX($x);
  7173. $this->SetAbsY($y);
  7174. }
  7175. /**
  7176. * Send the document to a given destination: string, local file or browser.
  7177. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  7178. * The method first calls Close() if necessary to terminate the document.
  7179. * @param $name (string) The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
  7180. * @param $dest (string) Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local server file with the name given by name.</li><li>S: return the document as a string (name is ignored).</li><li>FI: equivalent to F + I option</li><li>FD: equivalent to F + D option</li><li>E: return the document as base64 mime multi-part email attachment (RFC 2045)</li></ul>
  7181. * @return string
  7182. * @public
  7183. * @since 1.0
  7184. * @see Close()
  7185. */
  7186. public function Output($name='doc.pdf', $dest='I') {
  7187. //Output PDF to some destination
  7188. //Finish document if necessary
  7189. if ($this->state < 3) {
  7190. $this->Close();
  7191. }
  7192. //Normalize parameters
  7193. if (is_bool($dest)) {
  7194. $dest = $dest ? 'D' : 'F';
  7195. }
  7196. $dest = strtoupper($dest);
  7197. if ($dest[0] != 'F') {
  7198. $name = preg_replace('/[\s]+/', '_', $name);
  7199. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  7200. }
  7201. if ($this->sign) {
  7202. // *** apply digital signature to the document ***
  7203. // get the document content
  7204. $pdfdoc = $this->getBuffer();
  7205. // remove last newline
  7206. $pdfdoc = substr($pdfdoc, 0, -1);
  7207. // remove filler space
  7208. $byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
  7209. // define the ByteRange
  7210. $byte_range = array();
  7211. $byte_range[0] = 0;
  7212. $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
  7213. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  7214. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  7215. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  7216. // replace the ByteRange
  7217. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  7218. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  7219. $pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
  7220. // write the document to a temporary folder
  7221. $tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
  7222. $f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
  7223. if (!$f) {
  7224. $this->Error('Unable to create temporary file: '.$tempdoc);
  7225. }
  7226. $pdfdoc_length = strlen($pdfdoc);
  7227. fwrite($f, $pdfdoc, $pdfdoc_length);
  7228. fclose($f);
  7229. // get digital signature via openssl library
  7230. $tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
  7231. if (empty($this->signature_data['extracerts'])) {
  7232. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  7233. } else {
  7234. 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']);
  7235. }
  7236. // read signature
  7237. $signature = file_get_contents($tempsign);
  7238. // extract signature
  7239. $signature = substr($signature, $pdfdoc_length);
  7240. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  7241. $tmparr = explode("\n\n", $signature);
  7242. $signature = $tmparr[1];
  7243. // decode signature
  7244. $signature = base64_decode(trim($signature));
  7245. // add TSA timestamp to signature
  7246. $signature = $this->applyTSA($signature);
  7247. // convert signature to hex
  7248. $signature = current(unpack('H*', $signature));
  7249. $signature = str_pad($signature, $this->signature_max_length, '0');
  7250. // Add signature to the document
  7251. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  7252. $this->bufferlen = strlen($this->buffer);
  7253. }
  7254. switch($dest) {
  7255. case 'I': {
  7256. // Send PDF to the standard output
  7257. if (ob_get_contents()) {
  7258. $this->Error('Some data has already been output, can\'t send PDF file');
  7259. }
  7260. if (php_sapi_name() != 'cli') {
  7261. // send output to a browser
  7262. header('Content-Type: application/pdf');
  7263. if (headers_sent()) {
  7264. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7265. }
  7266. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7267. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7268. header('Pragma: public');
  7269. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7270. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7271. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7272. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7273. } else {
  7274. echo $this->getBuffer();
  7275. }
  7276. break;
  7277. }
  7278. case 'D': {
  7279. // download PDF as file
  7280. if (ob_get_contents()) {
  7281. $this->Error('Some data has already been output, can\'t send PDF file');
  7282. }
  7283. header('Content-Description: File Transfer');
  7284. if (headers_sent()) {
  7285. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7286. }
  7287. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7288. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7289. header('Pragma: public');
  7290. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7291. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7292. // force download dialog
  7293. if (strpos(php_sapi_name(), 'cgi') === false) {
  7294. header('Content-Type: application/force-download');
  7295. header('Content-Type: application/octet-stream', false);
  7296. header('Content-Type: application/download', false);
  7297. header('Content-Type: application/pdf', false);
  7298. } else {
  7299. header('Content-Type: application/pdf');
  7300. }
  7301. // use the Content-Disposition header to supply a recommended filename
  7302. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7303. header('Content-Transfer-Encoding: binary');
  7304. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7305. break;
  7306. }
  7307. case 'F':
  7308. case 'FI':
  7309. case 'FD': {
  7310. // save PDF to a local file
  7311. $f = TCPDF_STATIC::fopenLocal($name, 'wb');
  7312. if (!$f) {
  7313. $this->Error('Unable to create output file: '.$name);
  7314. }
  7315. fwrite($f, $this->getBuffer(), $this->bufferlen);
  7316. fclose($f);
  7317. if ($dest == 'FI') {
  7318. // send headers to browser
  7319. header('Content-Type: application/pdf');
  7320. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7321. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7322. header('Pragma: public');
  7323. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7324. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7325. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7326. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7327. } elseif ($dest == 'FD') {
  7328. // send headers to browser
  7329. if (ob_get_contents()) {
  7330. $this->Error('Some data has already been output, can\'t send PDF file');
  7331. }
  7332. header('Content-Description: File Transfer');
  7333. if (headers_sent()) {
  7334. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7335. }
  7336. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7337. header('Pragma: public');
  7338. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7339. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7340. // force download dialog
  7341. if (strpos(php_sapi_name(), 'cgi') === false) {
  7342. header('Content-Type: application/force-download');
  7343. header('Content-Type: application/octet-stream', false);
  7344. header('Content-Type: application/download', false);
  7345. header('Content-Type: application/pdf', false);
  7346. } else {
  7347. header('Content-Type: application/pdf');
  7348. }
  7349. // use the Content-Disposition header to supply a recommended filename
  7350. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7351. header('Content-Transfer-Encoding: binary');
  7352. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7353. }
  7354. break;
  7355. }
  7356. case 'E': {
  7357. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  7358. $retval = 'Content-Type: application/pdf;'."\r\n";
  7359. $retval .= ' name="'.$name.'"'."\r\n";
  7360. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  7361. $retval .= 'Content-Disposition: attachment;'."\r\n";
  7362. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  7363. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  7364. return $retval;
  7365. }
  7366. case 'S': {
  7367. // returns PDF as a string
  7368. return $this->getBuffer();
  7369. }
  7370. default: {
  7371. $this->Error('Incorrect output destination: '.$dest);
  7372. }
  7373. }
  7374. return '';
  7375. }
  7376. protected static $cleaned_ids = array();
  7377. /**
  7378. * Unset all class variables except the following critical variables.
  7379. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  7380. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  7381. * @public
  7382. * @since 4.5.016 (2009-02-24)
  7383. */
  7384. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  7385. // restore internal encoding
  7386. if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
  7387. mb_internal_encoding($this->internal_encoding);
  7388. }
  7389. if (isset(self::$cleaned_ids[$this->file_id])) {
  7390. $destroyall = false;
  7391. }
  7392. if ($destroyall AND !$preserve_objcopy) {
  7393. self::$cleaned_ids[$this->file_id] = true;
  7394. // remove all temporary files
  7395. if ($handle = @opendir(K_PATH_CACHE)) {
  7396. while ( false !== ( $file_name = readdir( $handle ) ) ) {
  7397. if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
  7398. unlink(K_PATH_CACHE.$file_name);
  7399. }
  7400. }
  7401. closedir($handle);
  7402. }
  7403. if (isset($this->imagekeys)) {
  7404. foreach($this->imagekeys as $file) {
  7405. if (strpos($file, K_PATH_CACHE) === 0) {
  7406. unlink($file);
  7407. }
  7408. }
  7409. }
  7410. }
  7411. $preserve = array(
  7412. 'file_id',
  7413. 'internal_encoding',
  7414. 'state',
  7415. 'bufferlen',
  7416. 'buffer',
  7417. 'cached_files',
  7418. 'sign',
  7419. 'signature_data',
  7420. 'signature_max_length',
  7421. 'byterange_string',
  7422. 'tsa_timestamp',
  7423. 'tsa_data'
  7424. );
  7425. foreach (array_keys(get_object_vars($this)) as $val) {
  7426. if ($destroyall OR !in_array($val, $preserve)) {
  7427. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
  7428. unset($this->$val);
  7429. }
  7430. }
  7431. }
  7432. }
  7433. /**
  7434. * Check for locale-related bug
  7435. * @protected
  7436. */
  7437. protected function _dochecks() {
  7438. //Check for locale-related bug
  7439. if (1.1 == 1) {
  7440. $this->Error('Don\'t alter the locale before including class file');
  7441. }
  7442. //Check for decimal separator
  7443. if (sprintf('%.1F', 1.0) != '1.0') {
  7444. setlocale(LC_NUMERIC, 'C');
  7445. }
  7446. }
  7447. /**
  7448. * Return an array containing variations for the basic page number alias.
  7449. * @param $a (string) Base alias.
  7450. * @return array of page number aliases
  7451. * @protected
  7452. */
  7453. protected function getInternalPageNumberAliases($a= '') {
  7454. $alias = array();
  7455. // build array of Unicode + ASCII variants (the order is important)
  7456. $alias = array('u' => array(), 'a' => array());
  7457. $u = '{'.$a.'}';
  7458. $alias['u'][] = TCPDF_STATIC::_escape($u);
  7459. if ($this->isunicode) {
  7460. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
  7461. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7462. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
  7463. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7464. }
  7465. $alias['a'][] = TCPDF_STATIC::_escape($a);
  7466. return $alias;
  7467. }
  7468. /**
  7469. * Return an array containing all internal page aliases.
  7470. * @return array of page number aliases
  7471. * @protected
  7472. */
  7473. protected function getAllInternalPageNumberAliases() {
  7474. $basic_alias = array(TCPDF_STATIC::$alias_tot_pages, TCPDF_STATIC::$alias_num_page, TCPDF_STATIC::$alias_group_tot_pages, TCPDF_STATIC::$alias_group_num_page, TCPDF_STATIC::$alias_right_shift);
  7475. $pnalias = array();
  7476. foreach($basic_alias as $k => $a) {
  7477. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  7478. }
  7479. return $pnalias;
  7480. }
  7481. /**
  7482. * Replace right shift page number aliases with spaces to correct right alignment.
  7483. * This works perfectly only when using monospaced fonts.
  7484. * @param $page (string) Page content.
  7485. * @param $aliases (array) Array of page aliases.
  7486. * @param $diff (int) initial difference to add.
  7487. * @return replaced page content.
  7488. * @protected
  7489. */
  7490. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  7491. foreach ($aliases as $type => $alias) {
  7492. foreach ($alias as $a) {
  7493. // find position of compensation factor
  7494. $startnum = (strpos($a, ':') + 1);
  7495. $a = substr($a, 0, $startnum);
  7496. if (($pos = strpos($page, $a)) !== false) {
  7497. // end of alias
  7498. $endnum = strpos($page, '}', $pos);
  7499. // string to be replaced
  7500. $aa = substr($page, $pos, ($endnum - $pos + 1));
  7501. // get compensation factor
  7502. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  7503. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  7504. $ratio = floatval($ratio);
  7505. if ($type == 'u') {
  7506. $chrdiff = floor(($diff + 12) * $ratio);
  7507. $shift = str_repeat(' ', $chrdiff);
  7508. $shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
  7509. } else {
  7510. $chrdiff = floor(($diff + 11) * $ratio);
  7511. $shift = str_repeat(' ', $chrdiff);
  7512. }
  7513. $page = str_replace($aa, $shift, $page);
  7514. }
  7515. }
  7516. }
  7517. return $page;
  7518. }
  7519. /**
  7520. * Set page boxes to be included on page descriptions.
  7521. * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
  7522. * @protected
  7523. */
  7524. protected function setPageBoxTypes($boxes) {
  7525. $this->page_boxes = array();
  7526. foreach ($boxes as $box) {
  7527. if (in_array($box, TCPDF_STATIC::$pageboxes)) {
  7528. $this->page_boxes[] = $box;
  7529. }
  7530. }
  7531. }
  7532. /**
  7533. * Output pages (and replace page number aliases).
  7534. * @protected
  7535. */
  7536. protected function _putpages() {
  7537. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  7538. // get internal aliases for page numbers
  7539. $pnalias = $this->getAllInternalPageNumberAliases();
  7540. $num_pages = $this->numpages;
  7541. $ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
  7542. $ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
  7543. $ptp_num_chars = $this->GetNumChars($ptpa);
  7544. $pagegroupnum = 0;
  7545. $groupnum = 0;
  7546. $ptgu = 1;
  7547. $ptga = 1;
  7548. $ptg_num_chars = 1;
  7549. for ($n = 1; $n <= $num_pages; ++$n) {
  7550. // get current page
  7551. $temppage = $this->getPageBuffer($n);
  7552. $pagelen = strlen($temppage);
  7553. // set replacements for total pages number
  7554. $pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
  7555. $pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
  7556. $pnp_num_chars = $this->GetNumChars($pnpa);
  7557. $pdiff = 0; // difference used for right shift alignment of page numbers
  7558. $gdiff = 0; // difference used for right shift alignment of page group numbers
  7559. if (!empty($this->pagegroups)) {
  7560. if (isset($this->newpagegroup[$n])) {
  7561. $pagegroupnum = 0;
  7562. ++$groupnum;
  7563. $ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
  7564. $ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
  7565. $ptg_num_chars = $this->GetNumChars($ptga);
  7566. }
  7567. ++$pagegroupnum;
  7568. $pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
  7569. $pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
  7570. $png_num_chars = $this->GetNumChars($pnga);
  7571. // replace page numbers
  7572. $replace = array();
  7573. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  7574. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  7575. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  7576. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  7577. list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
  7578. }
  7579. // replace page numbers
  7580. $replace = array();
  7581. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  7582. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  7583. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  7584. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  7585. list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
  7586. // replace right shift alias
  7587. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  7588. // replace EPS marker
  7589. $temppage = str_replace($this->epsmarker, '', $temppage);
  7590. //Page
  7591. $this->page_obj_id[$n] = $this->_newobj();
  7592. $out = '<<';
  7593. $out .= ' /Type /Page';
  7594. $out .= ' /Parent 1 0 R';
  7595. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  7596. $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
  7597. }
  7598. $out .= ' /Resources 2 0 R';
  7599. foreach ($this->page_boxes as $box) {
  7600. $out .= ' /'.$box;
  7601. $out .= sprintf(' [%F %F %F %F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']);
  7602. }
  7603. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  7604. $out .= ' /BoxColorInfo <<';
  7605. foreach ($this->page_boxes as $box) {
  7606. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  7607. $out .= ' /'.$box.' <<';
  7608. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  7609. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  7610. $out .= ' /C [';
  7611. $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  7612. $out .= ' ]';
  7613. }
  7614. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  7615. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  7616. }
  7617. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  7618. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  7619. }
  7620. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  7621. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  7622. $out .= ' /D [';
  7623. foreach ($dashes as $dash) {
  7624. $out .= sprintf(' %F', ($dash * $this->k));
  7625. }
  7626. $out .= ' ]';
  7627. }
  7628. $out .= ' >>';
  7629. }
  7630. }
  7631. $out .= ' >>';
  7632. }
  7633. $out .= ' /Contents '.($this->n + 1).' 0 R';
  7634. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  7635. if (!$this->pdfa_mode) {
  7636. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  7637. }
  7638. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  7639. // page transitions
  7640. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  7641. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  7642. }
  7643. $out .= ' /Trans <<';
  7644. $out .= ' /Type /Trans';
  7645. if (isset($this->pagedim[$n]['trans']['S'])) {
  7646. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  7647. }
  7648. if (isset($this->pagedim[$n]['trans']['D'])) {
  7649. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  7650. }
  7651. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  7652. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  7653. }
  7654. if (isset($this->pagedim[$n]['trans']['M'])) {
  7655. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  7656. }
  7657. if (isset($this->pagedim[$n]['trans']['Di'])) {
  7658. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  7659. }
  7660. if (isset($this->pagedim[$n]['trans']['SS'])) {
  7661. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  7662. }
  7663. if (isset($this->pagedim[$n]['trans']['B'])) {
  7664. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  7665. }
  7666. $out .= ' >>';
  7667. }
  7668. $out .= $this->_getannotsrefs($n);
  7669. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  7670. $out .= ' >>';
  7671. $out .= "\n".'endobj';
  7672. $this->_out($out);
  7673. //Page content
  7674. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  7675. $this->_newobj();
  7676. $p = $this->_getrawstream($p);
  7677. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  7678. }
  7679. //Pages root
  7680. $out = $this->_getobj(1)."\n";
  7681. $out .= '<< /Type /Pages /Kids [';
  7682. foreach($this->page_obj_id as $page_obj) {
  7683. $out .= ' '.$page_obj.' 0 R';
  7684. }
  7685. $out .= ' ] /Count '.$num_pages.' >>';
  7686. $out .= "\n".'endobj';
  7687. $this->_out($out);
  7688. }
  7689. /**
  7690. * Get references to page annotations.
  7691. * @param $n (int) page number
  7692. * @return string
  7693. * @protected
  7694. * @author Nicola Asuni
  7695. * @since 5.0.010 (2010-05-17)
  7696. */
  7697. protected function _getannotsrefs($n) {
  7698. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  7699. return '';
  7700. }
  7701. $out = ' /Annots [';
  7702. if (isset($this->PageAnnots[$n])) {
  7703. foreach ($this->PageAnnots[$n] as $key => $val) {
  7704. if (!in_array($val['n'], $this->radio_groups)) {
  7705. $out .= ' '.$val['n'].' 0 R';
  7706. }
  7707. }
  7708. // add radiobutton groups
  7709. if (isset($this->radiobutton_groups[$n])) {
  7710. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  7711. if (isset($data['n'])) {
  7712. $out .= ' '.$data['n'].' 0 R';
  7713. }
  7714. }
  7715. }
  7716. }
  7717. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  7718. // set reference for signature object
  7719. $out .= ' '.$this->sig_obj_id.' 0 R';
  7720. }
  7721. if (!empty($this->empty_signature_appearance)) {
  7722. foreach ($this->empty_signature_appearance as $esa) {
  7723. if ($esa['page'] == $n) {
  7724. // set reference for empty signature objects
  7725. $out .= ' '.$esa['objid'].' 0 R';
  7726. }
  7727. }
  7728. }
  7729. $out .= ' ]';
  7730. return $out;
  7731. }
  7732. /**
  7733. * Output annotations objects for all pages.
  7734. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  7735. * See section 12.5 of PDF 32000_2008 reference.
  7736. * @protected
  7737. * @author Nicola Asuni
  7738. * @since 4.0.018 (2008-08-06)
  7739. */
  7740. protected function _putannotsobjs() {
  7741. // reset object counter
  7742. for ($n=1; $n <= $this->numpages; ++$n) {
  7743. if (isset($this->PageAnnots[$n])) {
  7744. // set page annotations
  7745. foreach ($this->PageAnnots[$n] as $key => $pl) {
  7746. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  7747. // create annotation object for grouping radiobuttons
  7748. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  7749. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  7750. $annots = '<<';
  7751. $annots .= ' /Type /Annot';
  7752. $annots .= ' /Subtype /Widget';
  7753. $annots .= ' /Rect [0 0 0 0]';
  7754. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  7755. // read only
  7756. $annots .= ' /F 68';
  7757. $annots .= ' /Ff 49153';
  7758. } else {
  7759. $annots .= ' /F 4'; // default print for PDF/A
  7760. $annots .= ' /Ff 49152';
  7761. }
  7762. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  7763. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  7764. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
  7765. }
  7766. $annots .= ' /FT /Btn';
  7767. $annots .= ' /Kids [';
  7768. $defval = '';
  7769. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  7770. if (isset($data['kid'])) {
  7771. $annots .= ' '.$data['kid'].' 0 R';
  7772. if ($data['def'] !== 'Off') {
  7773. $defval = $data['def'];
  7774. }
  7775. }
  7776. }
  7777. $annots .= ' ]';
  7778. if (!empty($defval)) {
  7779. $annots .= ' /V /'.$defval;
  7780. }
  7781. $annots .= ' >>';
  7782. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  7783. $this->form_obj_id[] = $radio_button_obj_id;
  7784. // store object id to be used on Parent entry of Kids
  7785. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  7786. }
  7787. $formfield = false;
  7788. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  7789. $a = $pl['x'] * $this->k;
  7790. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  7791. $c = $pl['w'] * $this->k;
  7792. $d = $pl['h'] * $this->k;
  7793. $rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
  7794. // create new annotation object
  7795. $annots = '<</Type /Annot';
  7796. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  7797. $annots .= ' /Rect ['.$rect.']';
  7798. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  7799. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  7800. $annots .= ' /FT /'.$pl['opt']['ft'];
  7801. $formfield = true;
  7802. }
  7803. if ($pl['opt']['subtype'] !== 'Link') {
  7804. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  7805. }
  7806. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  7807. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  7808. $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
  7809. if (isset($pl['opt']['f'])) {
  7810. $fval = 0;
  7811. if (is_array($pl['opt']['f'])) {
  7812. foreach ($pl['opt']['f'] as $f) {
  7813. switch (strtolower($f)) {
  7814. case 'invisible': {
  7815. $fval += 1 << 0;
  7816. break;
  7817. }
  7818. case 'hidden': {
  7819. $fval += 1 << 1;
  7820. break;
  7821. }
  7822. case 'print': {
  7823. $fval += 1 << 2;
  7824. break;
  7825. }
  7826. case 'nozoom': {
  7827. $fval += 1 << 3;
  7828. break;
  7829. }
  7830. case 'norotate': {
  7831. $fval += 1 << 4;
  7832. break;
  7833. }
  7834. case 'noview': {
  7835. $fval += 1 << 5;
  7836. break;
  7837. }
  7838. case 'readonly': {
  7839. $fval += 1 << 6;
  7840. break;
  7841. }
  7842. case 'locked': {
  7843. $fval += 1 << 8;
  7844. break;
  7845. }
  7846. case 'togglenoview': {
  7847. $fval += 1 << 9;
  7848. break;
  7849. }
  7850. case 'lockedcontents': {
  7851. $fval += 1 << 10;
  7852. break;
  7853. }
  7854. default: {
  7855. break;
  7856. }
  7857. }
  7858. }
  7859. } else {
  7860. $fval = intval($pl['opt']['f']);
  7861. }
  7862. } else {
  7863. $fval = 4;
  7864. }
  7865. if ($this->pdfa_mode) {
  7866. // force print flag for PDF/A mode
  7867. $fval |= 4;
  7868. }
  7869. $annots .= ' /F '.intval($fval);
  7870. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  7871. $annots .= ' /AS /'.$pl['opt']['as'];
  7872. }
  7873. if (isset($pl['opt']['ap'])) {
  7874. // appearance stream
  7875. $annots .= ' /AP <<';
  7876. if (is_array($pl['opt']['ap'])) {
  7877. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  7878. // $apmode can be: n = normal; r = rollover; d = down;
  7879. $annots .= ' /'.strtoupper($apmode);
  7880. if (is_array($apdef)) {
  7881. $annots .= ' <<';
  7882. foreach ($apdef as $apstate => $stream) {
  7883. // reference to XObject that define the appearance for this mode-state
  7884. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  7885. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  7886. }
  7887. $annots .= ' >>';
  7888. } else {
  7889. // reference to XObject that define the appearance for this mode
  7890. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  7891. $annots .= ' '.$apsobjid.' 0 R';
  7892. }
  7893. }
  7894. } else {
  7895. $annots .= $pl['opt']['ap'];
  7896. }
  7897. $annots .= ' >>';
  7898. }
  7899. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  7900. $annots .= ' /BS <<';
  7901. $annots .= ' /Type /Border';
  7902. if (isset($pl['opt']['bs']['w'])) {
  7903. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  7904. }
  7905. $bstyles = array('S', 'D', 'B', 'I', 'U');
  7906. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  7907. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7908. }
  7909. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  7910. $annots .= ' /D [';
  7911. foreach ($pl['opt']['bs']['d'] as $cord) {
  7912. $annots .= ' '.intval($cord);
  7913. }
  7914. $annots .= ']';
  7915. }
  7916. $annots .= ' >>';
  7917. } else {
  7918. $annots .= ' /Border [';
  7919. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  7920. $annots .= intval($pl['opt']['border'][0]).' ';
  7921. $annots .= intval($pl['opt']['border'][1]).' ';
  7922. $annots .= intval($pl['opt']['border'][2]);
  7923. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  7924. $annots .= ' [';
  7925. foreach ($pl['opt']['border'][3] as $dash) {
  7926. $annots .= intval($dash).' ';
  7927. }
  7928. $annots .= ']';
  7929. }
  7930. } else {
  7931. $annots .= '0 0 0';
  7932. }
  7933. $annots .= ']';
  7934. }
  7935. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  7936. $annots .= ' /BE <<';
  7937. $bstyles = array('S', 'C');
  7938. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
  7939. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7940. } else {
  7941. $annots .= ' /S /S';
  7942. }
  7943. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  7944. $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
  7945. }
  7946. $annots .= '>>';
  7947. }
  7948. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  7949. $annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
  7950. }
  7951. //$annots .= ' /StructParent ';
  7952. //$annots .= ' /OC ';
  7953. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  7954. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  7955. // this is a markup type
  7956. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  7957. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  7958. }
  7959. //$annots .= ' /Popup ';
  7960. if (isset($pl['opt']['ca'])) {
  7961. $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
  7962. }
  7963. if (isset($pl['opt']['rc'])) {
  7964. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  7965. }
  7966. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
  7967. //$annots .= ' /IRT ';
  7968. if (isset($pl['opt']['subj'])) {
  7969. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  7970. }
  7971. //$annots .= ' /RT ';
  7972. //$annots .= ' /IT ';
  7973. //$annots .= ' /ExData ';
  7974. }
  7975. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  7976. // Annotation types
  7977. switch (strtolower($pl['opt']['subtype'])) {
  7978. case 'text': {
  7979. if (isset($pl['opt']['open'])) {
  7980. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  7981. }
  7982. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  7983. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  7984. $annots .= ' /Name /'.$pl['opt']['name'];
  7985. } else {
  7986. $annots .= ' /Name /Note';
  7987. }
  7988. $statemodels = array('Marked', 'Review');
  7989. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  7990. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  7991. } else {
  7992. $pl['opt']['statemodel'] = 'Marked';
  7993. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  7994. }
  7995. if ($pl['opt']['statemodel'] == 'Marked') {
  7996. $states = array('Accepted', 'Unmarked');
  7997. } else {
  7998. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  7999. }
  8000. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  8001. $annots .= ' /State /'.$pl['opt']['state'];
  8002. } else {
  8003. if ($pl['opt']['statemodel'] == 'Marked') {
  8004. $annots .= ' /State /Unmarked';
  8005. } else {
  8006. $annots .= ' /State /None';
  8007. }
  8008. }
  8009. break;
  8010. }
  8011. case 'link': {
  8012. if (is_string($pl['txt']) && !empty($pl['txt'])) {
  8013. if ($pl['txt'][0] == '#') {
  8014. // internal destination
  8015. $annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
  8016. } elseif ($pl['txt'][0] == '%') {
  8017. // embedded PDF file
  8018. $filename = basename(substr($pl['txt'], 1));
  8019. $annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  8020. } elseif ($pl['txt'][0] == '*') {
  8021. // embedded generic file
  8022. $filename = basename(substr($pl['txt'], 1));
  8023. $jsa = 'var D=event.target.doc;var MyData=D.dataObjects;for (var i in MyData) if (MyData[i].path=="'.$filename.'") D.exportDataObject( { cName : MyData[i].name, nLaunch : 2});';
  8024. $annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
  8025. } else {
  8026. $parsedUrl = parse_url($pl['txt']);
  8027. if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
  8028. // relative link to a PDF file
  8029. $dest = '[0 /Fit]'; // default page 0
  8030. if (!empty($parsedUrl['fragment'])) {
  8031. // check for named destination
  8032. $tmp = explode('=', $parsedUrl['fragment']);
  8033. $dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
  8034. }
  8035. $annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
  8036. } else {
  8037. // external URI link
  8038. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  8039. }
  8040. }
  8041. } elseif (isset($this->links[$pl['txt']])) {
  8042. // internal link ID
  8043. $l = $this->links[$pl['txt']];
  8044. if (isset($this->page_obj_id[($l['p'])])) {
  8045. $annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l['p'])], ($this->pagedim[$l['p']]['h'] - ($l['y'] * $this->k)));
  8046. }
  8047. }
  8048. $hmodes = array('N', 'I', 'O', 'P');
  8049. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  8050. $annots .= ' /H /'.$pl['opt']['h'];
  8051. } else {
  8052. $annots .= ' /H /I';
  8053. }
  8054. //$annots .= ' /PA ';
  8055. //$annots .= ' /Quadpoints ';
  8056. break;
  8057. }
  8058. case 'freetext': {
  8059. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8060. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8061. }
  8062. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8063. $annots .= ' /Q '.intval($pl['opt']['q']);
  8064. }
  8065. if (isset($pl['opt']['rc'])) {
  8066. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8067. }
  8068. if (isset($pl['opt']['ds'])) {
  8069. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  8070. }
  8071. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  8072. $annots .= ' /CL [';
  8073. foreach ($pl['opt']['cl'] as $cl) {
  8074. $annots .= sprintf('%F ', $cl * $this->k);
  8075. }
  8076. $annots .= ']';
  8077. }
  8078. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  8079. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  8080. $annots .= ' /IT /'.$pl['opt']['it'];
  8081. }
  8082. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  8083. $l = $pl['opt']['rd'][0] * $this->k;
  8084. $r = $pl['opt']['rd'][1] * $this->k;
  8085. $t = $pl['opt']['rd'][2] * $this->k;
  8086. $b = $pl['opt']['rd'][3] * $this->k;
  8087. $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
  8088. }
  8089. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  8090. $annots .= ' /LE /'.$pl['opt']['le'];
  8091. }
  8092. break;
  8093. }
  8094. case 'line': {
  8095. break;
  8096. }
  8097. case 'square': {
  8098. break;
  8099. }
  8100. case 'circle': {
  8101. break;
  8102. }
  8103. case 'polygon': {
  8104. break;
  8105. }
  8106. case 'polyline': {
  8107. break;
  8108. }
  8109. case 'highlight': {
  8110. break;
  8111. }
  8112. case 'underline': {
  8113. break;
  8114. }
  8115. case 'squiggly': {
  8116. break;
  8117. }
  8118. case 'strikeout': {
  8119. break;
  8120. }
  8121. case 'stamp': {
  8122. break;
  8123. }
  8124. case 'caret': {
  8125. break;
  8126. }
  8127. case 'ink': {
  8128. break;
  8129. }
  8130. case 'popup': {
  8131. break;
  8132. }
  8133. case 'fileattachment': {
  8134. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  8135. // embedded files are not allowed in PDF/A mode version 1 and 2
  8136. break;
  8137. }
  8138. if (!isset($pl['opt']['fs'])) {
  8139. break;
  8140. }
  8141. $filename = basename($pl['opt']['fs']);
  8142. if (isset($this->embeddedfiles[$filename]['f'])) {
  8143. $annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8144. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  8145. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8146. $annots .= ' /Name /'.$pl['opt']['name'];
  8147. } else {
  8148. $annots .= ' /Name /PushPin';
  8149. }
  8150. // index (zero-based) of the annotation in the Annots array of this page
  8151. $this->embeddedfiles[$filename]['a'] = $key;
  8152. }
  8153. break;
  8154. }
  8155. case 'sound': {
  8156. if (!isset($pl['opt']['fs'])) {
  8157. break;
  8158. }
  8159. $filename = basename($pl['opt']['fs']);
  8160. if (isset($this->embeddedfiles[$filename]['f'])) {
  8161. // ... TO BE COMPLETED ...
  8162. // /R /C /B /E /CO /CP
  8163. $annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8164. $iconsapp = array('Speaker', 'Mic');
  8165. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8166. $annots .= ' /Name /'.$pl['opt']['name'];
  8167. } else {
  8168. $annots .= ' /Name /Speaker';
  8169. }
  8170. }
  8171. break;
  8172. }
  8173. case 'movie': {
  8174. break;
  8175. }
  8176. case 'widget': {
  8177. $hmode = array('N', 'I', 'O', 'P', 'T');
  8178. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  8179. $annots .= ' /H /'.$pl['opt']['h'];
  8180. }
  8181. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  8182. $annots .= ' /MK <<';
  8183. if (isset($pl['opt']['mk']['r'])) {
  8184. $annots .= ' /R '.$pl['opt']['mk']['r'];
  8185. }
  8186. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  8187. $annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
  8188. }
  8189. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  8190. $annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
  8191. }
  8192. if (isset($pl['opt']['mk']['ca'])) {
  8193. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  8194. }
  8195. if (isset($pl['opt']['mk']['rc'])) {
  8196. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  8197. }
  8198. if (isset($pl['opt']['mk']['ac'])) {
  8199. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  8200. }
  8201. if (isset($pl['opt']['mk']['i'])) {
  8202. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  8203. if ($info !== false) {
  8204. $annots .= ' /I '.$info['n'].' 0 R';
  8205. }
  8206. }
  8207. if (isset($pl['opt']['mk']['ri'])) {
  8208. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  8209. if ($info !== false) {
  8210. $annots .= ' /RI '.$info['n'].' 0 R';
  8211. }
  8212. }
  8213. if (isset($pl['opt']['mk']['ix'])) {
  8214. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  8215. if ($info !== false) {
  8216. $annots .= ' /IX '.$info['n'].' 0 R';
  8217. }
  8218. }
  8219. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  8220. $annots .= ' /IF <<';
  8221. $if_sw = array('A', 'B', 'S', 'N');
  8222. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  8223. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  8224. }
  8225. $if_s = array('A', 'P');
  8226. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  8227. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  8228. }
  8229. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  8230. $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  8231. }
  8232. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  8233. $annots .= ' /FB true';
  8234. }
  8235. $annots .= '>>';
  8236. }
  8237. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  8238. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  8239. }
  8240. $annots .= '>>';
  8241. } // end MK
  8242. // --- Entries for field dictionaries ---
  8243. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8244. // set parent
  8245. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  8246. }
  8247. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  8248. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  8249. }
  8250. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  8251. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  8252. }
  8253. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  8254. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  8255. }
  8256. if (isset($pl['opt']['ff'])) {
  8257. if (is_array($pl['opt']['ff'])) {
  8258. // array of bit settings
  8259. $flag = 0;
  8260. foreach($pl['opt']['ff'] as $val) {
  8261. $flag += 1 << ($val - 1);
  8262. }
  8263. } else {
  8264. $flag = intval($pl['opt']['ff']);
  8265. }
  8266. $annots .= ' /Ff '.$flag;
  8267. }
  8268. if (isset($pl['opt']['maxlen'])) {
  8269. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  8270. }
  8271. if (isset($pl['opt']['v'])) {
  8272. $annots .= ' /V';
  8273. if (is_array($pl['opt']['v'])) {
  8274. foreach ($pl['opt']['v'] AS $optval) {
  8275. if (is_float($optval)) {
  8276. $optval = sprintf('%F', $optval);
  8277. }
  8278. $annots .= ' '.$optval;
  8279. }
  8280. } else {
  8281. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  8282. }
  8283. }
  8284. if (isset($pl['opt']['dv'])) {
  8285. $annots .= ' /DV';
  8286. if (is_array($pl['opt']['dv'])) {
  8287. foreach ($pl['opt']['dv'] AS $optval) {
  8288. if (is_float($optval)) {
  8289. $optval = sprintf('%F', $optval);
  8290. }
  8291. $annots .= ' '.$optval;
  8292. }
  8293. } else {
  8294. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  8295. }
  8296. }
  8297. if (isset($pl['opt']['rv'])) {
  8298. $annots .= ' /RV';
  8299. if (is_array($pl['opt']['rv'])) {
  8300. foreach ($pl['opt']['rv'] AS $optval) {
  8301. if (is_float($optval)) {
  8302. $optval = sprintf('%F', $optval);
  8303. }
  8304. $annots .= ' '.$optval;
  8305. }
  8306. } else {
  8307. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  8308. }
  8309. }
  8310. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  8311. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  8312. }
  8313. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  8314. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  8315. }
  8316. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8317. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8318. }
  8319. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8320. $annots .= ' /Q '.intval($pl['opt']['q']);
  8321. }
  8322. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  8323. $annots .= ' /Opt [';
  8324. foreach($pl['opt']['opt'] AS $copt) {
  8325. if (is_array($copt)) {
  8326. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  8327. } else {
  8328. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  8329. }
  8330. }
  8331. $annots .= ']';
  8332. }
  8333. if (isset($pl['opt']['ti'])) {
  8334. $annots .= ' /TI '.intval($pl['opt']['ti']);
  8335. }
  8336. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  8337. $annots .= ' /I [';
  8338. foreach($pl['opt']['i'] AS $copt) {
  8339. $annots .= intval($copt).' ';
  8340. }
  8341. $annots .= ']';
  8342. }
  8343. break;
  8344. }
  8345. case 'screen': {
  8346. break;
  8347. }
  8348. case 'printermark': {
  8349. break;
  8350. }
  8351. case 'trapnet': {
  8352. break;
  8353. }
  8354. case 'watermark': {
  8355. break;
  8356. }
  8357. case '3d': {
  8358. break;
  8359. }
  8360. default: {
  8361. break;
  8362. }
  8363. }
  8364. $annots .= '>>';
  8365. // create new annotation object
  8366. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  8367. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8368. // store reference of form object
  8369. $this->form_obj_id[] = $annot_obj_id;
  8370. }
  8371. }
  8372. }
  8373. } // end for each page
  8374. }
  8375. /**
  8376. * Put appearance streams XObject used to define annotation's appearance states.
  8377. * @param $w (int) annotation width
  8378. * @param $h (int) annotation height
  8379. * @param $stream (string) appearance stream
  8380. * @return int object ID
  8381. * @protected
  8382. * @since 4.8.001 (2009-09-09)
  8383. */
  8384. protected function _putAPXObject($w=0, $h=0, $stream='') {
  8385. $stream = trim($stream);
  8386. $out = $this->_getobj()."\n";
  8387. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  8388. $out .= '<<';
  8389. $out .= ' /Type /XObject';
  8390. $out .= ' /Subtype /Form';
  8391. $out .= ' /FormType 1';
  8392. if ($this->compress) {
  8393. $stream = gzcompress($stream);
  8394. $out .= ' /Filter /FlateDecode';
  8395. }
  8396. $rect = sprintf('%F %F', $w, $h);
  8397. $out .= ' /BBox [0 0 '.$rect.']';
  8398. $out .= ' /Matrix [1 0 0 1 0 0]';
  8399. $out .= ' /Resources 2 0 R';
  8400. $stream = $this->_getrawstream($stream);
  8401. $out .= ' /Length '.strlen($stream);
  8402. $out .= ' >>';
  8403. $out .= ' stream'."\n".$stream."\n".'endstream';
  8404. $out .= "\n".'endobj';
  8405. $this->_out($out);
  8406. return $this->n;
  8407. }
  8408. /**
  8409. * Output fonts.
  8410. * @author Nicola Asuni
  8411. * @protected
  8412. */
  8413. protected function _putfonts() {
  8414. $nf = $this->n;
  8415. foreach ($this->diffs as $diff) {
  8416. //Encodings
  8417. $this->_newobj();
  8418. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  8419. }
  8420. $mqr = TCPDF_STATIC::get_mqr();
  8421. TCPDF_STATIC::set_mqr(false);
  8422. foreach ($this->FontFiles as $file => $info) {
  8423. // search and get font file to embedd
  8424. $fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
  8425. if (!TCPDF_STATIC::empty_string($fontfile)) {
  8426. $font = file_get_contents($fontfile);
  8427. $compressed = (substr($file, -2) == '.z');
  8428. if ((!$compressed) AND (isset($info['length2']))) {
  8429. $header = (ord($font[0]) == 128);
  8430. if ($header) {
  8431. // strip first binary header
  8432. $font = substr($font, 6);
  8433. }
  8434. if ($header AND (ord($font[$info['length1']]) == 128)) {
  8435. // strip second binary header
  8436. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  8437. }
  8438. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  8439. if ($compressed) {
  8440. // uncompress font
  8441. $font = gzuncompress($font);
  8442. }
  8443. // merge subset characters
  8444. $subsetchars = array(); // used chars
  8445. foreach ($info['fontkeys'] as $fontkey) {
  8446. $fontinfo = $this->getFontBuffer($fontkey);
  8447. $subsetchars += $fontinfo['subsetchars'];
  8448. }
  8449. // rebuild a font subset
  8450. $font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
  8451. // calculate new font length
  8452. $info['length1'] = strlen($font);
  8453. if ($compressed) {
  8454. // recompress font
  8455. $font = gzcompress($font);
  8456. }
  8457. }
  8458. $this->_newobj();
  8459. $this->FontFiles[$file]['n'] = $this->n;
  8460. $stream = $this->_getrawstream($font);
  8461. $out = '<< /Length '.strlen($stream);
  8462. if ($compressed) {
  8463. $out .= ' /Filter /FlateDecode';
  8464. }
  8465. $out .= ' /Length1 '.$info['length1'];
  8466. if (isset($info['length2'])) {
  8467. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  8468. }
  8469. $out .= ' >>';
  8470. $out .= ' stream'."\n".$stream."\n".'endstream';
  8471. $out .= "\n".'endobj';
  8472. $this->_out($out);
  8473. }
  8474. }
  8475. TCPDF_STATIC::set_mqr($mqr);
  8476. foreach ($this->fontkeys as $k) {
  8477. //Font objects
  8478. $font = $this->getFontBuffer($k);
  8479. $type = $font['type'];
  8480. $name = $font['name'];
  8481. if ($type == 'core') {
  8482. // standard core font
  8483. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8484. $out .= '<</Type /Font';
  8485. $out .= ' /Subtype /Type1';
  8486. $out .= ' /BaseFont /'.$name;
  8487. $out .= ' /Name /F'.$font['i'];
  8488. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  8489. $out .= ' /Encoding /WinAnsiEncoding';
  8490. }
  8491. if ($k == 'helvetica') {
  8492. // add default font for annotations
  8493. $this->annotation_fonts[$k] = $font['i'];
  8494. }
  8495. $out .= ' >>';
  8496. $out .= "\n".'endobj';
  8497. $this->_out($out);
  8498. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  8499. // additional Type1 or TrueType font
  8500. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8501. $out .= '<</Type /Font';
  8502. $out .= ' /Subtype /'.$type;
  8503. $out .= ' /BaseFont /'.$name;
  8504. $out .= ' /Name /F'.$font['i'];
  8505. $out .= ' /FirstChar 32 /LastChar 255';
  8506. $out .= ' /Widths '.($this->n + 1).' 0 R';
  8507. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  8508. if ($font['enc']) {
  8509. if (isset($font['diff'])) {
  8510. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  8511. } else {
  8512. $out .= ' /Encoding /WinAnsiEncoding';
  8513. }
  8514. }
  8515. $out .= ' >>';
  8516. $out .= "\n".'endobj';
  8517. $this->_out($out);
  8518. // Widths
  8519. $this->_newobj();
  8520. $s = '[';
  8521. for ($i = 32; $i < 256; ++$i) {
  8522. if (isset($font['cw'][$i])) {
  8523. $s .= $font['cw'][$i].' ';
  8524. } else {
  8525. $s .= $font['dw'].' ';
  8526. }
  8527. }
  8528. $s .= ']';
  8529. $s .= "\n".'endobj';
  8530. $this->_out($s);
  8531. //Descriptor
  8532. $this->_newobj();
  8533. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8534. foreach ($font['desc'] as $fdk => $fdv) {
  8535. if (is_float($fdv)) {
  8536. $fdv = sprintf('%F', $fdv);
  8537. }
  8538. $s .= ' /'.$fdk.' '.$fdv.'';
  8539. }
  8540. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8541. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8542. }
  8543. $s .= '>>';
  8544. $s .= "\n".'endobj';
  8545. $this->_out($s);
  8546. } else {
  8547. // additional types
  8548. $mtd = '_put'.strtolower($type);
  8549. if (!method_exists($this, $mtd)) {
  8550. $this->Error('Unsupported font type: '.$type);
  8551. }
  8552. $this->$mtd($font);
  8553. }
  8554. }
  8555. }
  8556. /**
  8557. * Adds unicode fonts.<br>
  8558. * Based on PDF Reference 1.3 (section 5)
  8559. * @param $font (array) font data
  8560. * @protected
  8561. * @author Nicola Asuni
  8562. * @since 1.52.0.TC005 (2005-01-05)
  8563. */
  8564. protected function _puttruetypeunicode($font) {
  8565. $fontname = '';
  8566. if ($font['subset']) {
  8567. // change name for font subsetting
  8568. $subtag = sprintf('%06u', $font['i']);
  8569. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  8570. $fontname .= $subtag.'+';
  8571. }
  8572. $fontname .= $font['name'];
  8573. // Type0 Font
  8574. // A composite font composed of other fonts, organized hierarchically
  8575. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8576. $out .= '<< /Type /Font';
  8577. $out .= ' /Subtype /Type0';
  8578. $out .= ' /BaseFont /'.$fontname;
  8579. $out .= ' /Name /F'.$font['i'];
  8580. $out .= ' /Encoding /'.$font['enc'];
  8581. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  8582. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  8583. $out .= ' >>';
  8584. $out .= "\n".'endobj';
  8585. $this->_out($out);
  8586. // ToUnicode map for Identity-H
  8587. $stream = TCPDF_FONT_DATA::$uni_identity_h;
  8588. // ToUnicode Object
  8589. $this->_newobj();
  8590. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  8591. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8592. $stream = $this->_getrawstream($stream);
  8593. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  8594. // CIDFontType2
  8595. // A CIDFont whose glyph descriptions are based on TrueType font technology
  8596. $oid = $this->_newobj();
  8597. $out = '<< /Type /Font';
  8598. $out .= ' /Subtype /CIDFontType2';
  8599. $out .= ' /BaseFont /'.$fontname;
  8600. // A dictionary containing entries that define the character collection of the CIDFont.
  8601. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8602. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8603. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8604. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  8605. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8606. $out .= ' /DW '.$font['dw']; // default width
  8607. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
  8608. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8609. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  8610. }
  8611. $out .= ' >>';
  8612. $out .= "\n".'endobj';
  8613. $this->_out($out);
  8614. // Font descriptor
  8615. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  8616. $this->_newobj();
  8617. $out = '<< /Type /FontDescriptor';
  8618. $out .= ' /FontName /'.$fontname;
  8619. foreach ($font['desc'] as $key => $value) {
  8620. if (is_float($value)) {
  8621. $value = sprintf('%F', $value);
  8622. }
  8623. $out .= ' /'.$key.' '.$value;
  8624. }
  8625. $fontdir = false;
  8626. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8627. // A stream containing a TrueType font
  8628. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8629. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  8630. }
  8631. $out .= ' >>';
  8632. $out .= "\n".'endobj';
  8633. $this->_out($out);
  8634. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8635. $this->_newobj();
  8636. // Embed CIDToGIDMap
  8637. // A specification of the mapping from CIDs to glyph indices
  8638. // search and get CTG font file to embedd
  8639. $ctgfile = strtolower($font['ctg']);
  8640. // search and get ctg font file to embedd
  8641. $fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
  8642. if (TCPDF_STATIC::empty_string($fontfile)) {
  8643. $this->Error('Font file not found: '.$ctgfile);
  8644. }
  8645. $stream = $this->_getrawstream(file_get_contents($fontfile));
  8646. $out = '<< /Length '.strlen($stream).'';
  8647. if (substr($fontfile, -2) == '.z') { // check file extension
  8648. // Decompresses data encoded using the public-domain
  8649. // zlib/deflate compression method, reproducing the
  8650. // original text or binary data
  8651. $out .= ' /Filter /FlateDecode';
  8652. }
  8653. $out .= ' >>';
  8654. $out .= ' stream'."\n".$stream."\n".'endstream';
  8655. $out .= "\n".'endobj';
  8656. $this->_out($out);
  8657. }
  8658. }
  8659. /**
  8660. * Output CID-0 fonts.
  8661. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  8662. * @param $font (array) font data
  8663. * @protected
  8664. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  8665. * @since 3.2.000 (2008-06-23)
  8666. */
  8667. protected function _putcidfont0($font) {
  8668. $cidoffset = 0;
  8669. if (!isset($font['cw'][1])) {
  8670. $cidoffset = 31;
  8671. }
  8672. if (isset($font['cidinfo']['uni2cid'])) {
  8673. // convert unicode to cid.
  8674. $uni2cid = $font['cidinfo']['uni2cid'];
  8675. $cw = array();
  8676. foreach ($font['cw'] as $uni => $width) {
  8677. if (isset($uni2cid[$uni])) {
  8678. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  8679. } elseif ($uni < 256) {
  8680. $cw[$uni] = $width;
  8681. } // else unknown character
  8682. }
  8683. $font = array_merge($font, array('cw' => $cw));
  8684. }
  8685. $name = $font['name'];
  8686. $enc = $font['enc'];
  8687. if ($enc) {
  8688. $longname = $name.'-'.$enc;
  8689. } else {
  8690. $longname = $name;
  8691. }
  8692. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8693. $out .= '<</Type /Font';
  8694. $out .= ' /Subtype /Type0';
  8695. $out .= ' /BaseFont /'.$longname;
  8696. $out .= ' /Name /F'.$font['i'];
  8697. if ($enc) {
  8698. $out .= ' /Encoding /'.$enc;
  8699. }
  8700. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  8701. $out .= ' >>';
  8702. $out .= "\n".'endobj';
  8703. $this->_out($out);
  8704. $oid = $this->_newobj();
  8705. $out = '<</Type /Font';
  8706. $out .= ' /Subtype /CIDFontType0';
  8707. $out .= ' /BaseFont /'.$name;
  8708. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8709. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8710. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8711. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  8712. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8713. $out .= ' /DW '.$font['dw'];
  8714. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
  8715. $out .= ' >>';
  8716. $out .= "\n".'endobj';
  8717. $this->_out($out);
  8718. $this->_newobj();
  8719. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8720. foreach ($font['desc'] as $k => $v) {
  8721. if ($k != 'Style') {
  8722. if (is_float($v)) {
  8723. $v = sprintf('%F', $v);
  8724. }
  8725. $s .= ' /'.$k.' '.$v.'';
  8726. }
  8727. }
  8728. $s .= '>>';
  8729. $s .= "\n".'endobj';
  8730. $this->_out($s);
  8731. }
  8732. /**
  8733. * Output images.
  8734. * @protected
  8735. */
  8736. protected function _putimages() {
  8737. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8738. foreach ($this->imagekeys as $file) {
  8739. $info = $this->getImageBuffer($file);
  8740. // set object for alternate images array
  8741. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  8742. $altoid = $this->_newobj();
  8743. $out = '[';
  8744. foreach ($info['altimgs'] as $altimage) {
  8745. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  8746. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  8747. $out .= ' /DefaultForPrinting';
  8748. if ($altimage[1] === true) {
  8749. $out .= ' true';
  8750. } else {
  8751. $out .= ' false';
  8752. }
  8753. $out .= ' >>';
  8754. }
  8755. }
  8756. $out .= ' ]';
  8757. $out .= "\n".'endobj';
  8758. $this->_out($out);
  8759. }
  8760. // set image object
  8761. $oid = $this->_newobj();
  8762. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  8763. $this->setImageSubBuffer($file, 'n', $this->n);
  8764. $out = '<</Type /XObject';
  8765. $out .= ' /Subtype /Image';
  8766. $out .= ' /Width '.$info['w'];
  8767. $out .= ' /Height '.$info['h'];
  8768. if (array_key_exists('masked', $info)) {
  8769. $out .= ' /SMask '.($this->n - 1).' 0 R';
  8770. }
  8771. // set color space
  8772. $icc = false;
  8773. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  8774. // ICC Colour Space
  8775. $icc = true;
  8776. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  8777. } elseif ($info['cs'] == 'Indexed') {
  8778. // Indexed Colour Space
  8779. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  8780. } else {
  8781. // Device Colour Space
  8782. $out .= ' /ColorSpace /'.$info['cs'];
  8783. }
  8784. if ($info['cs'] == 'DeviceCMYK') {
  8785. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  8786. }
  8787. $out .= ' /BitsPerComponent '.$info['bpc'];
  8788. if (isset($altoid) AND ($altoid > 0)) {
  8789. // reference to alternate images dictionary
  8790. $out .= ' /Alternates '.$altoid.' 0 R';
  8791. }
  8792. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  8793. // external stream
  8794. $out .= ' /Length 0';
  8795. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  8796. if (isset($info['f'])) {
  8797. $out .= ' /FFilter /'.$info['f'];
  8798. }
  8799. $out .= ' >>';
  8800. $out .= ' stream'."\n".'endstream';
  8801. } else {
  8802. if (isset($info['f'])) {
  8803. $out .= ' /Filter /'.$info['f'];
  8804. }
  8805. if (isset($info['parms'])) {
  8806. $out .= ' '.$info['parms'];
  8807. }
  8808. if (isset($info['trns']) AND is_array($info['trns'])) {
  8809. $trns = '';
  8810. $count_info = count($info['trns']);
  8811. if ($info['cs'] == 'Indexed') {
  8812. $maxval =(pow(2, $info['bpc']) - 1);
  8813. for ($i = 0; $i < $count_info; ++$i) {
  8814. if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
  8815. // this is not a binary type mask @TODO: create a SMask
  8816. $trns = '';
  8817. break;
  8818. } elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
  8819. // store the first fully transparent value
  8820. $trns .= $i.' '.$i.' ';
  8821. }
  8822. }
  8823. } else {
  8824. // grayscale or RGB
  8825. for ($i = 0; $i < $count_info; ++$i) {
  8826. if ($info['trns'][$i] == 0) {
  8827. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  8828. }
  8829. }
  8830. }
  8831. // Colour Key Masking
  8832. if (!empty($trns)) {
  8833. $out .= ' /Mask ['.$trns.']';
  8834. }
  8835. }
  8836. $stream = $this->_getrawstream($info['data']);
  8837. $out .= ' /Length '.strlen($stream).' >>';
  8838. $out .= ' stream'."\n".$stream."\n".'endstream';
  8839. }
  8840. $out .= "\n".'endobj';
  8841. $this->_out($out);
  8842. if ($icc) {
  8843. // ICC colour profile
  8844. $this->_newobj();
  8845. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  8846. $icc = $this->_getrawstream($icc);
  8847. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  8848. } elseif ($info['cs'] == 'Indexed') {
  8849. // colour palette
  8850. $this->_newobj();
  8851. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  8852. $pal = $this->_getrawstream($pal);
  8853. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  8854. }
  8855. }
  8856. }
  8857. /**
  8858. * Output Form XObjects Templates.
  8859. * @author Nicola Asuni
  8860. * @since 5.8.017 (2010-08-24)
  8861. * @protected
  8862. * @see startTemplate(), endTemplate(), printTemplate()
  8863. */
  8864. protected function _putxobjects() {
  8865. foreach ($this->xobjects as $key => $data) {
  8866. if (isset($data['outdata'])) {
  8867. $stream = str_replace($this->epsmarker, '', trim($data['outdata']));
  8868. $out = $this->_getobj($data['n'])."\n";
  8869. $out .= '<<';
  8870. $out .= ' /Type /XObject';
  8871. $out .= ' /Subtype /Form';
  8872. $out .= ' /FormType 1';
  8873. if ($this->compress) {
  8874. $stream = gzcompress($stream);
  8875. $out .= ' /Filter /FlateDecode';
  8876. }
  8877. $out .= sprintf(' /BBox [%F %F %F %F]', ($data['x'] * $this->k), (-$data['y'] * $this->k), (($data['w'] + $data['x']) * $this->k), (($data['h'] - $data['y']) * $this->k));
  8878. $out .= ' /Matrix [1 0 0 1 0 0]';
  8879. $out .= ' /Resources <<';
  8880. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8881. if (!$this->pdfa_mode) {
  8882. // transparency
  8883. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  8884. $out .= ' /ExtGState <<';
  8885. foreach ($data['extgstates'] as $k => $extgstate) {
  8886. if (isset($this->extgstates[$k]['name'])) {
  8887. $out .= ' /'.$this->extgstates[$k]['name'];
  8888. } else {
  8889. $out .= ' /GS'.$k;
  8890. }
  8891. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  8892. }
  8893. $out .= ' >>';
  8894. }
  8895. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  8896. $gp = '';
  8897. $gs = '';
  8898. foreach ($data['gradients'] as $id => $grad) {
  8899. // gradient patterns
  8900. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  8901. // gradient shadings
  8902. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  8903. }
  8904. $out .= ' /Pattern <<'.$gp.' >>';
  8905. $out .= ' /Shading <<'.$gs.' >>';
  8906. }
  8907. }
  8908. // spot colors
  8909. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  8910. $out .= ' /ColorSpace <<';
  8911. foreach ($data['spot_colors'] as $name => $color) {
  8912. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  8913. }
  8914. $out .= ' >>';
  8915. }
  8916. // fonts
  8917. if (!empty($data['fonts'])) {
  8918. $out .= ' /Font <<';
  8919. foreach ($data['fonts'] as $fontkey => $fontid) {
  8920. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  8921. }
  8922. $out .= ' >>';
  8923. }
  8924. // images or nested xobjects
  8925. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  8926. $out .= ' /XObject <<';
  8927. foreach ($data['images'] as $imgid) {
  8928. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  8929. }
  8930. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  8931. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  8932. }
  8933. $out .= ' >>';
  8934. }
  8935. $out .= ' >>'; //end resources
  8936. if (isset($data['group']) AND ($data['group'] !== false)) {
  8937. // set transparency group
  8938. $out .= ' /Group << /Type /Group /S /Transparency';
  8939. if (is_array($data['group'])) {
  8940. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  8941. $out .= ' /CS /'.$data['group']['CS'];
  8942. }
  8943. if (isset($data['group']['I'])) {
  8944. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  8945. }
  8946. if (isset($data['group']['K'])) {
  8947. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  8948. }
  8949. }
  8950. $out .= ' >>';
  8951. }
  8952. $stream = $this->_getrawstream($stream, $data['n']);
  8953. $out .= ' /Length '.strlen($stream);
  8954. $out .= ' >>';
  8955. $out .= ' stream'."\n".$stream."\n".'endstream';
  8956. $out .= "\n".'endobj';
  8957. $this->_out($out);
  8958. }
  8959. }
  8960. }
  8961. /**
  8962. * Output Spot Colors Resources.
  8963. * @protected
  8964. * @since 4.0.024 (2008-09-12)
  8965. */
  8966. protected function _putspotcolors() {
  8967. foreach ($this->spot_colors as $name => $color) {
  8968. $this->_newobj();
  8969. $this->spot_colors[$name]['n'] = $this->n;
  8970. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  8971. $out .= ' /DeviceCMYK <<';
  8972. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  8973. $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  8974. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  8975. $out .= "\n".'endobj';
  8976. $this->_out($out);
  8977. }
  8978. }
  8979. /**
  8980. * Return XObjects Dictionary.
  8981. * @return string XObjects dictionary
  8982. * @protected
  8983. * @since 5.8.014 (2010-08-23)
  8984. */
  8985. protected function _getxobjectdict() {
  8986. $out = '';
  8987. foreach ($this->xobjects as $id => $objid) {
  8988. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  8989. }
  8990. return $out;
  8991. }
  8992. /**
  8993. * Output Resources Dictionary.
  8994. * @protected
  8995. */
  8996. protected function _putresourcedict() {
  8997. $out = $this->_getobj(2)."\n";
  8998. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8999. $out .= ' /Font <<';
  9000. foreach ($this->fontkeys as $fontkey) {
  9001. $font = $this->getFontBuffer($fontkey);
  9002. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  9003. }
  9004. $out .= ' >>';
  9005. $out .= ' /XObject <<';
  9006. $out .= $this->_getxobjectdict();
  9007. $out .= ' >>';
  9008. // layers
  9009. if (!empty($this->pdflayers)) {
  9010. $out .= ' /Properties <<';
  9011. foreach ($this->pdflayers as $layer) {
  9012. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  9013. }
  9014. $out .= ' >>';
  9015. }
  9016. if (!$this->pdfa_mode) {
  9017. // transparency
  9018. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  9019. $out .= ' /ExtGState <<';
  9020. foreach ($this->extgstates as $k => $extgstate) {
  9021. if (isset($extgstate['name'])) {
  9022. $out .= ' /'.$extgstate['name'];
  9023. } else {
  9024. $out .= ' /GS'.$k;
  9025. }
  9026. $out .= ' '.$extgstate['n'].' 0 R';
  9027. }
  9028. $out .= ' >>';
  9029. }
  9030. if (isset($this->gradients) AND !empty($this->gradients)) {
  9031. $gp = '';
  9032. $gs = '';
  9033. foreach ($this->gradients as $id => $grad) {
  9034. // gradient patterns
  9035. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  9036. // gradient shadings
  9037. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  9038. }
  9039. $out .= ' /Pattern <<'.$gp.' >>';
  9040. $out .= ' /Shading <<'.$gs.' >>';
  9041. }
  9042. }
  9043. // spot colors
  9044. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  9045. $out .= ' /ColorSpace <<';
  9046. foreach ($this->spot_colors as $color) {
  9047. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  9048. }
  9049. $out .= ' >>';
  9050. }
  9051. $out .= ' >>';
  9052. $out .= "\n".'endobj';
  9053. $this->_out($out);
  9054. }
  9055. /**
  9056. * Output Resources.
  9057. * @protected
  9058. */
  9059. protected function _putresources() {
  9060. $this->_putextgstates();
  9061. $this->_putocg();
  9062. $this->_putfonts();
  9063. $this->_putimages();
  9064. $this->_putspotcolors();
  9065. $this->_putshaders();
  9066. $this->_putxobjects();
  9067. $this->_putresourcedict();
  9068. $this->_putdests();
  9069. $this->_putEmbeddedFiles();
  9070. $this->_putannotsobjs();
  9071. $this->_putjavascript();
  9072. $this->_putbookmarks();
  9073. $this->_putencryption();
  9074. }
  9075. /**
  9076. * Adds some Metadata information (Document Information Dictionary)
  9077. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  9078. * @return int object id
  9079. * @protected
  9080. */
  9081. protected function _putinfo() {
  9082. $oid = $this->_newobj();
  9083. $out = '<<';
  9084. // store current isunicode value
  9085. $prev_isunicode = $this->isunicode;
  9086. if ($this->docinfounicode) {
  9087. $this->isunicode = true;
  9088. }
  9089. if (!TCPDF_STATIC::empty_string($this->title)) {
  9090. // The document's title.
  9091. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  9092. }
  9093. if (!TCPDF_STATIC::empty_string($this->author)) {
  9094. // The name of the person who created the document.
  9095. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  9096. }
  9097. if (!TCPDF_STATIC::empty_string($this->subject)) {
  9098. // The subject of the document.
  9099. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  9100. }
  9101. if (!TCPDF_STATIC::empty_string($this->keywords)) {
  9102. // Keywords associated with the document.
  9103. $out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
  9104. }
  9105. if (!TCPDF_STATIC::empty_string($this->creator)) {
  9106. // If the document was converted to PDF from another format, the name of the conforming product that created the original document from which it was converted.
  9107. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  9108. }
  9109. // restore previous isunicode value
  9110. $this->isunicode = $prev_isunicode;
  9111. // default producer
  9112. $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
  9113. // The date and time the document was created, in human-readable form
  9114. $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
  9115. // The date and time the document was most recently modified, in human-readable form
  9116. $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
  9117. // A name object indicating whether the document has been modified to include trapping information
  9118. $out .= ' /Trapped /False';
  9119. $out .= ' >>';
  9120. $out .= "\n".'endobj';
  9121. $this->_out($out);
  9122. return $oid;
  9123. }
  9124. /**
  9125. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  9126. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9127. * @param $xmp (string) Custom XMP data.
  9128. * @since 5.9.128 (2011-10-06)
  9129. * @public
  9130. */
  9131. public function setExtraXMP($xmp) {
  9132. $this->custom_xmp = $xmp;
  9133. }
  9134. /**
  9135. * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
  9136. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9137. * @param $xmp (string) Custom XMP RDF data.
  9138. * @since 6.3.0 (2019-09-19)
  9139. * @public
  9140. */
  9141. public function setExtraXMPRDF($xmp) {
  9142. $this->custom_xmp_rdf = $xmp;
  9143. }
  9144. /**
  9145. * Put XMP data object and return ID.
  9146. * @return (int) The object ID.
  9147. * @since 5.9.121 (2011-09-28)
  9148. * @protected
  9149. */
  9150. protected function _putXMP() {
  9151. $oid = $this->_newobj();
  9152. // store current isunicode value
  9153. $prev_isunicode = $this->isunicode;
  9154. $this->isunicode = true;
  9155. $prev_encrypted = $this->encrypted;
  9156. $this->encrypted = false;
  9157. // set XMP data
  9158. $xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  9159. $xmp .= '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:08:04">'."\n";
  9160. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  9161. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  9162. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  9163. $xmp .= "\t\t\t".'<dc:title>'."\n";
  9164. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9165. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
  9166. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9167. $xmp .= "\t\t\t".'</dc:title>'."\n";
  9168. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  9169. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  9170. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
  9171. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  9172. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  9173. $xmp .= "\t\t\t".'<dc:description>'."\n";
  9174. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9175. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
  9176. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9177. $xmp .= "\t\t\t".'</dc:description>'."\n";
  9178. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  9179. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9180. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
  9181. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9182. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  9183. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9184. // convert doc creation date format
  9185. $dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
  9186. $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
  9187. $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
  9188. $doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
  9189. $doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
  9190. // convert doc modification date format
  9191. $dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
  9192. $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
  9193. $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
  9194. $docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
  9195. $docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
  9196. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  9197. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
  9198. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  9199. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
  9200. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
  9201. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9202. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  9203. $xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
  9204. $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
  9205. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9206. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  9207. $uuid = 'uuid:'.substr($this->file_id, 0, 8).'-'.substr($this->file_id, 8, 4).'-'.substr($this->file_id, 12, 4).'-'.substr($this->file_id, 16, 4).'-'.substr($this->file_id, 20, 12);
  9208. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  9209. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  9210. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9211. if ($this->pdfa_mode) {
  9212. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  9213. $xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
  9214. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  9215. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9216. }
  9217. // XMP extension schemas
  9218. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#">'."\n";
  9219. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  9220. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9221. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9222. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  9223. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  9224. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  9225. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9226. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9227. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  9228. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  9229. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  9230. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9231. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9232. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9233. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9234. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  9235. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9236. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9237. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9238. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9239. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9240. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9241. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9242. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  9243. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  9244. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  9245. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9246. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9247. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9248. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9249. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  9250. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  9251. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  9252. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9253. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9254. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9255. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  9256. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  9257. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9258. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9259. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9260. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9261. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  9262. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  9263. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9264. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9265. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9266. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9267. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9268. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9269. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  9270. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9271. $xmp .= $this->custom_xmp_rdf;
  9272. $xmp .= "\t".'</rdf:RDF>'."\n";
  9273. $xmp .= $this->custom_xmp;
  9274. $xmp .= '</x:xmpmeta>'."\n";
  9275. $xmp .= '<?xpacket end="w"?>';
  9276. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  9277. // restore previous isunicode value
  9278. $this->isunicode = $prev_isunicode;
  9279. $this->encrypted = $prev_encrypted;
  9280. $this->_out($out);
  9281. return $oid;
  9282. }
  9283. /**
  9284. * Output Catalog.
  9285. * @return int object id
  9286. * @protected
  9287. */
  9288. protected function _putcatalog() {
  9289. // put XMP
  9290. $xmpobj = $this->_putXMP();
  9291. // if required, add standard sRGB ICC colour profile
  9292. if ($this->pdfa_mode OR $this->force_srgb) {
  9293. $iccobj = $this->_newobj();
  9294. $icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
  9295. $filter = '';
  9296. if ($this->compress) {
  9297. $filter = ' /Filter /FlateDecode';
  9298. $icc = gzcompress($icc);
  9299. }
  9300. $icc = $this->_getrawstream($icc);
  9301. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  9302. }
  9303. // start catalog
  9304. $oid = $this->_newobj();
  9305. $out = '<< /Type /Catalog';
  9306. $out .= ' /Version /'.$this->PDFVersion;
  9307. //$out .= ' /Extensions <<>>';
  9308. $out .= ' /Pages 1 0 R';
  9309. //$out .= ' /PageLabels ' //...;
  9310. $out .= ' /Names <<';
  9311. if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
  9312. $out .= ' /JavaScript '.$this->n_js;
  9313. }
  9314. if (!empty($this->efnames)) {
  9315. $out .= ' /EmbeddedFiles <</Names [';
  9316. foreach ($this->efnames AS $fn => $fref) {
  9317. $out .= ' '.$this->_datastring($fn).' '.$fref;
  9318. }
  9319. $out .= ' ]>>';
  9320. }
  9321. $out .= ' >>';
  9322. if (!empty($this->dests)) {
  9323. $out .= ' /Dests '.($this->n_dests).' 0 R';
  9324. }
  9325. $out .= $this->_putviewerpreferences();
  9326. if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
  9327. $out .= ' /PageLayout /'.$this->LayoutMode;
  9328. }
  9329. if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
  9330. $out .= ' /PageMode /'.$this->PageMode;
  9331. }
  9332. if (count($this->outlines) > 0) {
  9333. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  9334. $out .= ' /PageMode /UseOutlines';
  9335. }
  9336. //$out .= ' /Threads []';
  9337. if ($this->ZoomMode == 'fullpage') {
  9338. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  9339. } elseif ($this->ZoomMode == 'fullwidth') {
  9340. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  9341. } elseif ($this->ZoomMode == 'real') {
  9342. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  9343. } elseif (!is_string($this->ZoomMode)) {
  9344. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
  9345. }
  9346. //$out .= ' /AA <<>>';
  9347. //$out .= ' /URI <<>>';
  9348. $out .= ' /Metadata '.$xmpobj.' 0 R';
  9349. //$out .= ' /StructTreeRoot <<>>';
  9350. //$out .= ' /MarkInfo <<>>';
  9351. if (isset($this->l['a_meta_language'])) {
  9352. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  9353. }
  9354. //$out .= ' /SpiderInfo <<>>';
  9355. // set OutputIntent to sRGB IEC61966-2.1 if required
  9356. if ($this->pdfa_mode OR $this->force_srgb) {
  9357. $out .= ' /OutputIntents [<<';
  9358. $out .= ' /Type /OutputIntent';
  9359. $out .= ' /S /GTS_PDFA1';
  9360. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9361. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9362. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  9363. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9364. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  9365. $out .= ' >>]';
  9366. }
  9367. //$out .= ' /PieceInfo <<>>';
  9368. if (!empty($this->pdflayers)) {
  9369. $lyrobjs = '';
  9370. $lyrobjs_off = '';
  9371. $lyrobjs_lock = '';
  9372. foreach ($this->pdflayers as $layer) {
  9373. $layer_obj_ref = ' '.$layer['objid'].' 0 R';
  9374. $lyrobjs .= $layer_obj_ref;
  9375. if ($layer['view'] === false) {
  9376. $lyrobjs_off .= $layer_obj_ref;
  9377. }
  9378. if ($layer['lock']) {
  9379. $lyrobjs_lock .= $layer_obj_ref;
  9380. }
  9381. }
  9382. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  9383. $out .= ' /D <<';
  9384. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  9385. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  9386. $out .= ' /BaseState /ON';
  9387. $out .= ' /OFF ['.$lyrobjs_off.']';
  9388. $out .= ' /Locked ['.$lyrobjs_lock.']';
  9389. $out .= ' /Intent /View';
  9390. $out .= ' /AS [';
  9391. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  9392. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  9393. $out .= ' ]';
  9394. $out .= ' /Order ['.$lyrobjs.']';
  9395. $out .= ' /ListMode /AllPages';
  9396. //$out .= ' /RBGroups ['..']';
  9397. //$out .= ' /Locked ['..']';
  9398. $out .= ' >>';
  9399. $out .= ' >>';
  9400. }
  9401. // AcroForm
  9402. if (!empty($this->form_obj_id)
  9403. OR ($this->sign AND isset($this->signature_data['cert_type']))
  9404. OR !empty($this->empty_signature_appearance)) {
  9405. $out .= ' /AcroForm <<';
  9406. $objrefs = '';
  9407. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9408. // set reference for signature object
  9409. $objrefs .= $this->sig_obj_id.' 0 R';
  9410. }
  9411. if (!empty($this->empty_signature_appearance)) {
  9412. foreach ($this->empty_signature_appearance as $esa) {
  9413. // set reference for empty signature objects
  9414. $objrefs .= ' '.$esa['objid'].' 0 R';
  9415. }
  9416. }
  9417. if (!empty($this->form_obj_id)) {
  9418. foreach($this->form_obj_id as $objid) {
  9419. $objrefs .= ' '.$objid.' 0 R';
  9420. }
  9421. }
  9422. $out .= ' /Fields ['.$objrefs.']';
  9423. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  9424. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  9425. $out .= ' /NeedAppearances false';
  9426. }
  9427. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9428. if ($this->signature_data['cert_type'] > 0) {
  9429. $out .= ' /SigFlags 3';
  9430. } else {
  9431. $out .= ' /SigFlags 1';
  9432. }
  9433. }
  9434. //$out .= ' /CO ';
  9435. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  9436. $out .= ' /DR <<';
  9437. $out .= ' /Font <<';
  9438. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  9439. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  9440. }
  9441. $out .= ' >> >>';
  9442. }
  9443. $font = $this->getFontBuffer('helvetica');
  9444. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  9445. $out .= ' /Q '.(($this->rtl)?'2':'0');
  9446. //$out .= ' /XFA ';
  9447. $out .= ' >>';
  9448. // signatures
  9449. if ($this->sign AND isset($this->signature_data['cert_type'])
  9450. AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
  9451. if ($this->signature_data['cert_type'] > 0) {
  9452. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  9453. } else {
  9454. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  9455. }
  9456. }
  9457. }
  9458. //$out .= ' /Legal <<>>';
  9459. //$out .= ' /Requirements []';
  9460. //$out .= ' /Collection <<>>';
  9461. //$out .= ' /NeedsRendering true';
  9462. $out .= ' >>';
  9463. $out .= "\n".'endobj';
  9464. $this->_out($out);
  9465. return $oid;
  9466. }
  9467. /**
  9468. * Output viewer preferences.
  9469. * @return string for viewer preferences
  9470. * @author Nicola asuni
  9471. * @since 3.1.000 (2008-06-09)
  9472. * @protected
  9473. */
  9474. protected function _putviewerpreferences() {
  9475. $vp = $this->viewer_preferences;
  9476. $out = ' /ViewerPreferences <<';
  9477. if ($this->rtl) {
  9478. $out .= ' /Direction /R2L';
  9479. } else {
  9480. $out .= ' /Direction /L2R';
  9481. }
  9482. if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
  9483. $out .= ' /HideToolbar true';
  9484. }
  9485. if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
  9486. $out .= ' /HideMenubar true';
  9487. }
  9488. if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
  9489. $out .= ' /HideWindowUI true';
  9490. }
  9491. if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
  9492. $out .= ' /FitWindow true';
  9493. }
  9494. if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
  9495. $out .= ' /CenterWindow true';
  9496. }
  9497. if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
  9498. $out .= ' /DisplayDocTitle true';
  9499. }
  9500. if (isset($vp['NonFullScreenPageMode'])) {
  9501. $out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
  9502. }
  9503. if (isset($vp['ViewArea'])) {
  9504. $out .= ' /ViewArea /'.$vp['ViewArea'];
  9505. }
  9506. if (isset($vp['ViewClip'])) {
  9507. $out .= ' /ViewClip /'.$vp['ViewClip'];
  9508. }
  9509. if (isset($vp['PrintArea'])) {
  9510. $out .= ' /PrintArea /'.$vp['PrintArea'];
  9511. }
  9512. if (isset($vp['PrintClip'])) {
  9513. $out .= ' /PrintClip /'.$vp['PrintClip'];
  9514. }
  9515. if (isset($vp['PrintScaling'])) {
  9516. $out .= ' /PrintScaling /'.$vp['PrintScaling'];
  9517. }
  9518. if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
  9519. $out .= ' /Duplex /'.$vp['Duplex'];
  9520. }
  9521. if (isset($vp['PickTrayByPDFSize'])) {
  9522. if ($vp['PickTrayByPDFSize']) {
  9523. $out .= ' /PickTrayByPDFSize true';
  9524. } else {
  9525. $out .= ' /PickTrayByPDFSize false';
  9526. }
  9527. }
  9528. if (isset($vp['PrintPageRange'])) {
  9529. $PrintPageRangeNum = '';
  9530. foreach ($vp['PrintPageRange'] as $k => $v) {
  9531. $PrintPageRangeNum .= ' '.($v - 1).'';
  9532. }
  9533. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  9534. }
  9535. if (isset($vp['NumCopies'])) {
  9536. $out .= ' /NumCopies '.intval($vp['NumCopies']);
  9537. }
  9538. $out .= ' >>';
  9539. return $out;
  9540. }
  9541. /**
  9542. * Output PDF File Header (7.5.2).
  9543. * @protected
  9544. */
  9545. protected function _putheader() {
  9546. $this->_out('%PDF-'.$this->PDFVersion);
  9547. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  9548. }
  9549. /**
  9550. * Output end of document (EOF).
  9551. * @protected
  9552. */
  9553. protected function _enddoc() {
  9554. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  9555. // save subset chars of the previous font
  9556. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  9557. }
  9558. $this->state = 1;
  9559. $this->_putheader();
  9560. $this->_putpages();
  9561. $this->_putresources();
  9562. // empty signature fields
  9563. if (!empty($this->empty_signature_appearance)) {
  9564. foreach ($this->empty_signature_appearance as $key => $esa) {
  9565. // widget annotation for empty signature
  9566. $out = $this->_getobj($esa['objid'])."\n";
  9567. $out .= '<< /Type /Annot';
  9568. $out .= ' /Subtype /Widget';
  9569. $out .= ' /Rect ['.$esa['rect'].']';
  9570. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  9571. $out .= ' /F 4';
  9572. $out .= ' /FT /Sig';
  9573. $signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
  9574. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  9575. $out .= ' /Ff 0';
  9576. $out .= ' >>';
  9577. $out .= "\n".'endobj';
  9578. $this->_out($out);
  9579. }
  9580. }
  9581. // Signature
  9582. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9583. // widget annotation for signature
  9584. $out = $this->_getobj($this->sig_obj_id)."\n";
  9585. $out .= '<< /Type /Annot';
  9586. $out .= ' /Subtype /Widget';
  9587. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  9588. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  9589. $out .= ' /F 4';
  9590. $out .= ' /FT /Sig';
  9591. $out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
  9592. $out .= ' /Ff 0';
  9593. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  9594. $out .= ' >>';
  9595. $out .= "\n".'endobj';
  9596. $this->_out($out);
  9597. // signature
  9598. $this->_putsignature();
  9599. }
  9600. // Info
  9601. $objid_info = $this->_putinfo();
  9602. // Catalog
  9603. $objid_catalog = $this->_putcatalog();
  9604. // Cross-ref
  9605. $o = $this->bufferlen;
  9606. // XREF section
  9607. $this->_out('xref');
  9608. $this->_out('0 '.($this->n + 1));
  9609. $this->_out('0000000000 65535 f ');
  9610. $freegen = ($this->n + 2);
  9611. for ($i=1; $i <= $this->n; ++$i) {
  9612. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  9613. $this->_out(sprintf('0000000000 %05d f ', $freegen));
  9614. ++$freegen;
  9615. } else {
  9616. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  9617. }
  9618. }
  9619. // TRAILER
  9620. $out = 'trailer'."\n";
  9621. $out .= '<<';
  9622. $out .= ' /Size '.($this->n + 1);
  9623. $out .= ' /Root '.$objid_catalog.' 0 R';
  9624. $out .= ' /Info '.$objid_info.' 0 R';
  9625. if ($this->encrypted) {
  9626. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  9627. }
  9628. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  9629. $out .= ' >>';
  9630. $this->_out($out);
  9631. $this->_out('startxref');
  9632. $this->_out($o);
  9633. $this->_out('%%EOF');
  9634. $this->state = 3; // end-of-doc
  9635. }
  9636. /**
  9637. * Initialize a new page.
  9638. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  9639. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  9640. * @protected
  9641. * @see getPageSizeFromFormat(), setPageFormat()
  9642. */
  9643. protected function _beginpage($orientation='', $format='') {
  9644. ++$this->page;
  9645. $this->pageobjects[$this->page] = array();
  9646. $this->setPageBuffer($this->page, '');
  9647. // initialize array for graphics tranformation positions inside a page buffer
  9648. $this->transfmrk[$this->page] = array();
  9649. $this->state = 2;
  9650. if (TCPDF_STATIC::empty_string($orientation)) {
  9651. if (isset($this->CurOrientation)) {
  9652. $orientation = $this->CurOrientation;
  9653. } elseif ($this->fwPt > $this->fhPt) {
  9654. // landscape
  9655. $orientation = 'L';
  9656. } else {
  9657. // portrait
  9658. $orientation = 'P';
  9659. }
  9660. }
  9661. if (TCPDF_STATIC::empty_string($format)) {
  9662. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  9663. $this->setPageOrientation($orientation);
  9664. } else {
  9665. $this->setPageFormat($format, $orientation);
  9666. }
  9667. if ($this->rtl) {
  9668. $this->x = $this->w - $this->rMargin;
  9669. } else {
  9670. $this->x = $this->lMargin;
  9671. }
  9672. $this->y = $this->tMargin;
  9673. if (isset($this->newpagegroup[$this->page])) {
  9674. // start a new group
  9675. $this->currpagegroup = $this->newpagegroup[$this->page];
  9676. $this->pagegroups[$this->currpagegroup] = 1;
  9677. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  9678. ++$this->pagegroups[$this->currpagegroup];
  9679. }
  9680. }
  9681. /**
  9682. * Mark end of page.
  9683. * @protected
  9684. */
  9685. protected function _endpage() {
  9686. $this->setVisibility('all');
  9687. $this->state = 1;
  9688. }
  9689. /**
  9690. * Begin a new object and return the object number.
  9691. * @return int object number
  9692. * @protected
  9693. */
  9694. protected function _newobj() {
  9695. $this->_out($this->_getobj());
  9696. return $this->n;
  9697. }
  9698. /**
  9699. * Return the starting object string for the selected object ID.
  9700. * @param $objid (int) Object ID (leave empty to get a new ID).
  9701. * @return string the starting object string
  9702. * @protected
  9703. * @since 5.8.009 (2010-08-20)
  9704. */
  9705. protected function _getobj($objid='') {
  9706. if ($objid === '') {
  9707. ++$this->n;
  9708. $objid = $this->n;
  9709. }
  9710. $this->offsets[$objid] = $this->bufferlen;
  9711. $this->pageobjects[$this->page][] = $objid;
  9712. return $objid.' 0 obj';
  9713. }
  9714. /**
  9715. * Underline text.
  9716. * @param $x (int) X coordinate
  9717. * @param $y (int) Y coordinate
  9718. * @param $txt (string) text to underline
  9719. * @protected
  9720. */
  9721. protected function _dounderline($x, $y, $txt) {
  9722. $w = $this->GetStringWidth($txt);
  9723. return $this->_dounderlinew($x, $y, $w);
  9724. }
  9725. /**
  9726. * Underline for rectangular text area.
  9727. * @param $x (int) X coordinate
  9728. * @param $y (int) Y coordinate
  9729. * @param $w (int) width to underline
  9730. * @protected
  9731. * @since 4.8.008 (2009-09-29)
  9732. */
  9733. protected function _dounderlinew($x, $y, $w) {
  9734. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9735. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  9736. }
  9737. /**
  9738. * Line through text.
  9739. * @param $x (int) X coordinate
  9740. * @param $y (int) Y coordinate
  9741. * @param $txt (string) text to linethrough
  9742. * @protected
  9743. */
  9744. protected function _dolinethrough($x, $y, $txt) {
  9745. $w = $this->GetStringWidth($txt);
  9746. return $this->_dolinethroughw($x, $y, $w);
  9747. }
  9748. /**
  9749. * Line through for rectangular text area.
  9750. * @param $x (int) X coordinate
  9751. * @param $y (int) Y coordinate
  9752. * @param $w (int) line length (width)
  9753. * @protected
  9754. * @since 4.9.008 (2009-09-29)
  9755. */
  9756. protected function _dolinethroughw($x, $y, $w) {
  9757. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9758. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  9759. }
  9760. /**
  9761. * Overline text.
  9762. * @param $x (int) X coordinate
  9763. * @param $y (int) Y coordinate
  9764. * @param $txt (string) text to overline
  9765. * @protected
  9766. * @since 4.9.015 (2010-04-19)
  9767. */
  9768. protected function _dooverline($x, $y, $txt) {
  9769. $w = $this->GetStringWidth($txt);
  9770. return $this->_dooverlinew($x, $y, $w);
  9771. }
  9772. /**
  9773. * Overline for rectangular text area.
  9774. * @param $x (int) X coordinate
  9775. * @param $y (int) Y coordinate
  9776. * @param $w (int) width to overline
  9777. * @protected
  9778. * @since 4.9.015 (2010-04-19)
  9779. */
  9780. protected function _dooverlinew($x, $y, $w) {
  9781. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9782. return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  9783. }
  9784. /**
  9785. * Format a data string for meta information
  9786. * @param $s (string) data string to escape.
  9787. * @param $n (int) object ID
  9788. * @return string escaped string.
  9789. * @protected
  9790. */
  9791. protected function _datastring($s, $n=0) {
  9792. if ($n == 0) {
  9793. $n = $this->n;
  9794. }
  9795. $s = $this->_encrypt_data($n, $s);
  9796. return '('. TCPDF_STATIC::_escape($s).')';
  9797. }
  9798. /**
  9799. * Set the document creation timestamp
  9800. * @param $time (mixed) Document creation timestamp in seconds or date-time string.
  9801. * @public
  9802. * @since 5.9.152 (2012-03-23)
  9803. */
  9804. public function setDocCreationTimestamp($time) {
  9805. if (is_string($time)) {
  9806. $time = TCPDF_STATIC::getTimestamp($time);
  9807. }
  9808. $this->doc_creation_timestamp = intval($time);
  9809. }
  9810. /**
  9811. * Set the document modification timestamp
  9812. * @param $time (mixed) Document modification timestamp in seconds or date-time string.
  9813. * @public
  9814. * @since 5.9.152 (2012-03-23)
  9815. */
  9816. public function setDocModificationTimestamp($time) {
  9817. if (is_string($time)) {
  9818. $time = TCPDF_STATIC::getTimestamp($time);
  9819. }
  9820. $this->doc_modification_timestamp = intval($time);
  9821. }
  9822. /**
  9823. * Returns document creation timestamp in seconds.
  9824. * @return (int) Creation timestamp in seconds.
  9825. * @public
  9826. * @since 5.9.152 (2012-03-23)
  9827. */
  9828. public function getDocCreationTimestamp() {
  9829. return $this->doc_creation_timestamp;
  9830. }
  9831. /**
  9832. * Returns document modification timestamp in seconds.
  9833. * @return (int) Modfication timestamp in seconds.
  9834. * @public
  9835. * @since 5.9.152 (2012-03-23)
  9836. */
  9837. public function getDocModificationTimestamp() {
  9838. return $this->doc_modification_timestamp;
  9839. }
  9840. /**
  9841. * Returns a formatted date for meta information
  9842. * @param $n (int) Object ID.
  9843. * @param $timestamp (int) Timestamp to convert.
  9844. * @return string escaped date string.
  9845. * @protected
  9846. * @since 4.6.028 (2009-08-25)
  9847. */
  9848. protected function _datestring($n=0, $timestamp=0) {
  9849. if ((empty($timestamp)) OR ($timestamp < 0)) {
  9850. $timestamp = $this->doc_creation_timestamp;
  9851. }
  9852. return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
  9853. }
  9854. /**
  9855. * Format a text string for meta information
  9856. * @param $s (string) string to escape.
  9857. * @param $n (int) object ID
  9858. * @return string escaped string.
  9859. * @protected
  9860. */
  9861. protected function _textstring($s, $n=0) {
  9862. if ($this->isunicode) {
  9863. //Convert string to UTF-16BE
  9864. $s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
  9865. }
  9866. return $this->_datastring($s, $n);
  9867. }
  9868. /**
  9869. * get raw output stream.
  9870. * @param $s (string) string to output.
  9871. * @param $n (int) object reference for encryption mode
  9872. * @protected
  9873. * @author Nicola Asuni
  9874. * @since 5.5.000 (2010-06-22)
  9875. */
  9876. protected function _getrawstream($s, $n=0) {
  9877. if ($n <= 0) {
  9878. // default to current object
  9879. $n = $this->n;
  9880. }
  9881. return $this->_encrypt_data($n, $s);
  9882. }
  9883. /**
  9884. * Output a string to the document.
  9885. * @param $s (string) string to output.
  9886. * @protected
  9887. */
  9888. protected function _out($s) {
  9889. if ($this->state == 2) {
  9890. if ($this->inxobj) {
  9891. // we are inside an XObject template
  9892. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  9893. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  9894. // puts data before page footer
  9895. $pagebuff = $this->getPageBuffer($this->page);
  9896. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  9897. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  9898. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  9899. // update footer position
  9900. $this->footerpos[$this->page] += strlen($s."\n");
  9901. } else {
  9902. // set page data
  9903. $this->setPageBuffer($this->page, $s."\n", true);
  9904. }
  9905. } elseif ($this->state > 0) {
  9906. // set general data
  9907. $this->setBuffer($s."\n");
  9908. }
  9909. }
  9910. /**
  9911. * Set header font.
  9912. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9913. * @public
  9914. * @since 1.1
  9915. */
  9916. public function setHeaderFont($font) {
  9917. $this->header_font = $font;
  9918. }
  9919. /**
  9920. * Get header font.
  9921. * @return array() Array describing the basic font parameters: (family, style, size).
  9922. * @public
  9923. * @since 4.0.012 (2008-07-24)
  9924. */
  9925. public function getHeaderFont() {
  9926. return $this->header_font;
  9927. }
  9928. /**
  9929. * Set footer font.
  9930. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9931. * @public
  9932. * @since 1.1
  9933. */
  9934. public function setFooterFont($font) {
  9935. $this->footer_font = $font;
  9936. }
  9937. /**
  9938. * Get Footer font.
  9939. * @return array() Array describing the basic font parameters: (family, style, size).
  9940. * @public
  9941. * @since 4.0.012 (2008-07-24)
  9942. */
  9943. public function getFooterFont() {
  9944. return $this->footer_font;
  9945. }
  9946. /**
  9947. * Set language array.
  9948. * @param $language (array)
  9949. * @public
  9950. * @since 1.1
  9951. */
  9952. public function setLanguageArray($language) {
  9953. $this->l = $language;
  9954. if (isset($this->l['a_meta_dir'])) {
  9955. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  9956. } else {
  9957. $this->rtl = false;
  9958. }
  9959. }
  9960. /**
  9961. * Returns the PDF data.
  9962. * @public
  9963. */
  9964. public function getPDFData() {
  9965. if ($this->state < 3) {
  9966. $this->Close();
  9967. }
  9968. return $this->buffer;
  9969. }
  9970. /**
  9971. * Output anchor link.
  9972. * @param $url (string) link URL or internal link (i.e.: &lt;a href="#23,4.5"&gt;link to page 23 at 4.5 Y position&lt;/a&gt;)
  9973. * @param $name (string) link name
  9974. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  9975. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  9976. * @param $color (array) array of RGB text color
  9977. * @param $style (string) font style (U, D, B, I)
  9978. * @param $firstblock (boolean) if true the string is the starting of a line.
  9979. * @return the number of cells used or the remaining text if $firstline = true;
  9980. * @public
  9981. */
  9982. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  9983. if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
  9984. // convert url to internal link
  9985. $lnkdata = explode(',', $url);
  9986. if (isset($lnkdata[0]) ) {
  9987. $page = substr($lnkdata[0], 1);
  9988. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  9989. $lnky = floatval($lnkdata[1]);
  9990. } else {
  9991. $lnky = 0;
  9992. }
  9993. $url = $this->AddLink();
  9994. $this->SetLink($url, $lnky, $page);
  9995. }
  9996. }
  9997. // store current settings
  9998. $prevcolor = $this->fgcolor;
  9999. $prevstyle = $this->FontStyle;
  10000. if (empty($color)) {
  10001. $this->SetTextColorArray($this->htmlLinkColorArray);
  10002. } else {
  10003. $this->SetTextColorArray($color);
  10004. }
  10005. if ($style == -1) {
  10006. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  10007. } else {
  10008. $this->SetFont('', $this->FontStyle.$style);
  10009. }
  10010. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  10011. // restore settings
  10012. $this->SetFont('', $prevstyle);
  10013. $this->SetTextColorArray($prevcolor);
  10014. return $ret;
  10015. }
  10016. /**
  10017. * Converts pixels to User's Units.
  10018. * @param $px (int) pixels
  10019. * @return float value in user's unit
  10020. * @public
  10021. * @see setImageScale(), getImageScale()
  10022. */
  10023. public function pixelsToUnits($px) {
  10024. return ($px / ($this->imgscale * $this->k));
  10025. }
  10026. /**
  10027. * Reverse function for htmlentities.
  10028. * Convert entities in UTF-8.
  10029. * @param $text_to_convert (string) Text to convert.
  10030. * @return string converted text string
  10031. * @public
  10032. */
  10033. public function unhtmlentities($text_to_convert) {
  10034. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  10035. }
  10036. // ENCRYPTION METHODS ----------------------------------
  10037. /**
  10038. * Compute encryption key depending on object number where the encrypted data is stored.
  10039. * This is used for all strings and streams without crypt filter specifier.
  10040. * @param $n (int) object number
  10041. * @return int object key
  10042. * @protected
  10043. * @author Nicola Asuni
  10044. * @since 2.0.000 (2008-01-02)
  10045. */
  10046. protected function _objectkey($n) {
  10047. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  10048. if ($this->encryptdata['mode'] == 2) { // AES-128
  10049. // AES padding
  10050. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  10051. }
  10052. $objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  10053. $objkey = substr($objkey, 0, 16);
  10054. return $objkey;
  10055. }
  10056. /**
  10057. * Encrypt the input string.
  10058. * @param $n (int) object number
  10059. * @param $s (string) data string to encrypt
  10060. * @return encrypted string
  10061. * @protected
  10062. * @author Nicola Asuni
  10063. * @since 5.0.005 (2010-05-11)
  10064. */
  10065. protected function _encrypt_data($n, $s) {
  10066. if (!$this->encrypted) {
  10067. return $s;
  10068. }
  10069. switch ($this->encryptdata['mode']) {
  10070. case 0: // RC4-40
  10071. case 1: { // RC4-128
  10072. $s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
  10073. break;
  10074. }
  10075. case 2: { // AES-128
  10076. $s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
  10077. break;
  10078. }
  10079. case 3: { // AES-256
  10080. $s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
  10081. break;
  10082. }
  10083. }
  10084. return $s;
  10085. }
  10086. /**
  10087. * Put encryption on PDF document.
  10088. * @protected
  10089. * @author Nicola Asuni
  10090. * @since 2.0.000 (2008-01-02)
  10091. */
  10092. protected function _putencryption() {
  10093. if (!$this->encrypted) {
  10094. return;
  10095. }
  10096. $this->encryptdata['objid'] = $this->_newobj();
  10097. $out = '<<';
  10098. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  10099. $this->encryptdata['Filter'] = 'Standard';
  10100. }
  10101. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  10102. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  10103. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  10104. }
  10105. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  10106. $this->encryptdata['V'] = 1;
  10107. }
  10108. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  10109. $out .= ' /V '.$this->encryptdata['V'];
  10110. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  10111. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  10112. $out .= ' /Length '.$this->encryptdata['Length'];
  10113. } else {
  10114. $out .= ' /Length 40';
  10115. }
  10116. if ($this->encryptdata['V'] >= 4) {
  10117. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  10118. $this->encryptdata['StmF'] = 'Identity';
  10119. }
  10120. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  10121. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10122. $this->encryptdata['StrF'] = 'Identity';
  10123. }
  10124. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  10125. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  10126. $out .= ' /CF <<';
  10127. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  10128. $out .= ' /Type /CryptFilter';
  10129. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  10130. // The method used
  10131. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  10132. if ($this->encryptdata['pubkey']) {
  10133. $out .= ' /Recipients [';
  10134. foreach ($this->encryptdata['Recipients'] as $rec) {
  10135. $out .= ' <'.$rec.'>';
  10136. }
  10137. $out .= ' ]';
  10138. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  10139. $out .= ' /EncryptMetadata false';
  10140. } else {
  10141. $out .= ' /EncryptMetadata true';
  10142. }
  10143. }
  10144. } else {
  10145. $out .= ' /CFM /None';
  10146. }
  10147. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  10148. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  10149. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  10150. } else {
  10151. $out .= ' /AuthEvent /DocOpen';
  10152. }
  10153. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  10154. // The bit length of the encryption key.
  10155. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  10156. }
  10157. $out .= ' >> >>';
  10158. }
  10159. // The name of the crypt filter that shall be used by default when decrypting streams.
  10160. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  10161. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10162. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  10163. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  10164. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  10165. $out .= ' /EFF /'.$this->encryptdata[''];
  10166. }
  10167. }
  10168. // Additional encryption dictionary entries for the standard security handler
  10169. if ($this->encryptdata['pubkey']) {
  10170. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  10171. $out .= ' /Recipients [';
  10172. foreach ($this->encryptdata['Recipients'] as $rec) {
  10173. $out .= ' <'.$rec.'>';
  10174. }
  10175. $out .= ' ]';
  10176. }
  10177. } else {
  10178. $out .= ' /R';
  10179. if ($this->encryptdata['V'] == 5) { // AES-256
  10180. $out .= ' 5';
  10181. $out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
  10182. $out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
  10183. $out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
  10184. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  10185. $out .= ' 4';
  10186. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  10187. $out .= ' 2';
  10188. } else { // RC-128
  10189. $out .= ' 3';
  10190. }
  10191. $out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
  10192. $out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
  10193. $out .= ' /P '.$this->encryptdata['P'];
  10194. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  10195. $out .= ' /EncryptMetadata false';
  10196. } else {
  10197. $out .= ' /EncryptMetadata true';
  10198. }
  10199. }
  10200. $out .= ' >>';
  10201. $out .= "\n".'endobj';
  10202. $this->_out($out);
  10203. }
  10204. /**
  10205. * Compute U value (used for encryption)
  10206. * @return string U value
  10207. * @protected
  10208. * @since 2.0.000 (2008-01-02)
  10209. * @author Nicola Asuni
  10210. */
  10211. protected function _Uvalue() {
  10212. if ($this->encryptdata['mode'] == 0) { // RC4-40
  10213. return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
  10214. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  10215. $tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
  10216. $enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
  10217. $len = strlen($tmp);
  10218. for ($i = 1; $i <= 19; ++$i) {
  10219. $ek = '';
  10220. for ($j = 0; $j < $len; ++$j) {
  10221. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  10222. }
  10223. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10224. }
  10225. $enc .= str_repeat("\x00", 16);
  10226. return substr($enc, 0, 32);
  10227. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10228. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10229. // User Validation Salt
  10230. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  10231. // User Key Salt
  10232. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  10233. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  10234. }
  10235. }
  10236. /**
  10237. * Compute UE value (used for encryption)
  10238. * @return string UE value
  10239. * @protected
  10240. * @since 5.9.006 (2010-10-19)
  10241. * @author Nicola Asuni
  10242. */
  10243. protected function _UEvalue() {
  10244. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  10245. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10246. }
  10247. /**
  10248. * Compute O value (used for encryption)
  10249. * @return string O value
  10250. * @protected
  10251. * @since 2.0.000 (2008-01-02)
  10252. * @author Nicola Asuni
  10253. */
  10254. protected function _Ovalue() {
  10255. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  10256. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
  10257. if ($this->encryptdata['mode'] > 0) {
  10258. for ($i = 0; $i < 50; ++$i) {
  10259. $tmp = TCPDF_STATIC::_md5_16($tmp);
  10260. }
  10261. }
  10262. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  10263. $enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
  10264. if ($this->encryptdata['mode'] > 0) {
  10265. $len = strlen($owner_key);
  10266. for ($i = 1; $i <= 19; ++$i) {
  10267. $ek = '';
  10268. for ($j = 0; $j < $len; ++$j) {
  10269. $ek .= chr(ord($owner_key[$j]) ^ $i);
  10270. }
  10271. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10272. }
  10273. }
  10274. return $enc;
  10275. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10276. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10277. // Owner Validation Salt
  10278. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  10279. // Owner Key Salt
  10280. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  10281. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  10282. }
  10283. }
  10284. /**
  10285. * Compute OE value (used for encryption)
  10286. * @return string OE value
  10287. * @protected
  10288. * @since 5.9.006 (2010-10-19)
  10289. * @author Nicola Asuni
  10290. */
  10291. protected function _OEvalue() {
  10292. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  10293. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10294. }
  10295. /**
  10296. * Convert password for AES-256 encryption mode
  10297. * @param $password (string) password
  10298. * @return string password
  10299. * @protected
  10300. * @since 5.9.006 (2010-10-19)
  10301. * @author Nicola Asuni
  10302. */
  10303. protected function _fixAES256Password($password) {
  10304. $psw = ''; // password to be returned
  10305. $psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
  10306. foreach ($psw_array as $c) {
  10307. $psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
  10308. }
  10309. return substr($psw, 0, 127);
  10310. }
  10311. /**
  10312. * Compute encryption key
  10313. * @protected
  10314. * @since 2.0.000 (2008-01-02)
  10315. * @author Nicola Asuni
  10316. */
  10317. protected function _generateencryptionkey() {
  10318. $keybytelen = ($this->encryptdata['Length'] / 8);
  10319. if (!$this->encryptdata['pubkey']) { // standard mode
  10320. if ($this->encryptdata['mode'] == 3) { // AES-256
  10321. // generate 256 bit random key
  10322. $this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
  10323. // truncate passwords
  10324. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  10325. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  10326. // Compute U value
  10327. $this->encryptdata['U'] = $this->_Uvalue();
  10328. // Compute UE value
  10329. $this->encryptdata['UE'] = $this->_UEvalue();
  10330. // Compute O value
  10331. $this->encryptdata['O'] = $this->_Ovalue();
  10332. // Compute OE value
  10333. $this->encryptdata['OE'] = $this->_OEvalue();
  10334. // Compute P value
  10335. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10336. // Computing the encryption dictionary's Perms (permissions) value
  10337. $perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  10338. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  10339. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  10340. $perms .= 'F';
  10341. } else {
  10342. $perms .= 'T';
  10343. }
  10344. $perms .= 'adb'; // bytes 9-11
  10345. $perms .= 'nick'; // bytes 12-15
  10346. $this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
  10347. } else { // RC4-40, RC4-128, AES-128
  10348. // Pad passwords
  10349. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10350. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10351. // Compute O value
  10352. $this->encryptdata['O'] = $this->_Ovalue();
  10353. // get default permissions (reverse byte order)
  10354. $permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
  10355. // Compute encryption key
  10356. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  10357. if ($this->encryptdata['mode'] > 0) {
  10358. for ($i = 0; $i < 50; ++$i) {
  10359. $tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
  10360. }
  10361. }
  10362. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  10363. // Compute U value
  10364. $this->encryptdata['U'] = $this->_Uvalue();
  10365. // Compute P value
  10366. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10367. }
  10368. } else { // Public-Key mode
  10369. // random 20-byte seed
  10370. $seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
  10371. $recipient_bytes = '';
  10372. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  10373. // for each public certificate
  10374. if (isset($pubkey['p'])) {
  10375. $pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  10376. } else {
  10377. $pkprotection = $this->encryptdata['protection'];
  10378. }
  10379. // get default permissions (reverse byte order)
  10380. $pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
  10381. // envelope data
  10382. $envelope = $seed.$pkpermissions;
  10383. // write the envelope data to a temporary file
  10384. $tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
  10385. $f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
  10386. if (!$f) {
  10387. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  10388. }
  10389. $envelope_length = strlen($envelope);
  10390. fwrite($f, $envelope, $envelope_length);
  10391. fclose($f);
  10392. $tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
  10393. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  10394. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  10395. }
  10396. // read encryption signature
  10397. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  10398. // extract signature
  10399. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  10400. $tmparr = explode("\n\n", $signature);
  10401. $signature = trim($tmparr[1]);
  10402. unset($tmparr);
  10403. // decode signature
  10404. $signature = base64_decode($signature);
  10405. // convert signature to hex
  10406. $hexsignature = current(unpack('H*', $signature));
  10407. // store signature on recipients array
  10408. $this->encryptdata['Recipients'][] = $hexsignature;
  10409. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  10410. $recipient_bytes .= $signature;
  10411. }
  10412. // calculate encryption key
  10413. if ($this->encryptdata['mode'] == 3) { // AES-256
  10414. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  10415. } else { // RC4-40, RC4-128, AES-128
  10416. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  10417. }
  10418. }
  10419. }
  10420. /**
  10421. * Set document protection
  10422. * Remark: the protection against modification is for people who have the full Acrobat product.
  10423. * 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.
  10424. * 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.
  10425. * @param $permissions (Array) the set of permissions (specify the ones you want to block):<ul><li>print : Print the document;</li><li>modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';</li><li>copy : Copy or otherwise extract text and graphics from the document;</li><li>annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);</li><li>fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;</li><li>extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);</li><li>assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;</li><li>print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.</li><li>owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.</li></ul>
  10426. * @param $user_pass (String) user password. Empty by default.
  10427. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  10428. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  10429. * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
  10430. * @public
  10431. * @since 2.0.000 (2008-01-02)
  10432. * @author Nicola Asuni
  10433. */
  10434. public function SetProtection($permissions=array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass='', $owner_pass=null, $mode=0, $pubkeys=null) {
  10435. if ($this->pdfa_mode) {
  10436. // encryption is not allowed in PDF/A mode
  10437. return;
  10438. }
  10439. $this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
  10440. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  10441. // public-key mode
  10442. $this->encryptdata['pubkeys'] = $pubkeys;
  10443. if ($mode == 0) {
  10444. // public-Key Security requires at least 128 bit
  10445. $mode = 1;
  10446. }
  10447. if (!function_exists('openssl_pkcs7_encrypt')) {
  10448. $this->Error('Public-Key Security requires openssl library.');
  10449. }
  10450. // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  10451. $this->encryptdata['pubkey'] = true;
  10452. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  10453. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  10454. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  10455. } else {
  10456. // standard mode (password mode)
  10457. $this->encryptdata['pubkey'] = false;
  10458. $this->encryptdata['Filter'] = 'Standard';
  10459. $this->encryptdata['StmF'] = 'StdCF';
  10460. $this->encryptdata['StrF'] = 'StdCF';
  10461. }
  10462. if ($mode > 1) { // AES
  10463. if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
  10464. $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
  10465. }
  10466. if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
  10467. $this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
  10468. }
  10469. if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  10470. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  10471. }
  10472. if (($mode == 3) AND !function_exists('hash')) {
  10473. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  10474. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  10475. }
  10476. }
  10477. if ($owner_pass === null) {
  10478. $owner_pass = md5(TCPDF_STATIC::getRandomSeed());
  10479. }
  10480. $this->encryptdata['user_password'] = $user_pass;
  10481. $this->encryptdata['owner_password'] = $owner_pass;
  10482. $this->encryptdata['mode'] = $mode;
  10483. switch ($mode) {
  10484. case 0: { // RC4 40 bit
  10485. $this->encryptdata['V'] = 1;
  10486. $this->encryptdata['Length'] = 40;
  10487. $this->encryptdata['CF']['CFM'] = 'V2';
  10488. break;
  10489. }
  10490. case 1: { // RC4 128 bit
  10491. $this->encryptdata['V'] = 2;
  10492. $this->encryptdata['Length'] = 128;
  10493. $this->encryptdata['CF']['CFM'] = 'V2';
  10494. if ($this->encryptdata['pubkey']) {
  10495. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  10496. $this->encryptdata['Recipients'] = array();
  10497. }
  10498. break;
  10499. }
  10500. case 2: { // AES 128 bit
  10501. $this->encryptdata['V'] = 4;
  10502. $this->encryptdata['Length'] = 128;
  10503. $this->encryptdata['CF']['CFM'] = 'AESV2';
  10504. $this->encryptdata['CF']['Length'] = 128;
  10505. if ($this->encryptdata['pubkey']) {
  10506. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10507. $this->encryptdata['Recipients'] = array();
  10508. }
  10509. break;
  10510. }
  10511. case 3: { // AES 256 bit
  10512. $this->encryptdata['V'] = 5;
  10513. $this->encryptdata['Length'] = 256;
  10514. $this->encryptdata['CF']['CFM'] = 'AESV3';
  10515. $this->encryptdata['CF']['Length'] = 256;
  10516. if ($this->encryptdata['pubkey']) {
  10517. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10518. $this->encryptdata['Recipients'] = array();
  10519. }
  10520. break;
  10521. }
  10522. }
  10523. $this->encrypted = true;
  10524. $this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
  10525. $this->_generateencryptionkey();
  10526. }
  10527. // END OF ENCRYPTION FUNCTIONS -------------------------
  10528. // START TRANSFORMATIONS SECTION -----------------------
  10529. /**
  10530. * Starts a 2D tranformation saving current graphic state.
  10531. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  10532. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10533. * @public
  10534. * @since 2.1.000 (2008-01-07)
  10535. * @see StartTransform(), StopTransform()
  10536. */
  10537. public function StartTransform() {
  10538. if ($this->state != 2) {
  10539. return;
  10540. }
  10541. $this->_outSaveGraphicsState();
  10542. if ($this->inxobj) {
  10543. // we are inside an XObject template
  10544. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10545. } else {
  10546. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  10547. }
  10548. ++$this->transfmatrix_key;
  10549. $this->transfmatrix[$this->transfmatrix_key] = array();
  10550. }
  10551. /**
  10552. * Stops a 2D tranformation restoring previous graphic state.
  10553. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  10554. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10555. * @public
  10556. * @since 2.1.000 (2008-01-07)
  10557. * @see StartTransform(), StopTransform()
  10558. */
  10559. public function StopTransform() {
  10560. if ($this->state != 2) {
  10561. return;
  10562. }
  10563. $this->_outRestoreGraphicsState();
  10564. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  10565. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  10566. --$this->transfmatrix_key;
  10567. }
  10568. if ($this->inxobj) {
  10569. // we are inside an XObject template
  10570. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  10571. } else {
  10572. array_pop($this->transfmrk[$this->page]);
  10573. }
  10574. }
  10575. /**
  10576. * Horizontal Scaling.
  10577. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10578. * @param $x (int) abscissa of the scaling center. Default is current x position
  10579. * @param $y (int) ordinate of the scaling center. Default is current y position
  10580. * @public
  10581. * @since 2.1.000 (2008-01-07)
  10582. * @see StartTransform(), StopTransform()
  10583. */
  10584. public function ScaleX($s_x, $x='', $y='') {
  10585. $this->Scale($s_x, 100, $x, $y);
  10586. }
  10587. /**
  10588. * Vertical Scaling.
  10589. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10590. * @param $x (int) abscissa of the scaling center. Default is current x position
  10591. * @param $y (int) ordinate of the scaling center. Default is current y position
  10592. * @public
  10593. * @since 2.1.000 (2008-01-07)
  10594. * @see StartTransform(), StopTransform()
  10595. */
  10596. public function ScaleY($s_y, $x='', $y='') {
  10597. $this->Scale(100, $s_y, $x, $y);
  10598. }
  10599. /**
  10600. * Vertical and horizontal proportional Scaling.
  10601. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  10602. * @param $x (int) abscissa of the scaling center. Default is current x position
  10603. * @param $y (int) ordinate of the scaling center. Default is current y position
  10604. * @public
  10605. * @since 2.1.000 (2008-01-07)
  10606. * @see StartTransform(), StopTransform()
  10607. */
  10608. public function ScaleXY($s, $x='', $y='') {
  10609. $this->Scale($s, $s, $x, $y);
  10610. }
  10611. /**
  10612. * Vertical and horizontal non-proportional Scaling.
  10613. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10614. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10615. * @param $x (int) abscissa of the scaling center. Default is current x position
  10616. * @param $y (int) ordinate of the scaling center. Default is current y position
  10617. * @public
  10618. * @since 2.1.000 (2008-01-07)
  10619. * @see StartTransform(), StopTransform()
  10620. */
  10621. public function Scale($s_x, $s_y, $x='', $y='') {
  10622. if ($x === '') {
  10623. $x = $this->x;
  10624. }
  10625. if ($y === '') {
  10626. $y = $this->y;
  10627. }
  10628. if (($s_x == 0) OR ($s_y == 0)) {
  10629. $this->Error('Please do not use values equal to zero for scaling');
  10630. }
  10631. $y = ($this->h - $y) * $this->k;
  10632. $x *= $this->k;
  10633. //calculate elements of transformation matrix
  10634. $s_x /= 100;
  10635. $s_y /= 100;
  10636. $tm = array();
  10637. $tm[0] = $s_x;
  10638. $tm[1] = 0;
  10639. $tm[2] = 0;
  10640. $tm[3] = $s_y;
  10641. $tm[4] = $x * (1 - $s_x);
  10642. $tm[5] = $y * (1 - $s_y);
  10643. //scale the coordinate system
  10644. $this->Transform($tm);
  10645. }
  10646. /**
  10647. * Horizontal Mirroring.
  10648. * @param $x (int) abscissa of the point. Default is current x position
  10649. * @public
  10650. * @since 2.1.000 (2008-01-07)
  10651. * @see StartTransform(), StopTransform()
  10652. */
  10653. public function MirrorH($x='') {
  10654. $this->Scale(-100, 100, $x);
  10655. }
  10656. /**
  10657. * Verical Mirroring.
  10658. * @param $y (int) ordinate of the point. Default is current y position
  10659. * @public
  10660. * @since 2.1.000 (2008-01-07)
  10661. * @see StartTransform(), StopTransform()
  10662. */
  10663. public function MirrorV($y='') {
  10664. $this->Scale(100, -100, '', $y);
  10665. }
  10666. /**
  10667. * Point reflection mirroring.
  10668. * @param $x (int) abscissa of the point. Default is current x position
  10669. * @param $y (int) ordinate of the point. Default is current y position
  10670. * @public
  10671. * @since 2.1.000 (2008-01-07)
  10672. * @see StartTransform(), StopTransform()
  10673. */
  10674. public function MirrorP($x='',$y='') {
  10675. $this->Scale(-100, -100, $x, $y);
  10676. }
  10677. /**
  10678. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  10679. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  10680. * @param $x (int) abscissa of the point. Default is current x position
  10681. * @param $y (int) ordinate of the point. Default is current y position
  10682. * @public
  10683. * @since 2.1.000 (2008-01-07)
  10684. * @see StartTransform(), StopTransform()
  10685. */
  10686. public function MirrorL($angle=0, $x='',$y='') {
  10687. $this->Scale(-100, 100, $x, $y);
  10688. $this->Rotate(-2*($angle-90), $x, $y);
  10689. }
  10690. /**
  10691. * Translate graphic object horizontally.
  10692. * @param $t_x (int) movement to the right (or left for RTL)
  10693. * @public
  10694. * @since 2.1.000 (2008-01-07)
  10695. * @see StartTransform(), StopTransform()
  10696. */
  10697. public function TranslateX($t_x) {
  10698. $this->Translate($t_x, 0);
  10699. }
  10700. /**
  10701. * Translate graphic object vertically.
  10702. * @param $t_y (int) movement to the bottom
  10703. * @public
  10704. * @since 2.1.000 (2008-01-07)
  10705. * @see StartTransform(), StopTransform()
  10706. */
  10707. public function TranslateY($t_y) {
  10708. $this->Translate(0, $t_y);
  10709. }
  10710. /**
  10711. * Translate graphic object horizontally and vertically.
  10712. * @param $t_x (int) movement to the right
  10713. * @param $t_y (int) movement to the bottom
  10714. * @public
  10715. * @since 2.1.000 (2008-01-07)
  10716. * @see StartTransform(), StopTransform()
  10717. */
  10718. public function Translate($t_x, $t_y) {
  10719. //calculate elements of transformation matrix
  10720. $tm = array();
  10721. $tm[0] = 1;
  10722. $tm[1] = 0;
  10723. $tm[2] = 0;
  10724. $tm[3] = 1;
  10725. $tm[4] = $t_x * $this->k;
  10726. $tm[5] = -$t_y * $this->k;
  10727. //translate the coordinate system
  10728. $this->Transform($tm);
  10729. }
  10730. /**
  10731. * Rotate object.
  10732. * @param $angle (float) angle in degrees for counter-clockwise rotation
  10733. * @param $x (int) abscissa of the rotation center. Default is current x position
  10734. * @param $y (int) ordinate of the rotation center. Default is current y position
  10735. * @public
  10736. * @since 2.1.000 (2008-01-07)
  10737. * @see StartTransform(), StopTransform()
  10738. */
  10739. public function Rotate($angle, $x='', $y='') {
  10740. if ($x === '') {
  10741. $x = $this->x;
  10742. }
  10743. if ($y === '') {
  10744. $y = $this->y;
  10745. }
  10746. $y = ($this->h - $y) * $this->k;
  10747. $x *= $this->k;
  10748. //calculate elements of transformation matrix
  10749. $tm = array();
  10750. $tm[0] = cos(deg2rad($angle));
  10751. $tm[1] = sin(deg2rad($angle));
  10752. $tm[2] = -$tm[1];
  10753. $tm[3] = $tm[0];
  10754. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  10755. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  10756. //rotate the coordinate system around ($x,$y)
  10757. $this->Transform($tm);
  10758. }
  10759. /**
  10760. * Skew horizontally.
  10761. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10762. * @param $x (int) abscissa of the skewing center. default is current x position
  10763. * @param $y (int) ordinate of the skewing center. default is current y position
  10764. * @public
  10765. * @since 2.1.000 (2008-01-07)
  10766. * @see StartTransform(), StopTransform()
  10767. */
  10768. public function SkewX($angle_x, $x='', $y='') {
  10769. $this->Skew($angle_x, 0, $x, $y);
  10770. }
  10771. /**
  10772. * Skew vertically.
  10773. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10774. * @param $x (int) abscissa of the skewing center. default is current x position
  10775. * @param $y (int) ordinate of the skewing center. default is current y position
  10776. * @public
  10777. * @since 2.1.000 (2008-01-07)
  10778. * @see StartTransform(), StopTransform()
  10779. */
  10780. public function SkewY($angle_y, $x='', $y='') {
  10781. $this->Skew(0, $angle_y, $x, $y);
  10782. }
  10783. /**
  10784. * Skew.
  10785. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10786. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10787. * @param $x (int) abscissa of the skewing center. default is current x position
  10788. * @param $y (int) ordinate of the skewing center. default is current y position
  10789. * @public
  10790. * @since 2.1.000 (2008-01-07)
  10791. * @see StartTransform(), StopTransform()
  10792. */
  10793. public function Skew($angle_x, $angle_y, $x='', $y='') {
  10794. if ($x === '') {
  10795. $x = $this->x;
  10796. }
  10797. if ($y === '') {
  10798. $y = $this->y;
  10799. }
  10800. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  10801. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  10802. }
  10803. $x *= $this->k;
  10804. $y = ($this->h - $y) * $this->k;
  10805. //calculate elements of transformation matrix
  10806. $tm = array();
  10807. $tm[0] = 1;
  10808. $tm[1] = tan(deg2rad($angle_y));
  10809. $tm[2] = tan(deg2rad($angle_x));
  10810. $tm[3] = 1;
  10811. $tm[4] = -$tm[2] * $y;
  10812. $tm[5] = -$tm[1] * $x;
  10813. //skew the coordinate system
  10814. $this->Transform($tm);
  10815. }
  10816. /**
  10817. * Apply graphic transformations.
  10818. * @param $tm (array) transformation matrix
  10819. * @protected
  10820. * @since 2.1.000 (2008-01-07)
  10821. * @see StartTransform(), StopTransform()
  10822. */
  10823. protected function Transform($tm) {
  10824. if ($this->state != 2) {
  10825. return;
  10826. }
  10827. $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  10828. // add tranformation matrix
  10829. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  10830. // update transformation mark
  10831. if ($this->inxobj) {
  10832. // we are inside an XObject template
  10833. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  10834. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  10835. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10836. }
  10837. } elseif (end($this->transfmrk[$this->page]) !== false) {
  10838. $key = key($this->transfmrk[$this->page]);
  10839. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  10840. }
  10841. }
  10842. // END TRANSFORMATIONS SECTION -------------------------
  10843. // START GRAPHIC FUNCTIONS SECTION ---------------------
  10844. // The following section is based on the code provided by David Hernandez Sanz
  10845. /**
  10846. * 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.
  10847. * @param $width (float) The width.
  10848. * @public
  10849. * @since 1.0
  10850. * @see Line(), Rect(), Cell(), MultiCell()
  10851. */
  10852. public function SetLineWidth($width) {
  10853. //Set line width
  10854. $this->LineWidth = $width;
  10855. $this->linestyleWidth = sprintf('%F w', ($width * $this->k));
  10856. if ($this->state == 2) {
  10857. $this->_out($this->linestyleWidth);
  10858. }
  10859. }
  10860. /**
  10861. * Returns the current the line width.
  10862. * @return int Line width
  10863. * @public
  10864. * @since 2.1.000 (2008-01-07)
  10865. * @see Line(), SetLineWidth()
  10866. */
  10867. public function GetLineWidth() {
  10868. return $this->LineWidth;
  10869. }
  10870. /**
  10871. * Set line style.
  10872. * @param $style (array) Line style. Array with keys among the following:
  10873. * <ul>
  10874. * <li>width (float): Width of the line in user units.</li>
  10875. * <li>cap (string): Type of cap to put on the line. Possible values are:
  10876. * butt, round, square. The difference between "square" and "butt" is that
  10877. * "square" projects a flat end past the end of the line.</li>
  10878. * <li>join (string): Type of join. Possible values are: miter, round,
  10879. * bevel.</li>
  10880. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  10881. * series of length values, which are the lengths of the on and off dashes.
  10882. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  10883. * 1 off, 2 on, 1 off, ...</li>
  10884. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  10885. * the point at which the pattern starts.</li>
  10886. * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName).</li>
  10887. * </ul>
  10888. * @param $ret (boolean) if true do not send the command.
  10889. * @return string the PDF command
  10890. * @public
  10891. * @since 2.1.000 (2008-01-08)
  10892. */
  10893. public function SetLineStyle($style, $ret=false) {
  10894. $s = ''; // string to be returned
  10895. if (!is_array($style)) {
  10896. return;
  10897. }
  10898. if (isset($style['width'])) {
  10899. $this->LineWidth = $style['width'];
  10900. $this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
  10901. $s .= $this->linestyleWidth.' ';
  10902. }
  10903. if (isset($style['cap'])) {
  10904. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  10905. if (isset($ca[$style['cap']])) {
  10906. $this->linestyleCap = $ca[$style['cap']].' J';
  10907. $s .= $this->linestyleCap.' ';
  10908. }
  10909. }
  10910. if (isset($style['join'])) {
  10911. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  10912. if (isset($ja[$style['join']])) {
  10913. $this->linestyleJoin = $ja[$style['join']].' j';
  10914. $s .= $this->linestyleJoin.' ';
  10915. }
  10916. }
  10917. if (isset($style['dash'])) {
  10918. $dash_string = '';
  10919. if ($style['dash']) {
  10920. if (preg_match('/^.+,/', $style['dash']) > 0) {
  10921. $tab = explode(',', $style['dash']);
  10922. } else {
  10923. $tab = array($style['dash']);
  10924. }
  10925. $dash_string = '';
  10926. foreach ($tab as $i => $v) {
  10927. if ($i) {
  10928. $dash_string .= ' ';
  10929. }
  10930. $dash_string .= sprintf('%F', $v);
  10931. }
  10932. }
  10933. if (!isset($style['phase']) OR !$style['dash']) {
  10934. $style['phase'] = 0;
  10935. }
  10936. $this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
  10937. $s .= $this->linestyleDash.' ';
  10938. }
  10939. if (isset($style['color'])) {
  10940. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  10941. }
  10942. if (!$ret AND ($this->state == 2)) {
  10943. $this->_out($s);
  10944. }
  10945. return $s;
  10946. }
  10947. /**
  10948. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  10949. * @param $x (float) Abscissa of point.
  10950. * @param $y (float) Ordinate of point.
  10951. * @protected
  10952. * @since 2.1.000 (2008-01-08)
  10953. */
  10954. protected function _outPoint($x, $y) {
  10955. if ($this->state == 2) {
  10956. $this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
  10957. }
  10958. }
  10959. /**
  10960. * Append a straight line segment from the current point to the point (x, y).
  10961. * The new current point shall be (x, y).
  10962. * @param $x (float) Abscissa of end point.
  10963. * @param $y (float) Ordinate of end point.
  10964. * @protected
  10965. * @since 2.1.000 (2008-01-08)
  10966. */
  10967. protected function _outLine($x, $y) {
  10968. if ($this->state == 2) {
  10969. $this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
  10970. }
  10971. }
  10972. /**
  10973. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  10974. * @param $x (float) Abscissa of upper-left corner.
  10975. * @param $y (float) Ordinate of upper-left corner.
  10976. * @param $w (float) Width.
  10977. * @param $h (float) Height.
  10978. * @param $op (string) options
  10979. * @protected
  10980. * @since 2.1.000 (2008-01-08)
  10981. */
  10982. protected function _outRect($x, $y, $w, $h, $op) {
  10983. if ($this->state == 2) {
  10984. $this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
  10985. }
  10986. }
  10987. /**
  10988. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x2, y2) as the Bezier control points.
  10989. * The new current point shall be (x3, y3).
  10990. * @param $x1 (float) Abscissa of control point 1.
  10991. * @param $y1 (float) Ordinate of control point 1.
  10992. * @param $x2 (float) Abscissa of control point 2.
  10993. * @param $y2 (float) Ordinate of control point 2.
  10994. * @param $x3 (float) Abscissa of end point.
  10995. * @param $y3 (float) Ordinate of end point.
  10996. * @protected
  10997. * @since 2.1.000 (2008-01-08)
  10998. */
  10999. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  11000. if ($this->state == 2) {
  11001. $this->_out(sprintf('%F %F %F %F %F %F c', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11002. }
  11003. }
  11004. /**
  11005. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using the current point and (x2, y2) as the Bezier control points.
  11006. * The new current point shall be (x3, y3).
  11007. * @param $x2 (float) Abscissa of control point 2.
  11008. * @param $y2 (float) Ordinate of control point 2.
  11009. * @param $x3 (float) Abscissa of end point.
  11010. * @param $y3 (float) Ordinate of end point.
  11011. * @protected
  11012. * @since 4.9.019 (2010-04-26)
  11013. */
  11014. protected function _outCurveV($x2, $y2, $x3, $y3) {
  11015. if ($this->state == 2) {
  11016. $this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11017. }
  11018. }
  11019. /**
  11020. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x3, y3) as the Bezier control points.
  11021. * The new current point shall be (x3, y3).
  11022. * @param $x1 (float) Abscissa of control point 1.
  11023. * @param $y1 (float) Ordinate of control point 1.
  11024. * @param $x3 (float) Abscissa of end point.
  11025. * @param $y3 (float) Ordinate of end point.
  11026. * @protected
  11027. * @since 2.1.000 (2008-01-08)
  11028. */
  11029. protected function _outCurveY($x1, $y1, $x3, $y3) {
  11030. if ($this->state == 2) {
  11031. $this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11032. }
  11033. }
  11034. /**
  11035. * Draws a line between two points.
  11036. * @param $x1 (float) Abscissa of first point.
  11037. * @param $y1 (float) Ordinate of first point.
  11038. * @param $x2 (float) Abscissa of second point.
  11039. * @param $y2 (float) Ordinate of second point.
  11040. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  11041. * @public
  11042. * @since 1.0
  11043. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  11044. */
  11045. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  11046. if ($this->state != 2) {
  11047. return;
  11048. }
  11049. if (is_array($style)) {
  11050. $this->SetLineStyle($style);
  11051. }
  11052. $this->_outPoint($x1, $y1);
  11053. $this->_outLine($x2, $y2);
  11054. $this->_out('S');
  11055. }
  11056. /**
  11057. * Draws a rectangle.
  11058. * @param $x (float) Abscissa of upper-left corner.
  11059. * @param $y (float) Ordinate of upper-left corner.
  11060. * @param $w (float) Width.
  11061. * @param $h (float) Height.
  11062. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11063. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  11064. * <ul>
  11065. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  11066. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  11067. * </ul>
  11068. * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
  11069. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11070. * @public
  11071. * @since 1.0
  11072. * @see SetLineStyle()
  11073. */
  11074. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  11075. if ($this->state != 2) {
  11076. return;
  11077. }
  11078. if (empty($style)) {
  11079. $style = 'S';
  11080. }
  11081. if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
  11082. // set background color
  11083. $this->SetFillColorArray($fill_color);
  11084. }
  11085. if (!empty($border_style)) {
  11086. if (isset($border_style['all']) AND !empty($border_style['all'])) {
  11087. //set global style for border
  11088. $this->SetLineStyle($border_style['all']);
  11089. $border_style = array();
  11090. } else {
  11091. // remove stroke operator from style
  11092. $opnostroke = array('S' => '', 'D' => '', 's' => '', 'd' => '', 'B' => 'F', 'FD' => 'F', 'DF' => 'F', 'B*' => 'F*', 'F*D' => 'F*', 'DF*' => 'F*', 'b' => 'f', 'fd' => 'f', 'df' => 'f', 'b*' => 'f*', 'f*d' => 'f*', 'df*' => 'f*' );
  11093. if (isset($opnostroke[$style])) {
  11094. $style = $opnostroke[$style];
  11095. }
  11096. }
  11097. }
  11098. if (!empty($style)) {
  11099. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11100. $this->_outRect($x, $y, $w, $h, $op);
  11101. }
  11102. if (!empty($border_style)) {
  11103. $border_style2 = array();
  11104. foreach ($border_style as $line => $value) {
  11105. $length = strlen($line);
  11106. for ($i = 0; $i < $length; ++$i) {
  11107. $border_style2[$line[$i]] = $value;
  11108. }
  11109. }
  11110. $border_style = $border_style2;
  11111. if (isset($border_style['L']) AND $border_style['L']) {
  11112. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  11113. }
  11114. if (isset($border_style['T']) AND $border_style['T']) {
  11115. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  11116. }
  11117. if (isset($border_style['R']) AND $border_style['R']) {
  11118. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  11119. }
  11120. if (isset($border_style['B']) AND $border_style['B']) {
  11121. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  11122. }
  11123. }
  11124. }
  11125. /**
  11126. * Draws a Bezier curve.
  11127. * The Bezier curve is a tangent to the line between the control points at
  11128. * either end of the curve.
  11129. * @param $x0 (float) Abscissa of start point.
  11130. * @param $y0 (float) Ordinate of start point.
  11131. * @param $x1 (float) Abscissa of control point 1.
  11132. * @param $y1 (float) Ordinate of control point 1.
  11133. * @param $x2 (float) Abscissa of control point 2.
  11134. * @param $y2 (float) Ordinate of control point 2.
  11135. * @param $x3 (float) Abscissa of end point.
  11136. * @param $y3 (float) Ordinate of end point.
  11137. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11138. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11139. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11140. * @public
  11141. * @see SetLineStyle()
  11142. * @since 2.1.000 (2008-01-08)
  11143. */
  11144. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  11145. if ($this->state != 2) {
  11146. return;
  11147. }
  11148. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11149. $this->SetFillColorArray($fill_color);
  11150. }
  11151. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11152. if ($line_style) {
  11153. $this->SetLineStyle($line_style);
  11154. }
  11155. $this->_outPoint($x0, $y0);
  11156. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11157. $this->_out($op);
  11158. }
  11159. /**
  11160. * Draws a poly-Bezier curve.
  11161. * Each Bezier curve segment is a tangent to the line between the control points at
  11162. * either end of the curve.
  11163. * @param $x0 (float) Abscissa of start point.
  11164. * @param $y0 (float) Ordinate of start point.
  11165. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  11166. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11167. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11168. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11169. * @public
  11170. * @see SetLineStyle()
  11171. * @since 3.0008 (2008-05-12)
  11172. */
  11173. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  11174. if ($this->state != 2) {
  11175. return;
  11176. }
  11177. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11178. $this->SetFillColorArray($fill_color);
  11179. }
  11180. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11181. if ($op == 'f') {
  11182. $line_style = array();
  11183. }
  11184. if ($line_style) {
  11185. $this->SetLineStyle($line_style);
  11186. }
  11187. $this->_outPoint($x0, $y0);
  11188. foreach ($segments as $segment) {
  11189. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  11190. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11191. }
  11192. $this->_out($op);
  11193. }
  11194. /**
  11195. * Draws an ellipse.
  11196. * An ellipse is formed from n Bezier curves.
  11197. * @param $x0 (float) Abscissa of center point.
  11198. * @param $y0 (float) Ordinate of center point.
  11199. * @param $rx (float) Horizontal radius.
  11200. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11201. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11202. * @param $astart: (float) Angle start of draw line. Default value: 0.
  11203. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  11204. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11205. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  11206. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11207. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11208. * @author Nicola Asuni
  11209. * @public
  11210. * @since 2.1.000 (2008-01-08)
  11211. */
  11212. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11213. if ($this->state != 2) {
  11214. return;
  11215. }
  11216. if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
  11217. $ry = $rx;
  11218. }
  11219. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11220. $this->SetFillColorArray($fill_color);
  11221. }
  11222. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11223. if ($op == 'f') {
  11224. $line_style = array();
  11225. }
  11226. if ($line_style) {
  11227. $this->SetLineStyle($line_style);
  11228. }
  11229. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  11230. $this->_out($op);
  11231. }
  11232. /**
  11233. * Append an elliptical arc to the current path.
  11234. * An ellipse is formed from n Bezier curves.
  11235. * @param $xc (float) Abscissa of center point.
  11236. * @param $yc (float) Ordinate of center point.
  11237. * @param $rx (float) Horizontal radius.
  11238. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11239. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  11240. * @param $angs: (float) Angle start of draw line. Default value: 0.
  11241. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  11242. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  11243. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11244. * @param $startpoint (boolean) if true output a starting point.
  11245. * @param $ccw (boolean) if true draws in counter-clockwise.
  11246. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  11247. * @return array bounding box coordinates (x min, y min, x max, y max)
  11248. * @author Nicola Asuni
  11249. * @protected
  11250. * @since 4.9.019 (2010-04-26)
  11251. */
  11252. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  11253. if (($rx <= 0) OR ($ry < 0)) {
  11254. return;
  11255. }
  11256. $k = $this->k;
  11257. if ($nc < 2) {
  11258. $nc = 2;
  11259. }
  11260. $xmin = 2147483647;
  11261. $ymin = 2147483647;
  11262. $xmax = 0;
  11263. $ymax = 0;
  11264. if ($pie) {
  11265. // center of the arc
  11266. $this->_outPoint($xc, $yc);
  11267. }
  11268. $xang = deg2rad((float) $xang);
  11269. $angs = deg2rad((float) $angs);
  11270. $angf = deg2rad((float) $angf);
  11271. if ($svg) {
  11272. $as = $angs;
  11273. $af = $angf;
  11274. } else {
  11275. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  11276. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  11277. }
  11278. if ($as < 0) {
  11279. $as += (2 * M_PI);
  11280. }
  11281. if ($af < 0) {
  11282. $af += (2 * M_PI);
  11283. }
  11284. if ($ccw AND ($as > $af)) {
  11285. // reverse rotation
  11286. $as -= (2 * M_PI);
  11287. } elseif (!$ccw AND ($as < $af)) {
  11288. // reverse rotation
  11289. $af -= (2 * M_PI);
  11290. }
  11291. $total_angle = ($af - $as);
  11292. if ($nc < 2) {
  11293. $nc = 2;
  11294. }
  11295. // total arcs to draw
  11296. $nc *= (2 * abs($total_angle) / M_PI);
  11297. $nc = round($nc) + 1;
  11298. // angle of each arc
  11299. $arcang = ($total_angle / $nc);
  11300. // center point in PDF coordinates
  11301. $x0 = $xc;
  11302. $y0 = ($this->h - $yc);
  11303. // starting angle
  11304. $ang = $as;
  11305. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  11306. $cos_xang = cos($xang);
  11307. $sin_xang = sin($xang);
  11308. $cos_ang = cos($ang);
  11309. $sin_ang = sin($ang);
  11310. // first arc point
  11311. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11312. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11313. // first Bezier control point
  11314. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11315. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11316. if ($pie) {
  11317. // line from center to arc starting point
  11318. $this->_outLine($px1, $this->h - $py1);
  11319. } elseif ($startpoint) {
  11320. // arc starting point
  11321. $this->_outPoint($px1, $this->h - $py1);
  11322. }
  11323. // draw arcs
  11324. for ($i = 1; $i <= $nc; ++$i) {
  11325. // starting angle
  11326. $ang = $as + ($i * $arcang);
  11327. if ($i == $nc) {
  11328. $ang = $af;
  11329. }
  11330. $cos_ang = cos($ang);
  11331. $sin_ang = sin($ang);
  11332. // second arc point
  11333. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11334. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11335. // second Bezier control point
  11336. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11337. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11338. // draw arc
  11339. $cx1 = ($px1 + $qx1);
  11340. $cy1 = ($this->h - ($py1 + $qy1));
  11341. $cx2 = ($px2 - $qx2);
  11342. $cy2 = ($this->h - ($py2 - $qy2));
  11343. $cx3 = $px2;
  11344. $cy3 = ($this->h - $py2);
  11345. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  11346. // get bounding box coordinates
  11347. $xmin = min($xmin, $cx1, $cx2, $cx3);
  11348. $ymin = min($ymin, $cy1, $cy2, $cy3);
  11349. $xmax = max($xmax, $cx1, $cx2, $cx3);
  11350. $ymax = max($ymax, $cy1, $cy2, $cy3);
  11351. // move to next point
  11352. $px1 = $px2;
  11353. $py1 = $py2;
  11354. $qx1 = $qx2;
  11355. $qy1 = $qy2;
  11356. }
  11357. if ($pie) {
  11358. $this->_outLine($xc, $yc);
  11359. // get bounding box coordinates
  11360. $xmin = min($xmin, $xc);
  11361. $ymin = min($ymin, $yc);
  11362. $xmax = max($xmax, $xc);
  11363. $ymax = max($ymax, $yc);
  11364. }
  11365. return array($xmin, $ymin, $xmax, $ymax);
  11366. }
  11367. /**
  11368. * Draws a circle.
  11369. * A circle is formed from n Bezier curves.
  11370. * @param $x0 (float) Abscissa of center point.
  11371. * @param $y0 (float) Ordinate of center point.
  11372. * @param $r (float) Radius.
  11373. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  11374. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  11375. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11376. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11377. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11378. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  11379. * @public
  11380. * @since 2.1.000 (2008-01-08)
  11381. */
  11382. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11383. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  11384. }
  11385. /**
  11386. * Draws a polygonal line
  11387. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11388. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11389. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11390. * <ul>
  11391. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11392. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11393. * </ul>
  11394. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11395. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11396. * @since 4.8.003 (2009-09-15)
  11397. * @public
  11398. */
  11399. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  11400. $this->Polygon($p, $style, $line_style, $fill_color, false);
  11401. }
  11402. /**
  11403. * Draws a polygon.
  11404. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11405. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11406. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11407. * <ul>
  11408. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11409. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11410. * </ul>
  11411. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11412. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11413. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  11414. * @public
  11415. * @since 2.1.000 (2008-01-08)
  11416. */
  11417. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  11418. if ($this->state != 2) {
  11419. return;
  11420. }
  11421. $nc = count($p); // number of coordinates
  11422. $np = $nc / 2; // number of points
  11423. if ($closed) {
  11424. // close polygon by adding the first 2 points at the end (one line)
  11425. for ($i = 0; $i < 4; ++$i) {
  11426. $p[$nc + $i] = $p[$i];
  11427. }
  11428. // copy style for the last added line
  11429. if (isset($line_style[0])) {
  11430. $line_style[$np] = $line_style[0];
  11431. }
  11432. $nc += 4;
  11433. }
  11434. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11435. $this->SetFillColorArray($fill_color);
  11436. }
  11437. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11438. if ($op == 'f') {
  11439. $line_style = array();
  11440. }
  11441. $draw = true;
  11442. if ($line_style) {
  11443. if (isset($line_style['all'])) {
  11444. $this->SetLineStyle($line_style['all']);
  11445. } else {
  11446. $draw = false;
  11447. if ($op == 'B') {
  11448. // draw fill
  11449. $op = 'f';
  11450. $this->_outPoint($p[0], $p[1]);
  11451. for ($i = 2; $i < $nc; $i = $i + 2) {
  11452. $this->_outLine($p[$i], $p[$i + 1]);
  11453. }
  11454. $this->_out($op);
  11455. }
  11456. // draw outline
  11457. $this->_outPoint($p[0], $p[1]);
  11458. for ($i = 2; $i < $nc; $i = $i + 2) {
  11459. $line_num = ($i / 2) - 1;
  11460. if (isset($line_style[$line_num])) {
  11461. if ($line_style[$line_num] != 0) {
  11462. if (is_array($line_style[$line_num])) {
  11463. $this->_out('S');
  11464. $this->SetLineStyle($line_style[$line_num]);
  11465. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  11466. $this->_outLine($p[$i], $p[$i + 1]);
  11467. $this->_out('S');
  11468. $this->_outPoint($p[$i], $p[$i + 1]);
  11469. } else {
  11470. $this->_outLine($p[$i], $p[$i + 1]);
  11471. }
  11472. }
  11473. } else {
  11474. $this->_outLine($p[$i], $p[$i + 1]);
  11475. }
  11476. }
  11477. $this->_out($op);
  11478. }
  11479. }
  11480. if ($draw) {
  11481. $this->_outPoint($p[0], $p[1]);
  11482. for ($i = 2; $i < $nc; $i = $i + 2) {
  11483. $this->_outLine($p[$i], $p[$i + 1]);
  11484. }
  11485. $this->_out($op);
  11486. }
  11487. }
  11488. /**
  11489. * Draws a regular polygon.
  11490. * @param $x0 (float) Abscissa of center point.
  11491. * @param $y0 (float) Ordinate of center point.
  11492. * @param $r: (float) Radius of inscribed circle.
  11493. * @param $ns (integer) Number of sides.
  11494. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  11495. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  11496. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11497. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11498. * <ul>
  11499. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  11500. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  11501. * </ul>
  11502. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11503. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11504. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11505. * <ul>
  11506. * <li>D or empty string: Draw (default).</li>
  11507. * <li>F: Fill.</li>
  11508. * <li>DF or FD: Draw and fill.</li>
  11509. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11510. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11511. * </ul>
  11512. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11513. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11514. * @public
  11515. * @since 2.1.000 (2008-01-08)
  11516. */
  11517. 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()) {
  11518. if (3 > $ns) {
  11519. $ns = 3;
  11520. }
  11521. if ($draw_circle) {
  11522. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11523. }
  11524. $p = array();
  11525. for ($i = 0; $i < $ns; ++$i) {
  11526. $a = $angle + ($i * 360 / $ns);
  11527. $a_rad = deg2rad((float) $a);
  11528. $p[] = $x0 + ($r * sin($a_rad));
  11529. $p[] = $y0 + ($r * cos($a_rad));
  11530. }
  11531. $this->Polygon($p, $style, $line_style, $fill_color);
  11532. }
  11533. /**
  11534. * Draws a star polygon
  11535. * @param $x0 (float) Abscissa of center point.
  11536. * @param $y0 (float) Ordinate of center point.
  11537. * @param $r (float) Radius of inscribed circle.
  11538. * @param $nv (integer) Number of vertices.
  11539. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  11540. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11541. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  11542. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11543. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11544. * <ul>
  11545. * <li>all: Line style of all sides. Array like for
  11546. * SetLineStyle().</li>
  11547. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  11548. * </ul>
  11549. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11550. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11551. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11552. * <ul>
  11553. * <li>D or empty string: Draw (default).</li>
  11554. * <li>F: Fill.</li>
  11555. * <li>DF or FD: Draw and fill.</li>
  11556. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11557. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11558. * </ul>
  11559. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11560. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11561. * @public
  11562. * @since 2.1.000 (2008-01-08)
  11563. */
  11564. 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()) {
  11565. if ($nv < 2) {
  11566. $nv = 2;
  11567. }
  11568. if ($draw_circle) {
  11569. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11570. }
  11571. $p2 = array();
  11572. $visited = array();
  11573. for ($i = 0; $i < $nv; ++$i) {
  11574. $a = $angle + ($i * 360 / $nv);
  11575. $a_rad = deg2rad((float) $a);
  11576. $p2[] = $x0 + ($r * sin($a_rad));
  11577. $p2[] = $y0 + ($r * cos($a_rad));
  11578. $visited[] = false;
  11579. }
  11580. $p = array();
  11581. $i = 0;
  11582. do {
  11583. $p[] = $p2[$i * 2];
  11584. $p[] = $p2[($i * 2) + 1];
  11585. $visited[$i] = true;
  11586. $i += $ng;
  11587. $i %= $nv;
  11588. } while (!$visited[$i]);
  11589. $this->Polygon($p, $style, $line_style, $fill_color);
  11590. }
  11591. /**
  11592. * Draws a rounded rectangle.
  11593. * @param $x (float) Abscissa of upper-left corner.
  11594. * @param $y (float) Ordinate of upper-left corner.
  11595. * @param $w (float) Width.
  11596. * @param $h (float) Height.
  11597. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  11598. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  11599. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11600. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11601. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11602. * @public
  11603. * @since 2.1.000 (2008-01-08)
  11604. */
  11605. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11606. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  11607. }
  11608. /**
  11609. * Draws a rounded rectangle.
  11610. * @param $x (float) Abscissa of upper-left corner.
  11611. * @param $y (float) Ordinate of upper-left corner.
  11612. * @param $w (float) Width.
  11613. * @param $h (float) Height.
  11614. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  11615. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  11616. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  11617. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11618. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11619. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11620. * @public
  11621. * @since 4.9.019 (2010-04-22)
  11622. */
  11623. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11624. if ($this->state != 2) {
  11625. return;
  11626. }
  11627. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  11628. // Not rounded
  11629. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  11630. return;
  11631. }
  11632. // Rounded
  11633. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11634. $this->SetFillColorArray($fill_color);
  11635. }
  11636. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11637. if ($op == 'f') {
  11638. $border_style = array();
  11639. }
  11640. if ($border_style) {
  11641. $this->SetLineStyle($border_style);
  11642. }
  11643. $MyArc = 4 / 3 * (sqrt(2) - 1);
  11644. $this->_outPoint($x + $rx, $y);
  11645. $xc = $x + $w - $rx;
  11646. $yc = $y + $ry;
  11647. $this->_outLine($xc, $y);
  11648. if ($round_corner[0]) {
  11649. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  11650. } else {
  11651. $this->_outLine($x + $w, $y);
  11652. }
  11653. $xc = $x + $w - $rx;
  11654. $yc = $y + $h - $ry;
  11655. $this->_outLine($x + $w, $yc);
  11656. if ($round_corner[1]) {
  11657. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  11658. } else {
  11659. $this->_outLine($x + $w, $y + $h);
  11660. }
  11661. $xc = $x + $rx;
  11662. $yc = $y + $h - $ry;
  11663. $this->_outLine($xc, $y + $h);
  11664. if ($round_corner[2]) {
  11665. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  11666. } else {
  11667. $this->_outLine($x, $y + $h);
  11668. }
  11669. $xc = $x + $rx;
  11670. $yc = $y + $ry;
  11671. $this->_outLine($x, $yc);
  11672. if ($round_corner[3]) {
  11673. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  11674. } else {
  11675. $this->_outLine($x, $y);
  11676. $this->_outLine($x + $rx, $y);
  11677. }
  11678. $this->_out($op);
  11679. }
  11680. /**
  11681. * Draws a grahic arrow.
  11682. * @param $x0 (float) Abscissa of first point.
  11683. * @param $y0 (float) Ordinate of first point.
  11684. * @param $x1 (float) Abscissa of second point.
  11685. * @param $y1 (float) Ordinate of second point.
  11686. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  11687. * @param $arm_size (float) length of arrowhead arms
  11688. * @param $arm_angle (int) angle between an arm and the shaft
  11689. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  11690. * @since 4.6.018 (2009-07-10)
  11691. */
  11692. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  11693. // getting arrow direction angle
  11694. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  11695. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  11696. if ($dir_angle < 0) {
  11697. $dir_angle += (2 * M_PI);
  11698. }
  11699. $arm_angle = deg2rad($arm_angle);
  11700. $sx1 = $x1;
  11701. $sy1 = $y1;
  11702. if ($head_style > 0) {
  11703. // calculate the stopping point for the arrow shaft
  11704. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  11705. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  11706. }
  11707. // main arrow line / shaft
  11708. $this->Line($x0, $y0, $sx1, $sy1);
  11709. // left arrowhead arm tip
  11710. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  11711. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  11712. // right arrowhead arm tip
  11713. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  11714. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  11715. $mode = 'D';
  11716. $style = array();
  11717. switch ($head_style) {
  11718. case 0: {
  11719. // draw only arrowhead arms
  11720. $mode = 'D';
  11721. $style = array(1, 1, 0);
  11722. break;
  11723. }
  11724. case 1: {
  11725. // draw closed arrowhead, but no fill
  11726. $mode = 'D';
  11727. break;
  11728. }
  11729. case 2: {
  11730. // closed and filled arrowhead
  11731. $mode = 'DF';
  11732. break;
  11733. }
  11734. case 3: {
  11735. // filled arrowhead
  11736. $mode = 'F';
  11737. break;
  11738. }
  11739. }
  11740. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  11741. }
  11742. // END GRAPHIC FUNCTIONS SECTION -----------------------
  11743. /**
  11744. * Add a Named Destination.
  11745. * NOTE: destination names are unique, so only last entry will be saved.
  11746. * @param $name (string) Destination name.
  11747. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  11748. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11749. * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
  11750. * @return (string) Stripped named destination identifier or false in case of error.
  11751. * @public
  11752. * @author Christian Deligant, Nicola Asuni
  11753. * @since 5.9.097 (2011-06-23)
  11754. */
  11755. public function setDestination($name, $y=-1, $page='', $x=-1) {
  11756. // remove unsupported characters
  11757. $name = TCPDF_STATIC::encodeNameObject($name);
  11758. if (TCPDF_STATIC::empty_string($name)) {
  11759. return false;
  11760. }
  11761. if ($y == -1) {
  11762. $y = $this->GetY();
  11763. } elseif ($y < 0) {
  11764. $y = 0;
  11765. } elseif ($y > $this->h) {
  11766. $y = $this->h;
  11767. }
  11768. if ($x == -1) {
  11769. $x = $this->GetX();
  11770. } elseif ($x < 0) {
  11771. $x = 0;
  11772. } elseif ($x > $this->w) {
  11773. $x = $this->w;
  11774. }
  11775. $fixed = false;
  11776. if (!empty($page) AND ($page[0] == '*')) {
  11777. $page = intval(substr($page, 1));
  11778. // this page number will not be changed when moving/add/deleting pages
  11779. $fixed = true;
  11780. }
  11781. if (empty($page)) {
  11782. $page = $this->PageNo();
  11783. if (empty($page)) {
  11784. return;
  11785. }
  11786. }
  11787. $this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
  11788. return $name;
  11789. }
  11790. /**
  11791. * Return the Named Destination array.
  11792. * @return (array) Named Destination array.
  11793. * @public
  11794. * @author Nicola Asuni
  11795. * @since 5.9.097 (2011-06-23)
  11796. */
  11797. public function getDestination() {
  11798. return $this->dests;
  11799. }
  11800. /**
  11801. * Insert Named Destinations.
  11802. * @protected
  11803. * @author Johannes G\FCntert, Nicola Asuni
  11804. * @since 5.9.098 (2011-06-23)
  11805. */
  11806. protected function _putdests() {
  11807. if (empty($this->dests)) {
  11808. return;
  11809. }
  11810. $this->n_dests = $this->_newobj();
  11811. $out = ' <<';
  11812. foreach($this->dests as $name => $o) {
  11813. $out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  11814. }
  11815. $out .= ' >>';
  11816. $out .= "\n".'endobj';
  11817. $this->_out($out);
  11818. }
  11819. /**
  11820. * Adds a bookmark - alias for Bookmark().
  11821. * @param $txt (string) Bookmark description.
  11822. * @param $level (int) Bookmark level (minimum value is 0).
  11823. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11824. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11825. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11826. * @param $color (array) RGB color array (values from 0 to 255).
  11827. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11828. * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
  11829. * @public
  11830. */
  11831. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11832. $this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
  11833. }
  11834. /**
  11835. * Adds a bookmark.
  11836. * @param $txt (string) Bookmark description.
  11837. * @param $level (int) Bookmark level (minimum value is 0).
  11838. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11839. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11840. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11841. * @param $color (array) RGB color array (values from 0 to 255).
  11842. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11843. * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
  11844. * @public
  11845. * @since 2.1.002 (2008-02-12)
  11846. */
  11847. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11848. if ($level < 0) {
  11849. $level = 0;
  11850. }
  11851. if (isset($this->outlines[0])) {
  11852. $lastoutline = end($this->outlines);
  11853. $maxlevel = $lastoutline['l'] + 1;
  11854. } else {
  11855. $maxlevel = 0;
  11856. }
  11857. if ($level > $maxlevel) {
  11858. $level = $maxlevel;
  11859. }
  11860. if ($y == -1) {
  11861. $y = $this->GetY();
  11862. } elseif ($y < 0) {
  11863. $y = 0;
  11864. } elseif ($y > $this->h) {
  11865. $y = $this->h;
  11866. }
  11867. if ($x == -1) {
  11868. $x = $this->GetX();
  11869. } elseif ($x < 0) {
  11870. $x = 0;
  11871. } elseif ($x > $this->w) {
  11872. $x = $this->w;
  11873. }
  11874. $fixed = false;
  11875. if (!empty($page) AND ($page[0] == '*')) {
  11876. $page = intval(substr($page, 1));
  11877. // this page number will not be changed when moving/add/deleting pages
  11878. $fixed = true;
  11879. }
  11880. if (empty($page)) {
  11881. $page = $this->PageNo();
  11882. if (empty($page)) {
  11883. return;
  11884. }
  11885. }
  11886. $this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
  11887. }
  11888. /**
  11889. * Sort bookmarks for page and key.
  11890. * @protected
  11891. * @since 5.9.119 (2011-09-19)
  11892. */
  11893. protected function sortBookmarks() {
  11894. // get sorting columns
  11895. $outline_p = array();
  11896. $outline_y = array();
  11897. foreach ($this->outlines as $key => $row) {
  11898. $outline_p[$key] = $row['p'];
  11899. $outline_k[$key] = $key;
  11900. }
  11901. // sort outlines by page and original position
  11902. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  11903. }
  11904. /**
  11905. * Create a bookmark PDF string.
  11906. * @protected
  11907. * @author Olivier Plathey, Nicola Asuni
  11908. * @since 2.1.002 (2008-02-12)
  11909. */
  11910. protected function _putbookmarks() {
  11911. $nb = count($this->outlines);
  11912. if ($nb == 0) {
  11913. return;
  11914. }
  11915. // sort bookmarks
  11916. $this->sortBookmarks();
  11917. $lru = array();
  11918. $level = 0;
  11919. foreach ($this->outlines as $i => $o) {
  11920. if ($o['l'] > 0) {
  11921. $parent = $lru[($o['l'] - 1)];
  11922. //Set parent and last pointers
  11923. $this->outlines[$i]['parent'] = $parent;
  11924. $this->outlines[$parent]['last'] = $i;
  11925. if ($o['l'] > $level) {
  11926. //Level increasing: set first pointer
  11927. $this->outlines[$parent]['first'] = $i;
  11928. }
  11929. } else {
  11930. $this->outlines[$i]['parent'] = $nb;
  11931. }
  11932. if (($o['l'] <= $level) AND ($i > 0)) {
  11933. //Set prev and next pointers
  11934. $prev = $lru[$o['l']];
  11935. $this->outlines[$prev]['next'] = $i;
  11936. $this->outlines[$i]['prev'] = $prev;
  11937. }
  11938. $lru[$o['l']] = $i;
  11939. $level = $o['l'];
  11940. }
  11941. //Outline items
  11942. $n = $this->n + 1;
  11943. $nltags = '/<br[\s]?\/>|<\/(blockquote|dd|dl|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|p|pre|ul|tcpdf|table|tr|td)>/si';
  11944. foreach ($this->outlines as $i => $o) {
  11945. $oid = $this->_newobj();
  11946. // covert HTML title to string
  11947. $title = preg_replace($nltags, "\n", $o['t']);
  11948. $title = preg_replace("/[\r]+/si", '', $title);
  11949. $title = preg_replace("/[\n]+/si", "\n", $title);
  11950. $title = strip_tags($title);
  11951. $title = $this->stringTrim($title);
  11952. $out = '<</Title '.$this->_textstring($title, $oid);
  11953. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  11954. if (isset($o['prev'])) {
  11955. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  11956. }
  11957. if (isset($o['next'])) {
  11958. $out .= ' /Next '.($n + $o['next']).' 0 R';
  11959. }
  11960. if (isset($o['first'])) {
  11961. $out .= ' /First '.($n + $o['first']).' 0 R';
  11962. }
  11963. if (isset($o['last'])) {
  11964. $out .= ' /Last '.($n + $o['last']).' 0 R';
  11965. }
  11966. if (isset($o['u']) AND !empty($o['u'])) {
  11967. // link
  11968. if (is_string($o['u'])) {
  11969. if ($o['u'][0] == '#') {
  11970. // internal destination
  11971. $out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
  11972. } elseif ($o['u'][0] == '%') {
  11973. // embedded PDF file
  11974. $filename = basename(substr($o['u'], 1));
  11975. $out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  11976. } elseif ($o['u'][0] == '*') {
  11977. // embedded generic file
  11978. $filename = basename(substr($o['u'], 1));
  11979. $jsa = 'var D=event.target.doc;var MyData=D.dataObjects;for (var i in MyData) if (MyData[i].path=="'.$filename.'") D.exportDataObject( { cName : MyData[i].name, nLaunch : 2});';
  11980. $out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
  11981. } else {
  11982. // external URI link
  11983. $out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
  11984. }
  11985. } elseif (isset($this->links[$o['u']])) {
  11986. // internal link ID
  11987. $l = $this->links[$o['u']];
  11988. if (isset($this->page_obj_id[($l['p'])])) {
  11989. $out .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l['p'])], ($this->pagedim[$l['p']]['h'] - ($l['y'] * $this->k)));
  11990. }
  11991. }
  11992. } elseif (isset($this->page_obj_id[($o['p'])])) {
  11993. // link to a page
  11994. $out .= ' '.sprintf('/Dest [%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  11995. }
  11996. // set font style
  11997. $style = 0;
  11998. if (!empty($o['s'])) {
  11999. // bold
  12000. if (strpos($o['s'], 'B') !== false) {
  12001. $style |= 2;
  12002. }
  12003. // oblique
  12004. if (strpos($o['s'], 'I') !== false) {
  12005. $style |= 1;
  12006. }
  12007. }
  12008. $out .= sprintf(' /F %d', $style);
  12009. // set bookmark color
  12010. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  12011. $color = array_values($o['c']);
  12012. $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  12013. } else {
  12014. // black
  12015. $out .= ' /C [0.0 0.0 0.0]';
  12016. }
  12017. $out .= ' /Count 0'; // normally closed item
  12018. $out .= ' >>';
  12019. $out .= "\n".'endobj';
  12020. $this->_out($out);
  12021. }
  12022. //Outline root
  12023. $this->OutlineRoot = $this->_newobj();
  12024. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  12025. }
  12026. // --- JAVASCRIPT ------------------------------------------------------
  12027. /**
  12028. * Adds a javascript
  12029. * @param $script (string) Javascript code
  12030. * @public
  12031. * @author Johannes G\FCntert, Nicola Asuni
  12032. * @since 2.1.002 (2008-02-12)
  12033. */
  12034. public function IncludeJS($script) {
  12035. $this->javascript .= $script;
  12036. }
  12037. /**
  12038. * Adds a javascript object and return object ID
  12039. * @param $script (string) Javascript code
  12040. * @param $onload (boolean) if true executes this object when opening the document
  12041. * @return int internal object ID
  12042. * @public
  12043. * @author Nicola Asuni
  12044. * @since 4.8.000 (2009-09-07)
  12045. */
  12046. public function addJavascriptObject($script, $onload=false) {
  12047. if ($this->pdfa_mode) {
  12048. // javascript is not allowed in PDF/A mode
  12049. return false;
  12050. }
  12051. ++$this->n;
  12052. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  12053. return $this->n;
  12054. }
  12055. /**
  12056. * Create a javascript PDF string.
  12057. * @protected
  12058. * @author Johannes G\FCntert, Nicola Asuni
  12059. * @since 2.1.002 (2008-02-12)
  12060. */
  12061. protected function _putjavascript() {
  12062. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  12063. return;
  12064. }
  12065. if (strpos($this->javascript, 'this.addField') > 0) {
  12066. if (!$this->ur['enabled']) {
  12067. //$this->setUserRights();
  12068. }
  12069. // the following two lines are used to avoid form fields duplication after saving
  12070. // The addField method only works when releasing user rights (UR3)
  12071. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  12072. $jsb = "getField('tcpdfdocsaved').value='saved';";
  12073. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  12074. }
  12075. // name tree for javascript
  12076. $this->n_js = '<< /Names [';
  12077. if (!empty($this->javascript)) {
  12078. $this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  12079. }
  12080. if (!empty($this->js_objects)) {
  12081. foreach ($this->js_objects as $key => $val) {
  12082. if ($val['onload']) {
  12083. $this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
  12084. }
  12085. }
  12086. }
  12087. $this->n_js .= ' ] >>';
  12088. // default Javascript object
  12089. if (!empty($this->javascript)) {
  12090. $obj_id = $this->_newobj();
  12091. $out = '<< /S /JavaScript';
  12092. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  12093. $out .= ' >>';
  12094. $out .= "\n".'endobj';
  12095. $this->_out($out);
  12096. }
  12097. // additional Javascript objects
  12098. if (!empty($this->js_objects)) {
  12099. foreach ($this->js_objects as $key => $val) {
  12100. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  12101. $this->_out($out);
  12102. }
  12103. }
  12104. }
  12105. /**
  12106. * Adds a javascript form field.
  12107. * @param $type (string) field type
  12108. * @param $name (string) field name
  12109. * @param $x (int) horizontal position
  12110. * @param $y (int) vertical position
  12111. * @param $w (int) width
  12112. * @param $h (int) height
  12113. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12114. * @protected
  12115. * @author Denis Van Nuffelen, Nicola Asuni
  12116. * @since 2.1.002 (2008-02-12)
  12117. */
  12118. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  12119. if ($this->rtl) {
  12120. $x = $x - $w;
  12121. }
  12122. // the followind avoid fields duplication after saving the document
  12123. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  12124. $k = $this->k;
  12125. $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%F,%F,%F,%F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
  12126. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  12127. foreach($prop as $key => $val) {
  12128. if (strcmp(substr($key, -5), 'Color') == 0) {
  12129. $val = TCPDF_COLORS::_JScolor($val);
  12130. } else {
  12131. $val = "'".$val."'";
  12132. }
  12133. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  12134. }
  12135. if ($this->rtl) {
  12136. $this->x -= $w;
  12137. } else {
  12138. $this->x += $w;
  12139. }
  12140. $this->javascript .= '}';
  12141. }
  12142. // --- FORM FIELDS -----------------------------------------------------
  12143. /**
  12144. * Set default properties for form fields.
  12145. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12146. * @public
  12147. * @author Nicola Asuni
  12148. * @since 4.8.000 (2009-09-06)
  12149. */
  12150. public function setFormDefaultProp($prop=array()) {
  12151. $this->default_form_prop = $prop;
  12152. }
  12153. /**
  12154. * Return the default properties for form fields.
  12155. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12156. * @public
  12157. * @author Nicola Asuni
  12158. * @since 4.8.000 (2009-09-06)
  12159. */
  12160. public function getFormDefaultProp() {
  12161. return $this->default_form_prop;
  12162. }
  12163. /**
  12164. * Creates a text field
  12165. * @param $name (string) field name
  12166. * @param $w (float) Width of the rectangle
  12167. * @param $h (float) Height of the rectangle
  12168. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12169. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12170. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12171. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12172. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12173. * @public
  12174. * @author Nicola Asuni
  12175. * @since 4.8.000 (2009-09-07)
  12176. */
  12177. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12178. if ($x === '') {
  12179. $x = $this->x;
  12180. }
  12181. if ($y === '') {
  12182. $y = $this->y;
  12183. }
  12184. // check page for no-write regions and adapt page margins if necessary
  12185. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12186. if ($js) {
  12187. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  12188. return;
  12189. }
  12190. // get default style
  12191. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12192. // get annotation data
  12193. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12194. // set default appearance stream
  12195. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12196. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12197. $popt['da'] = $fontstyle;
  12198. // build appearance stream
  12199. $popt['ap'] = array();
  12200. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12201. $text = '';
  12202. if (isset($prop['value']) AND !empty($prop['value'])) {
  12203. $text = $prop['value'];
  12204. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  12205. $text = $opt['v'];
  12206. }
  12207. $tmpid = $this->startTemplate($w, $h, false);
  12208. $align = '';
  12209. if (isset($popt['q'])) {
  12210. switch ($popt['q']) {
  12211. case 0: {
  12212. $align = 'L';
  12213. break;
  12214. }
  12215. case 1: {
  12216. $align = 'C';
  12217. break;
  12218. }
  12219. case 2: {
  12220. $align = 'R';
  12221. break;
  12222. }
  12223. default: {
  12224. $align = '';
  12225. break;
  12226. }
  12227. }
  12228. }
  12229. $this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12230. $this->endTemplate();
  12231. --$this->n;
  12232. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12233. unset($this->xobjects[$tmpid]);
  12234. $popt['ap']['n'] .= 'Q EMC';
  12235. // merge options
  12236. $opt = array_merge($popt, $opt);
  12237. // remove some conflicting options
  12238. unset($opt['bs']);
  12239. // set remaining annotation data
  12240. $opt['Subtype'] = 'Widget';
  12241. $opt['ft'] = 'Tx';
  12242. $opt['t'] = $name;
  12243. // Additional annotation's parameters (check _putannotsobj() method):
  12244. //$opt['f']
  12245. //$opt['as']
  12246. //$opt['bs']
  12247. //$opt['be']
  12248. //$opt['c']
  12249. //$opt['border']
  12250. //$opt['h']
  12251. //$opt['mk'];
  12252. //$opt['mk']['r']
  12253. //$opt['mk']['bc'];
  12254. //$opt['mk']['bg'];
  12255. unset($opt['mk']['ca']);
  12256. unset($opt['mk']['rc']);
  12257. unset($opt['mk']['ac']);
  12258. unset($opt['mk']['i']);
  12259. unset($opt['mk']['ri']);
  12260. unset($opt['mk']['ix']);
  12261. unset($opt['mk']['if']);
  12262. //$opt['mk']['if']['sw'];
  12263. //$opt['mk']['if']['s'];
  12264. //$opt['mk']['if']['a'];
  12265. //$opt['mk']['if']['fb'];
  12266. unset($opt['mk']['tp']);
  12267. //$opt['tu']
  12268. //$opt['tm']
  12269. //$opt['ff']
  12270. //$opt['v']
  12271. //$opt['dv']
  12272. //$opt['a']
  12273. //$opt['aa']
  12274. //$opt['q']
  12275. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12276. if ($this->rtl) {
  12277. $this->x -= $w;
  12278. } else {
  12279. $this->x += $w;
  12280. }
  12281. }
  12282. /**
  12283. * Creates a RadioButton field.
  12284. * @param $name (string) Field name.
  12285. * @param $w (int) Width of the radio button.
  12286. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12287. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12288. * @param $onvalue (string) Value to be returned if selected.
  12289. * @param $checked (boolean) Define the initial state.
  12290. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12291. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12292. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12293. * @public
  12294. * @author Nicola Asuni
  12295. * @since 4.8.000 (2009-09-07)
  12296. */
  12297. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  12298. if ($x === '') {
  12299. $x = $this->x;
  12300. }
  12301. if ($y === '') {
  12302. $y = $this->y;
  12303. }
  12304. // check page for no-write regions and adapt page margins if necessary
  12305. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12306. if ($js) {
  12307. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  12308. return;
  12309. }
  12310. if (TCPDF_STATIC::empty_string($onvalue)) {
  12311. $onvalue = 'On';
  12312. }
  12313. if ($checked) {
  12314. $defval = $onvalue;
  12315. } else {
  12316. $defval = 'Off';
  12317. }
  12318. // set font
  12319. $font = 'zapfdingbats';
  12320. if ($this->pdfa_mode) {
  12321. // all fonts must be embedded
  12322. $font = 'pdfa'.$font;
  12323. }
  12324. $this->AddFont($font);
  12325. $tmpfont = $this->getFontBuffer($font);
  12326. // set data for parent group
  12327. if (!isset($this->radiobutton_groups[$this->page])) {
  12328. $this->radiobutton_groups[$this->page] = array();
  12329. }
  12330. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  12331. $this->radiobutton_groups[$this->page][$name] = array();
  12332. ++$this->n;
  12333. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  12334. $this->radio_groups[] = $this->n;
  12335. }
  12336. $kid = ($this->n + 1);
  12337. // save object ID to be added on Kids entry on parent object
  12338. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  12339. // get default style
  12340. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12341. $prop['NoToggleToOff'] = 'true';
  12342. $prop['Radio'] = 'true';
  12343. $prop['borderStyle'] = 'inset';
  12344. // get annotation data
  12345. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12346. // set additional default options
  12347. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12348. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12349. $popt['da'] = $fontstyle;
  12350. // build appearance stream
  12351. $popt['ap'] = array();
  12352. $popt['ap']['n'] = array();
  12353. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
  12354. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12355. $popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(108).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12356. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(109).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12357. if (!isset($popt['mk'])) {
  12358. $popt['mk'] = array();
  12359. }
  12360. $popt['mk']['ca'] = '(l)';
  12361. // merge options
  12362. $opt = array_merge($popt, $opt);
  12363. // set remaining annotation data
  12364. $opt['Subtype'] = 'Widget';
  12365. $opt['ft'] = 'Btn';
  12366. if ($checked) {
  12367. $opt['v'] = array('/'.$onvalue);
  12368. $opt['as'] = $onvalue;
  12369. } else {
  12370. $opt['as'] = 'Off';
  12371. }
  12372. // store readonly flag
  12373. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  12374. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  12375. }
  12376. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  12377. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12378. if ($this->rtl) {
  12379. $this->x -= $w;
  12380. } else {
  12381. $this->x += $w;
  12382. }
  12383. }
  12384. /**
  12385. * Creates a List-box field
  12386. * @param $name (string) field name
  12387. * @param $w (int) width
  12388. * @param $h (int) height
  12389. * @param $values (array) array containing the list of values.
  12390. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12391. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12392. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12393. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12394. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12395. * @public
  12396. * @author Nicola Asuni
  12397. * @since 4.8.000 (2009-09-07)
  12398. */
  12399. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12400. if ($x === '') {
  12401. $x = $this->x;
  12402. }
  12403. if ($y === '') {
  12404. $y = $this->y;
  12405. }
  12406. // check page for no-write regions and adapt page margins if necessary
  12407. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12408. if ($js) {
  12409. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  12410. $s = '';
  12411. foreach ($values as $value) {
  12412. if (is_array($value)) {
  12413. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12414. } else {
  12415. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12416. }
  12417. }
  12418. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12419. return;
  12420. }
  12421. // get default style
  12422. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12423. // get annotation data
  12424. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12425. // set additional default values
  12426. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12427. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12428. $popt['da'] = $fontstyle;
  12429. // build appearance stream
  12430. $popt['ap'] = array();
  12431. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12432. $text = '';
  12433. foreach($values as $item) {
  12434. if (is_array($item)) {
  12435. $text .= $item[1]."\n";
  12436. } else {
  12437. $text .= $item."\n";
  12438. }
  12439. }
  12440. $tmpid = $this->startTemplate($w, $h, false);
  12441. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12442. $this->endTemplate();
  12443. --$this->n;
  12444. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12445. unset($this->xobjects[$tmpid]);
  12446. $popt['ap']['n'] .= 'Q EMC';
  12447. // merge options
  12448. $opt = array_merge($popt, $opt);
  12449. // set remaining annotation data
  12450. $opt['Subtype'] = 'Widget';
  12451. $opt['ft'] = 'Ch';
  12452. $opt['t'] = $name;
  12453. $opt['opt'] = $values;
  12454. unset($opt['mk']['ca']);
  12455. unset($opt['mk']['rc']);
  12456. unset($opt['mk']['ac']);
  12457. unset($opt['mk']['i']);
  12458. unset($opt['mk']['ri']);
  12459. unset($opt['mk']['ix']);
  12460. unset($opt['mk']['if']);
  12461. unset($opt['mk']['tp']);
  12462. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12463. if ($this->rtl) {
  12464. $this->x -= $w;
  12465. } else {
  12466. $this->x += $w;
  12467. }
  12468. }
  12469. /**
  12470. * Creates a Combo-box field
  12471. * @param $name (string) field name
  12472. * @param $w (int) width
  12473. * @param $h (int) height
  12474. * @param $values (array) array containing the list of values.
  12475. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12476. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12477. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12478. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12479. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12480. * @public
  12481. * @author Nicola Asuni
  12482. * @since 4.8.000 (2009-09-07)
  12483. */
  12484. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12485. if ($x === '') {
  12486. $x = $this->x;
  12487. }
  12488. if ($y === '') {
  12489. $y = $this->y;
  12490. }
  12491. // check page for no-write regions and adapt page margins if necessary
  12492. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12493. if ($js) {
  12494. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  12495. $s = '';
  12496. foreach ($values as $value) {
  12497. if (is_array($value)) {
  12498. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12499. } else {
  12500. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12501. }
  12502. }
  12503. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12504. return;
  12505. }
  12506. // get default style
  12507. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12508. $prop['Combo'] = true;
  12509. // get annotation data
  12510. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12511. // set additional default options
  12512. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12513. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12514. $popt['da'] = $fontstyle;
  12515. // build appearance stream
  12516. $popt['ap'] = array();
  12517. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12518. $text = '';
  12519. foreach($values as $item) {
  12520. if (is_array($item)) {
  12521. $text .= $item[1]."\n";
  12522. } else {
  12523. $text .= $item."\n";
  12524. }
  12525. }
  12526. $tmpid = $this->startTemplate($w, $h, false);
  12527. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12528. $this->endTemplate();
  12529. --$this->n;
  12530. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12531. unset($this->xobjects[$tmpid]);
  12532. $popt['ap']['n'] .= 'Q EMC';
  12533. // merge options
  12534. $opt = array_merge($popt, $opt);
  12535. // set remaining annotation data
  12536. $opt['Subtype'] = 'Widget';
  12537. $opt['ft'] = 'Ch';
  12538. $opt['t'] = $name;
  12539. $opt['opt'] = $values;
  12540. unset($opt['mk']['ca']);
  12541. unset($opt['mk']['rc']);
  12542. unset($opt['mk']['ac']);
  12543. unset($opt['mk']['i']);
  12544. unset($opt['mk']['ri']);
  12545. unset($opt['mk']['ix']);
  12546. unset($opt['mk']['if']);
  12547. unset($opt['mk']['tp']);
  12548. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12549. if ($this->rtl) {
  12550. $this->x -= $w;
  12551. } else {
  12552. $this->x += $w;
  12553. }
  12554. }
  12555. /**
  12556. * Creates a CheckBox field
  12557. * @param $name (string) field name
  12558. * @param $w (int) width
  12559. * @param $checked (boolean) define the initial state.
  12560. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12561. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12562. * @param $onvalue (string) value to be returned if selected.
  12563. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12564. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12565. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12566. * @public
  12567. * @author Nicola Asuni
  12568. * @since 4.8.000 (2009-09-07)
  12569. */
  12570. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  12571. if ($x === '') {
  12572. $x = $this->x;
  12573. }
  12574. if ($y === '') {
  12575. $y = $this->y;
  12576. }
  12577. // check page for no-write regions and adapt page margins if necessary
  12578. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12579. if ($js) {
  12580. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  12581. return;
  12582. }
  12583. if (!isset($prop['value'])) {
  12584. $prop['value'] = array('Yes');
  12585. }
  12586. // get default style
  12587. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12588. $prop['borderStyle'] = 'inset';
  12589. // get annotation data
  12590. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12591. // set additional default options
  12592. $font = 'zapfdingbats';
  12593. if ($this->pdfa_mode) {
  12594. // all fonts must be embedded
  12595. $font = 'pdfa'.$font;
  12596. }
  12597. $this->AddFont($font);
  12598. $tmpfont = $this->getFontBuffer($font);
  12599. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12600. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12601. $popt['da'] = $fontstyle;
  12602. // build appearance stream
  12603. $popt['ap'] = array();
  12604. $popt['ap']['n'] = array();
  12605. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
  12606. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12607. $popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(110).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12608. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(111).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12609. // merge options
  12610. $opt = array_merge($popt, $opt);
  12611. // set remaining annotation data
  12612. $opt['Subtype'] = 'Widget';
  12613. $opt['ft'] = 'Btn';
  12614. $opt['t'] = $name;
  12615. if (TCPDF_STATIC::empty_string($onvalue)) {
  12616. $onvalue = 'Yes';
  12617. }
  12618. $opt['opt'] = array($onvalue);
  12619. if ($checked) {
  12620. $opt['v'] = array('/Yes');
  12621. $opt['as'] = 'Yes';
  12622. } else {
  12623. $opt['v'] = array('/Off');
  12624. $opt['as'] = 'Off';
  12625. }
  12626. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12627. if ($this->rtl) {
  12628. $this->x -= $w;
  12629. } else {
  12630. $this->x += $w;
  12631. }
  12632. }
  12633. /**
  12634. * Creates a button field
  12635. * @param $name (string) field name
  12636. * @param $w (int) width
  12637. * @param $h (int) height
  12638. * @param $caption (string) caption.
  12639. * @param $action (mixed) action triggered by pressing the button. Use a string to specify a javascript action. Use an array to specify a form action options as on section 12.7.5 of PDF32000_2008.
  12640. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12641. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12642. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12643. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12644. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12645. * @public
  12646. * @author Nicola Asuni
  12647. * @since 4.8.000 (2009-09-07)
  12648. */
  12649. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12650. if ($x === '') {
  12651. $x = $this->x;
  12652. }
  12653. if ($y === '') {
  12654. $y = $this->y;
  12655. }
  12656. // check page for no-write regions and adapt page margins if necessary
  12657. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12658. if ($js) {
  12659. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  12660. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  12661. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  12662. $this->javascript .= 'f'.$name.".highlight='push';\n";
  12663. $this->javascript .= 'f'.$name.".print=false;\n";
  12664. return;
  12665. }
  12666. // get default style
  12667. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12668. $prop['Pushbutton'] = 'true';
  12669. $prop['highlight'] = 'push';
  12670. $prop['display'] = 'display.noPrint';
  12671. // get annotation data
  12672. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12673. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12674. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12675. $popt['da'] = $fontstyle;
  12676. // build appearance stream
  12677. $popt['ap'] = array();
  12678. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12679. $tmpid = $this->startTemplate($w, $h, false);
  12680. $bw = (2 / $this->k); // border width
  12681. $border = array(
  12682. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12683. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  12684. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12685. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  12686. $this->SetFillColor(204);
  12687. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  12688. $this->endTemplate();
  12689. --$this->n;
  12690. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12691. unset($this->xobjects[$tmpid]);
  12692. $popt['ap']['n'] .= 'Q EMC';
  12693. // set additional default options
  12694. if (!isset($popt['mk'])) {
  12695. $popt['mk'] = array();
  12696. }
  12697. $ann_obj_id = ($this->n + 1);
  12698. if (!empty($action) AND !is_array($action)) {
  12699. $ann_obj_id = ($this->n + 2);
  12700. }
  12701. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  12702. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  12703. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  12704. // merge options
  12705. $opt = array_merge($popt, $opt);
  12706. // set remaining annotation data
  12707. $opt['Subtype'] = 'Widget';
  12708. $opt['ft'] = 'Btn';
  12709. $opt['t'] = $caption;
  12710. $opt['v'] = $name;
  12711. if (!empty($action)) {
  12712. if (is_array($action)) {
  12713. // form action options as on section 12.7.5 of PDF32000_2008.
  12714. $opt['aa'] = '/D <<';
  12715. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  12716. foreach ($action AS $key => $val) {
  12717. if (($key == 'S') AND in_array($val, $bmode)) {
  12718. $opt['aa'] .= ' /S /'.$val;
  12719. } elseif (($key == 'F') AND (!empty($val))) {
  12720. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  12721. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  12722. $opt['aa'] .= ' /Fields [';
  12723. foreach ($val AS $field) {
  12724. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  12725. }
  12726. $opt['aa'] .= ']';
  12727. } elseif (($key == 'Flags')) {
  12728. $ff = 0;
  12729. if (is_array($val)) {
  12730. foreach ($val AS $flag) {
  12731. switch ($flag) {
  12732. case 'Include/Exclude': {
  12733. $ff += 1 << 0;
  12734. break;
  12735. }
  12736. case 'IncludeNoValueFields': {
  12737. $ff += 1 << 1;
  12738. break;
  12739. }
  12740. case 'ExportFormat': {
  12741. $ff += 1 << 2;
  12742. break;
  12743. }
  12744. case 'GetMethod': {
  12745. $ff += 1 << 3;
  12746. break;
  12747. }
  12748. case 'SubmitCoordinates': {
  12749. $ff += 1 << 4;
  12750. break;
  12751. }
  12752. case 'XFDF': {
  12753. $ff += 1 << 5;
  12754. break;
  12755. }
  12756. case 'IncludeAppendSaves': {
  12757. $ff += 1 << 6;
  12758. break;
  12759. }
  12760. case 'IncludeAnnotations': {
  12761. $ff += 1 << 7;
  12762. break;
  12763. }
  12764. case 'SubmitPDF': {
  12765. $ff += 1 << 8;
  12766. break;
  12767. }
  12768. case 'CanonicalFormat': {
  12769. $ff += 1 << 9;
  12770. break;
  12771. }
  12772. case 'ExclNonUserAnnots': {
  12773. $ff += 1 << 10;
  12774. break;
  12775. }
  12776. case 'ExclFKey': {
  12777. $ff += 1 << 11;
  12778. break;
  12779. }
  12780. case 'EmbedForm': {
  12781. $ff += 1 << 13;
  12782. break;
  12783. }
  12784. }
  12785. }
  12786. } else {
  12787. $ff = intval($val);
  12788. }
  12789. $opt['aa'] .= ' /Flags '.$ff;
  12790. }
  12791. }
  12792. $opt['aa'] .= ' >>';
  12793. } else {
  12794. // Javascript action or raw action command
  12795. $js_obj_id = $this->addJavascriptObject($action);
  12796. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  12797. }
  12798. }
  12799. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12800. if ($this->rtl) {
  12801. $this->x -= $w;
  12802. } else {
  12803. $this->x += $w;
  12804. }
  12805. }
  12806. // --- END FORMS FIELDS ------------------------------------------------
  12807. /**
  12808. * Add certification signature (DocMDP or UR3)
  12809. * You can set only one signature type
  12810. * @protected
  12811. * @author Nicola Asuni
  12812. * @since 4.6.008 (2009-05-07)
  12813. */
  12814. protected function _putsignature() {
  12815. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  12816. return;
  12817. }
  12818. $sigobjid = ($this->sig_obj_id + 1);
  12819. $out = $this->_getobj($sigobjid)."\n";
  12820. $out .= '<< /Type /Sig';
  12821. $out .= ' /Filter /Adobe.PPKLite';
  12822. $out .= ' /SubFilter /adbe.pkcs7.detached';
  12823. $out .= ' '.TCPDF_STATIC::$byterange_string;
  12824. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  12825. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  12826. $out .= ' /Reference ['; // array of signature reference dictionaries
  12827. $out .= ' << /Type /SigRef';
  12828. if ($this->signature_data['cert_type'] > 0) {
  12829. $out .= ' /TransformMethod /DocMDP';
  12830. $out .= ' /TransformParams <<';
  12831. $out .= ' /Type /TransformParams';
  12832. $out .= ' /P '.$this->signature_data['cert_type'];
  12833. $out .= ' /V /1.2';
  12834. } else {
  12835. $out .= ' /TransformMethod /UR3';
  12836. $out .= ' /TransformParams <<';
  12837. $out .= ' /Type /TransformParams';
  12838. $out .= ' /V /2.2';
  12839. if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
  12840. $out .= ' /Document['.$this->ur['document'].']';
  12841. }
  12842. if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
  12843. $out .= ' /Form['.$this->ur['form'].']';
  12844. }
  12845. if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
  12846. $out .= ' /Signature['.$this->ur['signature'].']';
  12847. }
  12848. if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
  12849. $out .= ' /Annots['.$this->ur['annots'].']';
  12850. }
  12851. if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
  12852. $out .= ' /EF['.$this->ur['ef'].']';
  12853. }
  12854. if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
  12855. $out .= ' /FormEX['.$this->ur['formex'].']';
  12856. }
  12857. }
  12858. $out .= ' >>'; // close TransformParams
  12859. // optional digest data (values must be calculated and replaced later)
  12860. //$out .= ' /Data ********** 0 R';
  12861. //$out .= ' /DigestMethod/MD5';
  12862. //$out .= ' /DigestLocation[********** 34]';
  12863. //$out .= ' /DigestValue<********************************>';
  12864. $out .= ' >>';
  12865. $out .= ' ]'; // end of reference
  12866. }
  12867. if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
  12868. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  12869. }
  12870. if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
  12871. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  12872. }
  12873. if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
  12874. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  12875. }
  12876. if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
  12877. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  12878. }
  12879. $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
  12880. $out .= ' >>';
  12881. $out .= "\n".'endobj';
  12882. $this->_out($out);
  12883. }
  12884. /**
  12885. * Set User's Rights for PDF Reader
  12886. * WARNING: This is experimental and currently do not work.
  12887. * Check the PDF Reference 8.7.1 Transform Methods,
  12888. * Table 8.105 Entries in the UR transform parameters dictionary
  12889. * @param $enable (boolean) if true enable user's rights on PDF reader
  12890. * @param $document (string) Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
  12891. * @param $annots (string) Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
  12892. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  12893. * @param $signature (string) Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
  12894. * @param $ef (string) Names specifying additional usage rights for named embedded files in the document. Valid names are /Create/Delete/Modify/Import, which permit the user to perform the named operation on named embedded files
  12895. Names specifying additional embedded-files-related usage rights for the document.
  12896. * @param $formex (string) Names specifying additional form-field-related usage rights. The only valid name is BarcodePlaintext, which permits text form field data to be encoded as a plaintext two-dimensional barcode.
  12897. * @public
  12898. * @author Nicola Asuni
  12899. * @since 2.9.000 (2008-03-26)
  12900. */
  12901. public function setUserRights(
  12902. $enable=true,
  12903. $document='/FullSave',
  12904. $annots='/Create/Delete/Modify/Copy/Import/Export',
  12905. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  12906. $signature='/Modify',
  12907. $ef='/Create/Delete/Modify/Import',
  12908. $formex='') {
  12909. $this->ur['enabled'] = $enable;
  12910. $this->ur['document'] = $document;
  12911. $this->ur['annots'] = $annots;
  12912. $this->ur['form'] = $form;
  12913. $this->ur['signature'] = $signature;
  12914. $this->ur['ef'] = $ef;
  12915. $this->ur['formex'] = $formex;
  12916. if (!$this->sign) {
  12917. $this->setSignature('', '', '', '', 0, array());
  12918. }
  12919. }
  12920. /**
  12921. * Enable document signature (requires the OpenSSL Library).
  12922. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  12923. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12924. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12925. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  12926. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  12927. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  12928. * @param $private_key_password (string) password
  12929. * @param $extracerts (string) specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
  12930. * @param $cert_type (int) The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature.
  12931. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  12932. * @param $approval (string) Enable approval signature eg. for PDF incremental update
  12933. * @public
  12934. * @author Nicola Asuni
  12935. * @since 4.6.005 (2009-04-24)
  12936. */
  12937. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
  12938. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12939. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12940. // to convert pfx certificate to pem: openssl
  12941. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  12942. $this->sign = true;
  12943. ++$this->n;
  12944. $this->sig_obj_id = $this->n; // signature widget
  12945. ++$this->n; // signature object ($this->sig_obj_id + 1)
  12946. $this->signature_data = array();
  12947. if (strlen($signing_cert) == 0) {
  12948. $this->Error('Please provide a certificate file and password!');
  12949. }
  12950. if (strlen($private_key) == 0) {
  12951. $private_key = $signing_cert;
  12952. }
  12953. $this->signature_data['signcert'] = $signing_cert;
  12954. $this->signature_data['privkey'] = $private_key;
  12955. $this->signature_data['password'] = $private_key_password;
  12956. $this->signature_data['extracerts'] = $extracerts;
  12957. $this->signature_data['cert_type'] = $cert_type;
  12958. $this->signature_data['info'] = $info;
  12959. $this->signature_data['approval'] = $approval;
  12960. }
  12961. /**
  12962. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  12963. * @param $x (float) Abscissa of the upper-left corner.
  12964. * @param $y (float) Ordinate of the upper-left corner.
  12965. * @param $w (float) Width of the signature area.
  12966. * @param $h (float) Height of the signature area.
  12967. * @param $page (int) option page number (if < 0 the current page is used).
  12968. * @param $name (string) Name of the signature.
  12969. * @public
  12970. * @author Nicola Asuni
  12971. * @since 5.3.011 (2010-06-17)
  12972. */
  12973. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  12974. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  12975. }
  12976. /**
  12977. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  12978. * @param $x (float) Abscissa of the upper-left corner.
  12979. * @param $y (float) Ordinate of the upper-left corner.
  12980. * @param $w (float) Width of the signature area.
  12981. * @param $h (float) Height of the signature area.
  12982. * @param $page (int) option page number (if < 0 the current page is used).
  12983. * @param $name (string) Name of the signature.
  12984. * @public
  12985. * @author Nicola Asuni
  12986. * @since 5.9.101 (2011-07-06)
  12987. */
  12988. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  12989. ++$this->n;
  12990. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  12991. }
  12992. /**
  12993. * Get the array that defines the signature appearance (page and rectangle coordinates).
  12994. * @param $x (float) Abscissa of the upper-left corner.
  12995. * @param $y (float) Ordinate of the upper-left corner.
  12996. * @param $w (float) Width of the signature area.
  12997. * @param $h (float) Height of the signature area.
  12998. * @param $page (int) option page number (if < 0 the current page is used).
  12999. * @param $name (string) Name of the signature.
  13000. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  13001. * @protected
  13002. * @author Nicola Asuni
  13003. * @since 5.9.101 (2011-07-06)
  13004. */
  13005. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13006. $sigapp = array();
  13007. if (($page < 1) OR ($page > $this->numpages)) {
  13008. $sigapp['page'] = $this->page;
  13009. } else {
  13010. $sigapp['page'] = intval($page);
  13011. }
  13012. if (empty($name)) {
  13013. $sigapp['name'] = 'Signature';
  13014. } else {
  13015. $sigapp['name'] = $name;
  13016. }
  13017. $a = $x * $this->k;
  13018. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  13019. $c = $w * $this->k;
  13020. $d = $h * $this->k;
  13021. $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
  13022. return $sigapp;
  13023. }
  13024. /**
  13025. * Enable document timestamping (requires the OpenSSL Library).
  13026. * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
  13027. * Use with digital signature only!
  13028. * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
  13029. * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
  13030. * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
  13031. * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
  13032. * @public
  13033. * @author Richard Stockinger
  13034. * @since 6.0.090 (2014-06-16)
  13035. */
  13036. public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
  13037. $this->tsa_data = array();
  13038. if (!function_exists('curl_init')) {
  13039. $this->Error('Please enable cURL PHP extension!');
  13040. }
  13041. if (strlen($tsa_host) == 0) {
  13042. $this->Error('Please specify the host of Time Stamping Authority (TSA)!');
  13043. }
  13044. $this->tsa_data['tsa_host'] = $tsa_host;
  13045. if (is_file($tsa_username)) {
  13046. $this->tsa_data['tsa_auth'] = $tsa_username;
  13047. } else {
  13048. $this->tsa_data['tsa_username'] = $tsa_username;
  13049. }
  13050. $this->tsa_data['tsa_password'] = $tsa_password;
  13051. $this->tsa_data['tsa_cert'] = $tsa_cert;
  13052. $this->tsa_timestamp = true;
  13053. }
  13054. /**
  13055. * NOT YET IMPLEMENTED
  13056. * Request TSA for a timestamp
  13057. * @param $signature (string) Digital signature as binary string
  13058. * @return (string) Timestamped digital signature
  13059. * @protected
  13060. * @author Richard Stockinger
  13061. * @since 6.0.090 (2014-06-16)
  13062. */
  13063. protected function applyTSA($signature) {
  13064. if (!$this->tsa_timestamp) {
  13065. return $signature;
  13066. }
  13067. //@TODO: implement this feature
  13068. return $signature;
  13069. }
  13070. /**
  13071. * Create a new page group.
  13072. * NOTE: call this function before calling AddPage()
  13073. * @param $page (int) starting group page (leave empty for next page).
  13074. * @public
  13075. * @since 3.0.000 (2008-03-27)
  13076. */
  13077. public function startPageGroup($page='') {
  13078. if (empty($page)) {
  13079. $page = $this->page + 1;
  13080. }
  13081. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  13082. }
  13083. /**
  13084. * Set the starting page number.
  13085. * @param $num (int) Starting page number.
  13086. * @since 5.9.093 (2011-06-16)
  13087. * @public
  13088. */
  13089. public function setStartingPageNumber($num=1) {
  13090. $this->starting_page_number = max(0, intval($num));
  13091. }
  13092. /**
  13093. * Returns the string alias used right align page numbers.
  13094. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  13095. * @return string
  13096. * @since 5.9.099 (2011-06-27)
  13097. * @public
  13098. */
  13099. public function getAliasRightShift() {
  13100. // calculate aproximatively the ratio between widths of aliases and replacements.
  13101. $ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
  13102. $rep = str_repeat(' ', $this->GetNumChars($ref));
  13103. $wrep = $this->GetStringWidth($rep);
  13104. if ($wrep > 0) {
  13105. $wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
  13106. } else {
  13107. $wdiff = 1;
  13108. }
  13109. $sdiff = sprintf('%F', $wdiff);
  13110. $alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
  13111. if ($this->isUnicodeFont()) {
  13112. $alias = '{'.$alias;
  13113. }
  13114. return $alias;
  13115. }
  13116. /**
  13117. * Returns the string alias used for the total number of pages.
  13118. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13119. * This alias will be replaced by the total number of pages in the document.
  13120. * @return string
  13121. * @since 4.0.018 (2008-08-08)
  13122. * @public
  13123. */
  13124. public function getAliasNbPages() {
  13125. if ($this->isUnicodeFont()) {
  13126. return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
  13127. }
  13128. return TCPDF_STATIC::$alias_tot_pages;
  13129. }
  13130. /**
  13131. * Returns the string alias used for the page number.
  13132. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13133. * This alias will be replaced by the page number.
  13134. * @return string
  13135. * @since 4.5.000 (2009-01-02)
  13136. * @public
  13137. */
  13138. public function getAliasNumPage() {
  13139. if ($this->isUnicodeFont()) {
  13140. return '{'.TCPDF_STATIC::$alias_num_page.'}';
  13141. }
  13142. return TCPDF_STATIC::$alias_num_page;
  13143. }
  13144. /**
  13145. * Return the alias for the total number of pages in the current page group.
  13146. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13147. * This alias will be replaced by the total number of pages in this group.
  13148. * @return alias of the current page group
  13149. * @public
  13150. * @since 3.0.000 (2008-03-27)
  13151. */
  13152. public function getPageGroupAlias() {
  13153. if ($this->isUnicodeFont()) {
  13154. return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
  13155. }
  13156. return TCPDF_STATIC::$alias_group_tot_pages;
  13157. }
  13158. /**
  13159. * Return the alias for the page number on the current page group.
  13160. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13161. * This alias will be replaced by the page number (relative to the belonging group).
  13162. * @return alias of the current page group
  13163. * @public
  13164. * @since 4.5.000 (2009-01-02)
  13165. */
  13166. public function getPageNumGroupAlias() {
  13167. if ($this->isUnicodeFont()) {
  13168. return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
  13169. }
  13170. return TCPDF_STATIC::$alias_group_num_page;
  13171. }
  13172. /**
  13173. * Return the current page in the group.
  13174. * @return current page in the group
  13175. * @public
  13176. * @since 3.0.000 (2008-03-27)
  13177. */
  13178. public function getGroupPageNo() {
  13179. return $this->pagegroups[$this->currpagegroup];
  13180. }
  13181. /**
  13182. * Returns the current group page number formatted as a string.
  13183. * @public
  13184. * @since 4.3.003 (2008-11-18)
  13185. * @see PaneNo(), formatPageNumber()
  13186. */
  13187. public function getGroupPageNoFormatted() {
  13188. return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
  13189. }
  13190. /**
  13191. * Returns the current page number formatted as a string.
  13192. * @public
  13193. * @since 4.2.005 (2008-11-06)
  13194. * @see PaneNo(), formatPageNumber()
  13195. */
  13196. public function PageNoFormatted() {
  13197. return TCPDF_STATIC::formatPageNumber($this->PageNo());
  13198. }
  13199. /**
  13200. * Put pdf layers.
  13201. * @protected
  13202. * @since 3.0.000 (2008-03-27)
  13203. */
  13204. protected function _putocg() {
  13205. if (empty($this->pdflayers)) {
  13206. return;
  13207. }
  13208. foreach ($this->pdflayers as $key => $layer) {
  13209. $this->pdflayers[$key]['objid'] = $this->_newobj();
  13210. $out = '<< /Type /OCG';
  13211. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  13212. $out .= ' /Usage <<';
  13213. if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
  13214. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  13215. }
  13216. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  13217. $out .= ' >> >>';
  13218. $out .= "\n".'endobj';
  13219. $this->_out($out);
  13220. }
  13221. }
  13222. /**
  13223. * Start a new pdf layer.
  13224. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  13225. * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
  13226. * @param $view (boolean) Set to true to view this layer.
  13227. * @param $lock (boolean) If true lock the layer
  13228. * @public
  13229. * @since 5.9.102 (2011-07-13)
  13230. */
  13231. public function startLayer($name='', $print=true, $view=true, $lock=true) {
  13232. if ($this->state != 2) {
  13233. return;
  13234. }
  13235. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  13236. if (empty($name)) {
  13237. $name = $layer;
  13238. } else {
  13239. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  13240. }
  13241. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
  13242. $this->openMarkedContent = true;
  13243. $this->_out('/OC /'.$layer.' BDC');
  13244. }
  13245. /**
  13246. * End the current PDF layer.
  13247. * @public
  13248. * @since 5.9.102 (2011-07-13)
  13249. */
  13250. public function endLayer() {
  13251. if ($this->state != 2) {
  13252. return;
  13253. }
  13254. if ($this->openMarkedContent) {
  13255. // close existing open marked-content layer
  13256. $this->_out('EMC');
  13257. $this->openMarkedContent = false;
  13258. }
  13259. }
  13260. /**
  13261. * Set the visibility of the successive elements.
  13262. * This can be useful, for instance, to put a background
  13263. * image or color that will show on screen but won't print.
  13264. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  13265. * @public
  13266. * @since 3.0.000 (2008-03-27)
  13267. */
  13268. public function setVisibility($v) {
  13269. if ($this->state != 2) {
  13270. return;
  13271. }
  13272. $this->endLayer();
  13273. switch($v) {
  13274. case 'print': {
  13275. $this->startLayer('Print', true, false);
  13276. break;
  13277. }
  13278. case 'view':
  13279. case 'screen': {
  13280. $this->startLayer('View', false, true);
  13281. break;
  13282. }
  13283. case 'all': {
  13284. $this->_out('');
  13285. break;
  13286. }
  13287. default: {
  13288. $this->Error('Incorrect visibility: '.$v);
  13289. break;
  13290. }
  13291. }
  13292. }
  13293. /**
  13294. * Add transparency parameters to the current extgstate
  13295. * @param $parms (array) parameters
  13296. * @return the number of extgstates
  13297. * @protected
  13298. * @since 3.0.000 (2008-03-27)
  13299. */
  13300. protected function addExtGState($parms) {
  13301. if ($this->pdfa_mode) {
  13302. // transparencies are not allowed in PDF/A mode
  13303. return;
  13304. }
  13305. // check if this ExtGState already exist
  13306. foreach ($this->extgstates as $i => $ext) {
  13307. if ($ext['parms'] == $parms) {
  13308. if ($this->inxobj) {
  13309. // we are inside an XObject template
  13310. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  13311. }
  13312. // return reference to existing ExtGState
  13313. return $i;
  13314. }
  13315. }
  13316. $n = (count($this->extgstates) + 1);
  13317. $this->extgstates[$n] = array('parms' => $parms);
  13318. if ($this->inxobj) {
  13319. // we are inside an XObject template
  13320. $this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
  13321. }
  13322. return $n;
  13323. }
  13324. /**
  13325. * Add an extgstate
  13326. * @param $gs (array) extgstate
  13327. * @protected
  13328. * @since 3.0.000 (2008-03-27)
  13329. */
  13330. protected function setExtGState($gs) {
  13331. if ($this->pdfa_mode OR ($this->state != 2)) {
  13332. // transparency is not allowed in PDF/A mode
  13333. return;
  13334. }
  13335. $this->_out(sprintf('/GS%d gs', $gs));
  13336. }
  13337. /**
  13338. * Put extgstates for object transparency
  13339. * @protected
  13340. * @since 3.0.000 (2008-03-27)
  13341. */
  13342. protected function _putextgstates() {
  13343. foreach ($this->extgstates as $i => $ext) {
  13344. $this->extgstates[$i]['n'] = $this->_newobj();
  13345. $out = '<< /Type /ExtGState';
  13346. foreach ($ext['parms'] as $k => $v) {
  13347. if (is_float($v)) {
  13348. $v = sprintf('%F', $v);
  13349. } elseif ($v === true) {
  13350. $v = 'true';
  13351. } elseif ($v === false)