PageRenderTime 136ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 2ms

/lib/tcpdf/tcpdf.php

https://bitbucket.org/moodle/moodle
PHP | 13912 lines | 8472 code | 563 blank | 4877 comment | 1760 complexity | 144aa32f4e30fd69d49d1f832331ce62 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  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. * Boolean flag to indicate if the document language is Right-To-Left.
  669. * @protected
  670. * @since 2.0.000
  671. */
  672. protected $rtl = false;
  673. /**
  674. * Boolean flag used to force RTL or LTR string direction.
  675. * @protected
  676. * @since 2.0.000
  677. */
  678. protected $tmprtl = false;
  679. // --- Variables used for document encryption:
  680. /**
  681. * IBoolean flag indicating whether document is protected.
  682. * @protected
  683. * @since 2.0.000 (2008-01-02)
  684. */
  685. protected $encrypted;
  686. /**
  687. * Array containing encryption settings.
  688. * @protected
  689. * @since 5.0.005 (2010-05-11)
  690. */
  691. protected $encryptdata = array();
  692. /**
  693. * Last RC4 key encrypted (cached for optimisation).
  694. * @protected
  695. * @since 2.0.000 (2008-01-02)
  696. */
  697. protected $last_enc_key;
  698. /**
  699. * Last RC4 computed key.
  700. * @protected
  701. * @since 2.0.000 (2008-01-02)
  702. */
  703. protected $last_enc_key_c;
  704. /**
  705. * File ID (used on document trailer).
  706. * @protected
  707. * @since 5.0.005 (2010-05-12)
  708. */
  709. protected $file_id;
  710. // --- bookmark ---
  711. /**
  712. * Outlines for bookmark.
  713. * @protected
  714. * @since 2.1.002 (2008-02-12)
  715. */
  716. protected $outlines = array();
  717. /**
  718. * Outline root for bookmark.
  719. * @protected
  720. * @since 2.1.002 (2008-02-12)
  721. */
  722. protected $OutlineRoot;
  723. // --- javascript and form ---
  724. /**
  725. * Javascript code.
  726. * @protected
  727. * @since 2.1.002 (2008-02-12)
  728. */
  729. protected $javascript = '';
  730. /**
  731. * Javascript counter.
  732. * @protected
  733. * @since 2.1.002 (2008-02-12)
  734. */
  735. protected $n_js;
  736. /**
  737. * line through state
  738. * @protected
  739. * @since 2.8.000 (2008-03-19)
  740. */
  741. protected $linethrough;
  742. /**
  743. * Array with additional document-wide usage rights for the document.
  744. * @protected
  745. * @since 5.8.014 (2010-08-23)
  746. */
  747. protected $ur = array();
  748. /**
  749. * DPI (Dot Per Inch) Document Resolution (do not change).
  750. * @protected
  751. * @since 3.0.000 (2008-03-27)
  752. */
  753. protected $dpi = 72;
  754. /**
  755. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  756. * @protected
  757. * @since 3.0.000 (2008-03-27)
  758. */
  759. protected $newpagegroup = array();
  760. /**
  761. * Array that contains the number of pages in each page group.
  762. * @protected
  763. * @since 3.0.000 (2008-03-27)
  764. */
  765. protected $pagegroups = array();
  766. /**
  767. * Current page group number.
  768. * @protected
  769. * @since 3.0.000 (2008-03-27)
  770. */
  771. protected $currpagegroup = 0;
  772. /**
  773. * Array of transparency objects and parameters.
  774. * @protected
  775. * @since 3.0.000 (2008-03-27)
  776. */
  777. protected $extgstates;
  778. /**
  779. * Set the default JPEG compression quality (1-100).
  780. * @protected
  781. * @since 3.0.000 (2008-03-27)
  782. */
  783. protected $jpeg_quality;
  784. /**
  785. * Default cell height ratio.
  786. * @protected
  787. * @since 3.0.014 (2008-05-23)
  788. */
  789. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  790. /**
  791. * PDF viewer preferences.
  792. * @protected
  793. * @since 3.1.000 (2008-06-09)
  794. */
  795. protected $viewer_preferences;
  796. /**
  797. * A name object specifying how the document should be displayed when opened.
  798. * @protected
  799. * @since 3.1.000 (2008-06-09)
  800. */
  801. protected $PageMode;
  802. /**
  803. * Array for storing gradient information.
  804. * @protected
  805. * @since 3.1.000 (2008-06-09)
  806. */
  807. protected $gradients = array();
  808. /**
  809. * Array used to store positions inside the pages buffer (keys are the page numbers).
  810. * @protected
  811. * @since 3.2.000 (2008-06-26)
  812. */
  813. protected $intmrk = array();
  814. /**
  815. * Array used to store positions inside the pages buffer (keys are the page numbers).
  816. * @protected
  817. * @since 5.7.000 (2010-08-03)
  818. */
  819. protected $bordermrk = array();
  820. /**
  821. * Array used to store page positions to track empty pages (keys are the page numbers).
  822. * @protected
  823. * @since 5.8.007 (2010-08-18)
  824. */
  825. protected $emptypagemrk = array();
  826. /**
  827. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  828. * @protected
  829. * @since 4.6.021 (2009-07-20)
  830. */
  831. protected $cntmrk = array();
  832. /**
  833. * Array used to store footer positions of each page.
  834. * @protected
  835. * @since 3.2.000 (2008-07-01)
  836. */
  837. protected $footerpos = array();
  838. /**
  839. * Array used to store footer length of each page.
  840. * @protected
  841. * @since 4.0.014 (2008-07-29)
  842. */
  843. protected $footerlen = array();
  844. /**
  845. * Boolean flag to indicate if a new line is created.
  846. * @protected
  847. * @since 3.2.000 (2008-07-01)
  848. */
  849. protected $newline = true;
  850. /**
  851. * End position of the latest inserted line.
  852. * @protected
  853. * @since 3.2.000 (2008-07-01)
  854. */
  855. protected $endlinex = 0;
  856. /**
  857. * PDF string for width value of the last line.
  858. * @protected
  859. * @since 4.0.006 (2008-07-16)
  860. */
  861. protected $linestyleWidth = '';
  862. /**
  863. * PDF string for CAP value of the last line.
  864. * @protected
  865. * @since 4.0.006 (2008-07-16)
  866. */
  867. protected $linestyleCap = '0 J';
  868. /**
  869. * PDF string for join value of the last line.
  870. * @protected
  871. * @since 4.0.006 (2008-07-16)
  872. */
  873. protected $linestyleJoin = '0 j';
  874. /**
  875. * PDF string for dash value of the last line.
  876. * @protected
  877. * @since 4.0.006 (2008-07-16)
  878. */
  879. protected $linestyleDash = '[] 0 d';
  880. /**
  881. * Boolean flag to indicate if marked-content sequence is open.
  882. * @protected
  883. * @since 4.0.013 (2008-07-28)
  884. */
  885. protected $openMarkedContent = false;
  886. /**
  887. * Count the latest inserted vertical spaces on HTML.
  888. * @protected
  889. * @since 4.0.021 (2008-08-24)
  890. */
  891. protected $htmlvspace = 0;
  892. /**
  893. * Array of Spot colors.
  894. * @protected
  895. * @since 4.0.024 (2008-09-12)
  896. */
  897. protected $spot_colors = array();
  898. /**
  899. * Symbol used for HTML unordered list items.
  900. * @protected
  901. * @since 4.0.028 (2008-09-26)
  902. */
  903. protected $lisymbol = '';
  904. /**
  905. * String used to mark the beginning and end of EPS image blocks.
  906. * @protected
  907. * @since 4.1.000 (2008-10-18)
  908. */
  909. protected $epsmarker = 'x#!#EPS#!#x';
  910. /**
  911. * Array of transformation matrix.
  912. * @protected
  913. * @since 4.2.000 (2008-10-29)
  914. */
  915. protected $transfmatrix = array();
  916. /**
  917. * Current key for transformation matrix.
  918. * @protected
  919. * @since 4.8.005 (2009-09-17)
  920. */
  921. protected $transfmatrix_key = 0;
  922. /**
  923. * Booklet mode for double-sided pages.
  924. * @protected
  925. * @since 4.2.000 (2008-10-29)
  926. */
  927. protected $booklet = false;
  928. /**
  929. * Epsilon value used for float calculations.
  930. * @protected
  931. * @since 4.2.000 (2008-10-29)
  932. */
  933. protected $feps = 0.005;
  934. /**
  935. * Array used for custom vertical spaces for HTML tags.
  936. * @protected
  937. * @since 4.2.001 (2008-10-30)
  938. */
  939. protected $tagvspaces = array();
  940. /**
  941. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  942. * @protected
  943. * @since 4.2.007 (2008-11-12)
  944. */
  945. protected $customlistindent = -1;
  946. /**
  947. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  948. * @protected
  949. * @since 4.2.010 (2008-11-14)
  950. */
  951. protected $opencell = true;
  952. /**
  953. * Array of files to embedd.
  954. * @protected
  955. * @since 4.4.000 (2008-12-07)
  956. */
  957. protected $embeddedfiles = array();
  958. /**
  959. * Boolean flag to indicate if we are inside a PRE tag.
  960. * @protected
  961. * @since 4.4.001 (2008-12-08)
  962. */
  963. protected $premode = false;
  964. /**
  965. * Array used to store positions of graphics transformation blocks inside the page buffer.
  966. * keys are the page numbers
  967. * @protected
  968. * @since 4.4.002 (2008-12-09)
  969. */
  970. protected $transfmrk = array();
  971. /**
  972. * Default color for html links.
  973. * @protected
  974. * @since 4.4.003 (2008-12-09)
  975. */
  976. protected $htmlLinkColorArray = array(0, 0, 255);
  977. /**
  978. * Default font style to add to html links.
  979. * @protected
  980. * @since 4.4.003 (2008-12-09)
  981. */
  982. protected $htmlLinkFontStyle = 'U';
  983. /**
  984. * Counts the number of pages.
  985. * @protected
  986. * @since 4.5.000 (2008-12-31)
  987. */
  988. protected $numpages = 0;
  989. /**
  990. * Array containing page lengths in bytes.
  991. * @protected
  992. * @since 4.5.000 (2008-12-31)
  993. */
  994. protected $pagelen = array();
  995. /**
  996. * Counts the number of pages.
  997. * @protected
  998. * @since 4.5.000 (2008-12-31)
  999. */
  1000. protected $numimages = 0;
  1001. /**
  1002. * Store the image keys.
  1003. * @protected
  1004. * @since 4.5.000 (2008-12-31)
  1005. */
  1006. protected $imagekeys = array();
  1007. /**
  1008. * Length of the buffer in bytes.
  1009. * @protected
  1010. * @since 4.5.000 (2008-12-31)
  1011. */
  1012. protected $bufferlen = 0;
  1013. /**
  1014. * Counts the number of fonts.
  1015. * @protected
  1016. * @since 4.5.000 (2009-01-02)
  1017. */
  1018. protected $numfonts = 0;
  1019. /**
  1020. * Store the font keys.
  1021. * @protected
  1022. * @since 4.5.000 (2009-01-02)
  1023. */
  1024. protected $fontkeys = array();
  1025. /**
  1026. * Store the font object IDs.
  1027. * @protected
  1028. * @since 4.8.001 (2009-09-09)
  1029. */
  1030. protected $font_obj_ids = array();
  1031. /**
  1032. * Store the fage status (true when opened, false when closed).
  1033. * @protected
  1034. * @since 4.5.000 (2009-01-02)
  1035. */
  1036. protected $pageopen = array();
  1037. /**
  1038. * Default monospace font.
  1039. * @protected
  1040. * @since 4.5.025 (2009-03-10)
  1041. */
  1042. protected $default_monospaced_font = 'courier';
  1043. /**
  1044. * Cloned copy of the current class object.
  1045. * @protected
  1046. * @since 4.5.029 (2009-03-19)
  1047. */
  1048. protected $objcopy;
  1049. /**
  1050. * Array used to store the lengths of cache files.
  1051. * @protected
  1052. * @since 4.5.029 (2009-03-19)
  1053. */
  1054. protected $cache_file_length = array();
  1055. /**
  1056. * Table header content to be repeated on each new page.
  1057. * @protected
  1058. * @since 4.5.030 (2009-03-20)
  1059. */
  1060. protected $thead = '';
  1061. /**
  1062. * Margins used for table header.
  1063. * @protected
  1064. * @since 4.5.030 (2009-03-20)
  1065. */
  1066. protected $theadMargins = array();
  1067. /**
  1068. * Boolean flag to enable document digital signature.
  1069. * @protected
  1070. * @since 4.6.005 (2009-04-24)
  1071. */
  1072. protected $sign = false;
  1073. /**
  1074. * Digital signature data.
  1075. * @protected
  1076. * @since 4.6.005 (2009-04-24)
  1077. */
  1078. protected $signature_data = array();
  1079. /**
  1080. * Digital signature max length.
  1081. * @protected
  1082. * @since 4.6.005 (2009-04-24)
  1083. */
  1084. protected $signature_max_length = 11742;
  1085. /**
  1086. * Data for digital signature appearance.
  1087. * @protected
  1088. * @since 5.3.011 (2010-06-16)
  1089. */
  1090. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1091. /**
  1092. * Array of empty digital signature appearances.
  1093. * @protected
  1094. * @since 5.9.101 (2011-07-06)
  1095. */
  1096. protected $empty_signature_appearance = array();
  1097. /**
  1098. * Boolean flag to enable document timestamping with TSA.
  1099. * @protected
  1100. * @since 6.0.085 (2014-06-19)
  1101. */
  1102. protected $tsa_timestamp = false;
  1103. /**
  1104. * Timestamping data.
  1105. * @protected
  1106. * @since 6.0.085 (2014-06-19)
  1107. */
  1108. protected $tsa_data = array();
  1109. /**
  1110. * Regular expression used to find blank characters (required for word-wrapping).
  1111. * @protected
  1112. * @since 4.6.006 (2009-04-28)
  1113. */
  1114. protected $re_spaces = '/[^\S\xa0]/';
  1115. /**
  1116. * Array of $re_spaces parts.
  1117. * @protected
  1118. * @since 5.5.011 (2010-07-09)
  1119. */
  1120. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1121. /**
  1122. * Digital signature object ID.
  1123. * @protected
  1124. * @since 4.6.022 (2009-06-23)
  1125. */
  1126. protected $sig_obj_id = 0;
  1127. /**
  1128. * ID of page objects.
  1129. * @protected
  1130. * @since 4.7.000 (2009-08-29)
  1131. */
  1132. protected $page_obj_id = array();
  1133. /**
  1134. * List of form annotations IDs.
  1135. * @protected
  1136. * @since 4.8.000 (2009-09-07)
  1137. */
  1138. protected $form_obj_id = array();
  1139. /**
  1140. * 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.
  1141. * @protected
  1142. * @since 4.8.000 (2009-09-07)
  1143. */
  1144. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1145. /**
  1146. * Javascript objects array.
  1147. * @protected
  1148. * @since 4.8.000 (2009-09-07)
  1149. */
  1150. protected $js_objects = array();
  1151. /**
  1152. * Current form action (used during XHTML rendering).
  1153. * @protected
  1154. * @since 4.8.000 (2009-09-07)
  1155. */
  1156. protected $form_action = '';
  1157. /**
  1158. * Current form encryption type (used during XHTML rendering).
  1159. * @protected
  1160. * @since 4.8.000 (2009-09-07)
  1161. */
  1162. protected $form_enctype = 'application/x-www-form-urlencoded';
  1163. /**
  1164. * Current method to submit forms.
  1165. * @protected
  1166. * @since 4.8.000 (2009-09-07)
  1167. */
  1168. protected $form_mode = 'post';
  1169. /**
  1170. * List of fonts used on form fields (fontname => fontkey).
  1171. * @protected
  1172. * @since 4.8.001 (2009-09-09)
  1173. */
  1174. protected $annotation_fonts = array();
  1175. /**
  1176. * List of radio buttons parent objects.
  1177. * @protected
  1178. * @since 4.8.001 (2009-09-09)
  1179. */
  1180. protected $radiobutton_groups = array();
  1181. /**
  1182. * List of radio group objects IDs.
  1183. * @protected
  1184. * @since 4.8.001 (2009-09-09)
  1185. */
  1186. protected $radio_groups = array();
  1187. /**
  1188. * Text indentation value (used for text-indent CSS attribute).
  1189. * @protected
  1190. * @since 4.8.006 (2009-09-23)
  1191. */
  1192. protected $textindent = 0;
  1193. /**
  1194. * Store page number when startTransaction() is called.
  1195. * @protected
  1196. * @since 4.8.006 (2009-09-23)
  1197. */
  1198. protected $start_transaction_page = 0;
  1199. /**
  1200. * Store Y position when startTransaction() is called.
  1201. * @protected
  1202. * @since 4.9.001 (2010-03-28)
  1203. */
  1204. protected $start_transaction_y = 0;
  1205. /**
  1206. * True when we are printing the thead section on a new page.
  1207. * @protected
  1208. * @since 4.8.027 (2010-01-25)
  1209. */
  1210. protected $inthead = false;
  1211. /**
  1212. * Array of column measures (width, space, starting Y position).
  1213. * @protected
  1214. * @since 4.9.001 (2010-03-28)
  1215. */
  1216. protected $columns = array();
  1217. /**
  1218. * Number of colums.
  1219. * @protected
  1220. * @since 4.9.001 (2010-03-28)
  1221. */
  1222. protected $num_columns = 1;
  1223. /**
  1224. * Current column number.
  1225. * @protected
  1226. * @since 4.9.001 (2010-03-28)
  1227. */
  1228. protected $current_column = 0;
  1229. /**
  1230. * Starting page for columns.
  1231. * @protected
  1232. * @since 4.9.001 (2010-03-28)
  1233. */
  1234. protected $column_start_page = 0;
  1235. /**
  1236. * Maximum page and column selected.
  1237. * @protected
  1238. * @since 5.8.000 (2010-08-11)
  1239. */
  1240. protected $maxselcol = array('page' => 0, 'column' => 0);
  1241. /**
  1242. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1243. * @protected
  1244. * @since 5.8.000 (2010-08-11)
  1245. */
  1246. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1247. /**
  1248. * 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.
  1249. * @protected
  1250. * @since 4.9.008 (2010-04-03)
  1251. */
  1252. protected $textrendermode = 0;
  1253. /**
  1254. * Text stroke width in doc units.
  1255. * @protected
  1256. * @since 4.9.008 (2010-04-03)
  1257. */
  1258. protected $textstrokewidth = 0;
  1259. /**
  1260. * Current stroke color.
  1261. * @protected
  1262. * @since 4.9.008 (2010-04-03)
  1263. */
  1264. protected $strokecolor;
  1265. /**
  1266. * Default unit of measure for document.
  1267. * @protected
  1268. * @since 5.0.000 (2010-04-22)
  1269. */
  1270. protected $pdfunit = 'mm';
  1271. /**
  1272. * Boolean flag true when we are on TOC (Table Of Content) page.
  1273. * @protected
  1274. */
  1275. protected $tocpage = false;
  1276. /**
  1277. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1278. * @protected
  1279. * @since 5.0.000 (2010-04-26)
  1280. */
  1281. protected $rasterize_vector_images = false;
  1282. /**
  1283. * Boolean flag: if true enables font subsetting by default.
  1284. * @protected
  1285. * @since 5.3.002 (2010-06-07)
  1286. */
  1287. protected $font_subsetting = true;
  1288. /**
  1289. * Array of default graphic settings.
  1290. * @protected
  1291. * @since 5.5.008 (2010-07-02)
  1292. */
  1293. protected $default_graphic_vars = array();
  1294. /**
  1295. * Array of XObjects.
  1296. * @protected
  1297. * @since 5.8.014 (2010-08-23)
  1298. */
  1299. protected $xobjects = array();
  1300. /**
  1301. * Boolean value true when we are inside an XObject.
  1302. * @protected
  1303. * @since 5.8.017 (2010-08-24)
  1304. */
  1305. protected $inxobj = false;
  1306. /**
  1307. * Current XObject ID.
  1308. * @protected
  1309. * @since 5.8.017 (2010-08-24)
  1310. */
  1311. protected $xobjid = '';
  1312. /**
  1313. * Percentage of character stretching.
  1314. * @protected
  1315. * @since 5.9.000 (2010-09-29)
  1316. */
  1317. protected $font_stretching = 100;
  1318. /**
  1319. * Increases or decreases the space between characters in a text by the specified amount (tracking).
  1320. * @protected
  1321. * @since 5.9.000 (2010-09-29)
  1322. */
  1323. protected $font_spacing = 0;
  1324. /**
  1325. * Array of no-write regions.
  1326. * ('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)
  1327. * @protected
  1328. * @since 5.9.003 (2010-10-14)
  1329. */
  1330. protected $page_regions = array();
  1331. /**
  1332. * Boolean value true when page region check is active.
  1333. * @protected
  1334. */
  1335. protected $check_page_regions = true;
  1336. /**
  1337. * Array of PDF layers data.
  1338. * @protected
  1339. * @since 5.9.102 (2011-07-13)
  1340. */
  1341. protected $pdflayers = array();
  1342. /**
  1343. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1344. * @protected
  1345. * @since 5.9.097 (2011-06-23)
  1346. */
  1347. protected $dests = array();
  1348. /**
  1349. * Object ID for Named Destinations
  1350. * @protected
  1351. * @since 5.9.097 (2011-06-23)
  1352. */
  1353. protected $n_dests;
  1354. /**
  1355. * Embedded Files Names
  1356. * @protected
  1357. * @since 5.9.204 (2013-01-23)
  1358. */
  1359. protected $efnames = array();
  1360. /**
  1361. * Directory used for the last SVG image.
  1362. * @protected
  1363. * @since 5.0.000 (2010-05-05)
  1364. */
  1365. protected $svgdir = '';
  1366. /**
  1367. * Deafult unit of measure for SVG.
  1368. * @protected
  1369. * @since 5.0.000 (2010-05-02)
  1370. */
  1371. protected $svgunit = 'px';
  1372. /**
  1373. * Array of SVG gradients.
  1374. * @protected
  1375. * @since 5.0.000 (2010-05-02)
  1376. */
  1377. protected $svggradients = array();
  1378. /**
  1379. * ID of last SVG gradient.
  1380. * @protected
  1381. * @since 5.0.000 (2010-05-02)
  1382. */
  1383. protected $svggradientid = 0;
  1384. /**
  1385. * Boolean value true when in SVG defs group.
  1386. * @protected
  1387. * @since 5.0.000 (2010-05-02)
  1388. */
  1389. protected $svgdefsmode = false;
  1390. /**
  1391. * Array of SVG defs.
  1392. * @protected
  1393. * @since 5.0.000 (2010-05-02)
  1394. */
  1395. protected $svgdefs = array();
  1396. /**
  1397. * Boolean value true when in SVG clipPath tag.
  1398. * @protected
  1399. * @since 5.0.000 (2010-04-26)
  1400. */
  1401. protected $svgclipmode = false;
  1402. /**
  1403. * Array of SVG clipPath commands.
  1404. * @protected
  1405. * @since 5.0.000 (2010-05-02)
  1406. */
  1407. protected $svgclippaths = array();
  1408. /**
  1409. * Array of SVG clipPath tranformation matrix.
  1410. * @protected
  1411. * @since 5.8.022 (2010-08-31)
  1412. */
  1413. protected $svgcliptm = array();
  1414. /**
  1415. * ID of last SVG clipPath.
  1416. * @protected
  1417. * @since 5.0.000 (2010-05-02)
  1418. */
  1419. protected $svgclipid = 0;
  1420. /**
  1421. * SVG text.
  1422. * @protected
  1423. * @since 5.0.000 (2010-05-02)
  1424. */
  1425. protected $svgtext = '';
  1426. /**
  1427. * SVG text properties.
  1428. * @protected
  1429. * @since 5.8.013 (2010-08-23)
  1430. */
  1431. protected $svgtextmode = array();
  1432. /**
  1433. * Array of SVG properties.
  1434. * @protected
  1435. * @since 5.0.000 (2010-05-02)
  1436. */
  1437. protected $svgstyles = array(array(
  1438. 'alignment-baseline' => 'auto',
  1439. 'baseline-shift' => 'baseline',
  1440. 'clip' => 'auto',
  1441. 'clip-path' => 'none',
  1442. 'clip-rule' => 'nonzero',
  1443. 'color' => 'black',
  1444. 'color-interpolation' => 'sRGB',
  1445. 'color-interpolation-filters' => 'linearRGB',
  1446. 'color-profile' => 'auto',
  1447. 'color-rendering' => 'auto',
  1448. 'cursor' => 'auto',
  1449. 'direction' => 'ltr',
  1450. 'display' => 'inline',
  1451. 'dominant-baseline' => 'auto',
  1452. 'enable-background' => 'accumulate',
  1453. 'fill' => 'black',
  1454. 'fill-opacity' => 1,
  1455. 'fill-rule' => 'nonzero',
  1456. 'filter' => 'none',
  1457. 'flood-color' => 'black',
  1458. 'flood-opacity' => 1,
  1459. 'font' => '',
  1460. 'font-family' => 'helvetica',
  1461. 'font-size' => 'medium',
  1462. 'font-size-adjust' => 'none',
  1463. 'font-stretch' => 'normal',
  1464. 'font-style' => 'normal',
  1465. 'font-variant' => 'normal',
  1466. 'font-weight' => 'normal',
  1467. 'glyph-orientation-horizontal' => '0deg',
  1468. 'glyph-orientation-vertical' => 'auto',
  1469. 'image-rendering' => 'auto',
  1470. 'kerning' => 'auto',
  1471. 'letter-spacing' => 'normal',
  1472. 'lighting-color' => 'white',
  1473. 'marker' => '',
  1474. 'marker-end' => 'none',
  1475. 'marker-mid' => 'none',
  1476. 'marker-start' => 'none',
  1477. 'mask' => 'none',
  1478. 'opacity' => 1,
  1479. 'overflow' => 'auto',
  1480. 'pointer-events' => 'visiblePainted',
  1481. 'shape-rendering' => 'auto',
  1482. 'stop-color' => 'black',
  1483. 'stop-opacity' => 1,
  1484. 'stroke' => 'none',
  1485. 'stroke-dasharray' => 'none',
  1486. 'stroke-dashoffset' => 0,
  1487. 'stroke-linecap' => 'butt',
  1488. 'stroke-linejoin' => 'miter',
  1489. 'stroke-miterlimit' => 4,
  1490. 'stroke-opacity' => 1,
  1491. 'stroke-width' => 1,
  1492. 'text-anchor' => 'start',
  1493. 'text-decoration' => 'none',
  1494. 'text-rendering' => 'auto',
  1495. 'unicode-bidi' => 'normal',
  1496. 'visibility' => 'visible',
  1497. 'word-spacing' => 'normal',
  1498. 'writing-mode' => 'lr-tb',
  1499. 'text-color' => 'black',
  1500. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1501. ));
  1502. /**
  1503. * If true force sRGB color profile for all document.
  1504. * @protected
  1505. * @since 5.9.121 (2011-09-28)
  1506. */
  1507. protected $force_srgb = false;
  1508. /**
  1509. * If true set the document to PDF/A mode.
  1510. * @protected
  1511. * @since 5.9.121 (2011-09-27)
  1512. */
  1513. protected $pdfa_mode = false;
  1514. /**
  1515. * version of PDF/A mode (1 - 3).
  1516. * @protected
  1517. * @since 6.2.26 (2019-03-12)
  1518. */
  1519. protected $pdfa_version = 1;
  1520. /**
  1521. * Document creation date-time
  1522. * @protected
  1523. * @since 5.9.152 (2012-03-22)
  1524. */
  1525. protected $doc_creation_timestamp;
  1526. /**
  1527. * Document modification date-time
  1528. * @protected
  1529. * @since 5.9.152 (2012-03-22)
  1530. */
  1531. protected $doc_modification_timestamp;
  1532. /**
  1533. * Custom XMP data.
  1534. * @protected
  1535. * @since 5.9.128 (2011-10-06)
  1536. */
  1537. protected $custom_xmp = '';
  1538. /**
  1539. * Custom XMP RDF data.
  1540. * @protected
  1541. * @since 6.3.0 (2019-09-19)
  1542. */
  1543. protected $custom_xmp_rdf = '';
  1544. /**
  1545. * Overprint mode array.
  1546. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1547. * @protected
  1548. * @since 5.9.152 (2012-03-23)
  1549. */
  1550. protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
  1551. /**
  1552. * Alpha mode array.
  1553. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1554. * @protected
  1555. * @since 5.9.152 (2012-03-23)
  1556. */
  1557. protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
  1558. /**
  1559. * Define the page boundaries boxes to be set on document.
  1560. * @protected
  1561. * @since 5.9.152 (2012-03-23)
  1562. */
  1563. protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  1564. /**
  1565. * If true print TCPDF meta link.
  1566. * @protected
  1567. * @since 5.9.152 (2012-03-23)
  1568. */
  1569. protected $tcpdflink = true;
  1570. /**
  1571. * Cache array for computed GD gamma values.
  1572. * @protected
  1573. * @since 5.9.1632 (2012-06-05)
  1574. */
  1575. protected $gdgammacache = array();
  1576. /**
  1577. * Cache array for file content
  1578. * @protected
  1579. * @var array
  1580. * @sinde 6.3.5 (2020-09-28)
  1581. */
  1582. protected $fileContentCache = array();
  1583. /**
  1584. * Whether to allow local file path in image html tags, when prefixed with file://
  1585. *
  1586. * @var bool
  1587. * @protected
  1588. * @since 6.4 (2020-07-23)
  1589. */
  1590. protected $allowLocalFiles = false;
  1591. //------------------------------------------------------------
  1592. // METHODS
  1593. //------------------------------------------------------------
  1594. /**
  1595. * This is the class constructor.
  1596. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
  1597. *
  1598. * @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>
  1599. * @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.
  1600. * @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().
  1601. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1602. * @param $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.
  1603. * @param $diskcache (boolean) DEPRECATED FEATURE
  1604. * @param $pdfa (integer) If not false, set the document to PDF/A mode and the good version (1 or 3).
  1605. * @public
  1606. * @see getPageSizeFromFormat(), setPageFormat()
  1607. */
  1608. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1609. // set file ID for trailer
  1610. $serformat = (is_array($format) ? json_encode($format) : $format);
  1611. $this->file_id = md5(TCPDF_STATIC::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
  1612. $this->font_obj_ids = array();
  1613. $this->page_obj_id = array();
  1614. $this->form_obj_id = array();
  1615. // set pdf/a mode
  1616. if ($pdfa != false) {
  1617. $this->pdfa_mode = true;
  1618. $this->pdfa_version = $pdfa; // 1 or 3
  1619. } else
  1620. $this->pdfa_mode = false;
  1621. $this->force_srgb = false;
  1622. // set language direction
  1623. $this->rtl = false;
  1624. $this->tmprtl = false;
  1625. // some checks
  1626. $this->_dochecks();
  1627. // initialization of properties
  1628. $this->isunicode = $unicode;
  1629. $this->page = 0;
  1630. $this->transfmrk[0] = array();
  1631. $this->pagedim = array();
  1632. $this->n = 2;
  1633. $this->buffer = '';
  1634. $this->pages = array();
  1635. $this->state = 0;
  1636. $this->fonts = array();
  1637. $this->FontFiles = array();
  1638. $this->diffs = array();
  1639. $this->images = array();
  1640. $this->links = array();
  1641. $this->gradients = array();
  1642. $this->InFooter = false;
  1643. $this->lasth = 0;
  1644. $this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  1645. $this->FontStyle = '';
  1646. $this->FontSizePt = 12;
  1647. $this->underline = false;
  1648. $this->overline = false;
  1649. $this->linethrough = false;
  1650. $this->DrawColor = '0 G';
  1651. $this->FillColor = '0 g';
  1652. $this->TextColor = '0 g';
  1653. $this->ColorFlag = false;
  1654. $this->pdflayers = array();
  1655. // encryption values
  1656. $this->encrypted = false;
  1657. $this->last_enc_key = '';
  1658. // standard Unicode fonts
  1659. $this->CoreFonts = array(
  1660. 'courier'=>'Courier',
  1661. 'courierB'=>'Courier-Bold',
  1662. 'courierI'=>'Courier-Oblique',
  1663. 'courierBI'=>'Courier-BoldOblique',
  1664. 'helvetica'=>'Helvetica',
  1665. 'helveticaB'=>'Helvetica-Bold',
  1666. 'helveticaI'=>'Helvetica-Oblique',
  1667. 'helveticaBI'=>'Helvetica-BoldOblique',
  1668. 'times'=>'Times-Roman',
  1669. 'timesB'=>'Times-Bold',
  1670. 'timesI'=>'Times-Italic',
  1671. 'timesBI'=>'Times-BoldItalic',
  1672. 'symbol'=>'Symbol',
  1673. 'zapfdingbats'=>'ZapfDingbats'
  1674. );
  1675. // set scale factor
  1676. $this->setPageUnit($unit);
  1677. // set page format and orientation
  1678. $this->setPageFormat($format, $orientation);
  1679. // page margins (1 cm)
  1680. $margin = 28.35 / $this->k;
  1681. $this->SetMargins($margin, $margin);
  1682. $this->clMargin = $this->lMargin;
  1683. $this->crMargin = $this->rMargin;
  1684. // internal cell padding
  1685. $cpadding = $margin / 10;
  1686. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1687. // cell margins
  1688. $this->setCellMargins(0, 0, 0, 0);
  1689. // line width (0.2 mm)
  1690. $this->LineWidth = 0.57 / $this->k;
  1691. $this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
  1692. $this->linestyleCap = '0 J';
  1693. $this->linestyleJoin = '0 j';
  1694. $this->linestyleDash = '[] 0 d';
  1695. // automatic page break
  1696. $this->SetAutoPageBreak(true, (2 * $margin));
  1697. // full width display mode
  1698. $this->SetDisplayMode('fullwidth');
  1699. // compression
  1700. $this->SetCompression();
  1701. // set default PDF version number
  1702. $this->setPDFVersion();
  1703. $this->tcpdflink = true;
  1704. $this->encoding = $encoding;
  1705. $this->HREF = array();
  1706. $this->getFontsList();
  1707. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1708. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1709. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1710. $this->extgstates = array();
  1711. $this->setTextShadow();
  1712. // signature
  1713. $this->sign = false;
  1714. $this->tsa_timestamp = false;
  1715. $this->tsa_data = array();
  1716. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
  1717. $this->empty_signature_appearance = array();
  1718. // user's rights
  1719. $this->ur['enabled'] = false;
  1720. $this->ur['document'] = '/FullSave';
  1721. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1722. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1723. $this->ur['signature'] = '/Modify';
  1724. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1725. $this->ur['formex'] = '';
  1726. // set default JPEG quality
  1727. $this->jpeg_quality = 75;
  1728. // initialize some settings
  1729. TCPDF_FONTS::utf8Bidi(array(), '', false, $this->isunicode, $this->CurrentFont);
  1730. // set default font
  1731. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1732. $this->setHeaderFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1733. $this->setFooterFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1734. // check if PCRE Unicode support is enabled
  1735. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1736. // PCRE unicode support is turned ON
  1737. // \s : any whitespace character
  1738. // \p{Z} : any separator
  1739. // \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  1740. // \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  1741. //$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
  1742. $this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
  1743. } else {
  1744. // PCRE unicode support is turned OFF
  1745. $this->setSpacesRE('/[^\S\xa0]/');
  1746. }
  1747. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1748. // set document creation and modification timestamp
  1749. $this->doc_creation_timestamp = time();
  1750. $this->doc_modification_timestamp = $this->doc_creation_timestamp;
  1751. // get default graphic vars
  1752. $this->default_graphic_vars = $this->getGraphicVars();
  1753. $this->header_xobj_autoreset = false;
  1754. $this->custom_xmp = '';
  1755. $this->custom_xmp_rdf = '';
  1756. // Call cleanup method after script execution finishes or exit() is called.
  1757. // NOTE: This will not be executed if the process is killed with a SIGTERM or SIGKILL signal.
  1758. register_shutdown_function(array($this, '_destroy'), true);
  1759. }
  1760. /**
  1761. * Default destructor.
  1762. * @public
  1763. * @since 1.53.0.TC016
  1764. */
  1765. public function __destruct() {
  1766. // cleanup
  1767. $this->_destroy(true);
  1768. }
  1769. /**
  1770. * Set the units of measure for the document.
  1771. * @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.
  1772. * @public
  1773. * @since 3.0.015 (2008-06-06)
  1774. */
  1775. public function setPageUnit($unit) {
  1776. $unit = strtolower($unit);
  1777. //Set scale factor
  1778. switch ($unit) {
  1779. // points
  1780. case 'px':
  1781. case 'pt': {
  1782. $this->k = 1;
  1783. break;
  1784. }
  1785. // millimeters
  1786. case 'mm': {
  1787. $this->k = $this->dpi / 25.4;
  1788. break;
  1789. }
  1790. // centimeters
  1791. case 'cm': {
  1792. $this->k = $this->dpi / 2.54;
  1793. break;
  1794. }
  1795. // inches
  1796. case 'in': {
  1797. $this->k = $this->dpi;
  1798. break;
  1799. }
  1800. // unsupported unit
  1801. default : {
  1802. $this->Error('Incorrect unit: '.$unit);
  1803. break;
  1804. }
  1805. }
  1806. $this->pdfunit = $unit;
  1807. if (isset($this->CurOrientation)) {
  1808. $this->setPageOrientation($this->CurOrientation);
  1809. }
  1810. }
  1811. /**
  1812. * Change the format of the current page
  1813. * @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>
  1814. * <li>['format'] = page format name (one of the above);</li>
  1815. * <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>
  1816. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  1817. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  1818. * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
  1819. * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
  1820. * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
  1821. * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
  1822. * <li>['CropBox'] : the visible region of default user space:</li>
  1823. * <li>['CropBox']['llx'] : lower-left x coordinate</li>
  1824. * <li>['CropBox']['lly'] : lower-left y coordinate</li>
  1825. * <li>['CropBox']['urx'] : upper-right x coordinate</li>
  1826. * <li>['CropBox']['ury'] : upper-right y coordinate</li>
  1827. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  1828. * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
  1829. * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
  1830. * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
  1831. * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
  1832. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  1833. * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
  1834. * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
  1835. * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
  1836. * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
  1837. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  1838. * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
  1839. * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
  1840. * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
  1841. * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
  1842. * <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>
  1843. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  1844. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  1845. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  1846. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  1847. * <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>
  1848. * <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>
  1849. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  1850. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  1851. * <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>
  1852. * <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>
  1853. * <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>
  1854. * <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>
  1855. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  1856. * </ul>
  1857. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  1858. * <li>P or Portrait (default)</li>
  1859. * <li>L or Landscape</li>
  1860. * <li>'' (empty string) for automatic orientation</li>
  1861. * </ul>
  1862. * @protected
  1863. * @since 3.0.015 (2008-06-06)
  1864. * @see getPageSizeFromFormat()
  1865. */
  1866. protected function setPageFormat($format, $orientation='P') {
  1867. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  1868. // remove inherited values
  1869. unset($this->pagedim[$this->page]);
  1870. }
  1871. if (is_string($format)) {
  1872. // get page measures from format name
  1873. $pf = TCPDF_STATIC::getPageSizeFromFormat($format);
  1874. $this->fwPt = $pf[0];
  1875. $this->fhPt = $pf[1];
  1876. } else {
  1877. // the boundaries of the physical medium on which the page shall be displayed or printed
  1878. if (isset($format['MediaBox'])) {
  1879. $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);
  1880. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  1881. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  1882. } else {
  1883. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  1884. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  1885. } else {
  1886. if (!isset($format['format'])) {
  1887. // default value
  1888. $format['format'] = 'A4';
  1889. }
  1890. $pf = TCPDF_STATIC::getPageSizeFromFormat($format['format']);
  1891. }
  1892. $this->fwPt = $pf[0];
  1893. $this->fhPt = $pf[1];
  1894. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1895. }
  1896. // the visible region of default user space
  1897. if (isset($format['CropBox'])) {
  1898. $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);
  1899. }
  1900. // the region to which the contents of the page shall be clipped when output in a production environment
  1901. if (isset($format['BleedBox'])) {
  1902. $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);
  1903. }
  1904. // the intended dimensions of the finished page after trimming
  1905. if (isset($format['TrimBox'])) {
  1906. $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);
  1907. }
  1908. // the page's meaningful content (including potential white space)
  1909. if (isset($format['ArtBox'])) {
  1910. $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);
  1911. }
  1912. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  1913. if (isset($format['BoxColorInfo'])) {
  1914. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  1915. }
  1916. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  1917. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  1918. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  1919. }
  1920. if (isset($format['PZ'])) {
  1921. // The page's preferred zoom (magnification) factor
  1922. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  1923. }
  1924. if (isset($format['trans'])) {
  1925. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  1926. if (isset($format['trans']['Dur'])) {
  1927. // The page's display duration
  1928. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  1929. }
  1930. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  1931. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  1932. // The transition style that shall be used when moving to this page from another during a presentation
  1933. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  1934. $valid_effect = array('Split', 'Blinds');
  1935. $valid_vals = array('H', 'V');
  1936. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  1937. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  1938. }
  1939. $valid_effect = array('Split', 'Box', 'Fly');
  1940. $valid_vals = array('I', 'O');
  1941. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  1942. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  1943. }
  1944. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  1945. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  1946. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  1947. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  1948. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  1949. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  1950. }
  1951. }
  1952. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  1953. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  1954. }
  1955. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  1956. $this->pagedim[$this->page]['trans']['B'] = 'true';
  1957. }
  1958. } else {
  1959. $this->pagedim[$this->page]['trans']['S'] = 'R';
  1960. }
  1961. if (isset($format['trans']['D'])) {
  1962. // The duration of the transition effect, in seconds
  1963. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  1964. } else {
  1965. $this->pagedim[$this->page]['trans']['D'] = 1;
  1966. }
  1967. }
  1968. }
  1969. $this->setPageOrientation($orientation);
  1970. }
  1971. /**
  1972. * Set page orientation.
  1973. * @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>
  1974. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  1975. * @param $bottommargin (float) bottom margin of the page.
  1976. * @public
  1977. * @since 3.0.015 (2008-06-06)
  1978. */
  1979. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  1980. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  1981. // the boundaries of the physical medium on which the page shall be displayed or printed
  1982. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1983. }
  1984. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  1985. // the visible region of default user space
  1986. $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);
  1987. }
  1988. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  1989. // the region to which the contents of the page shall be clipped when output in a production environment
  1990. $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);
  1991. }
  1992. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  1993. // the intended dimensions of the finished page after trimming
  1994. $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);
  1995. }
  1996. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  1997. // the page's meaningful content (including potential white space)
  1998. $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);
  1999. }
  2000. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  2001. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2002. $this->pagedim[$this->page]['Rotate'] = 0;
  2003. }
  2004. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2005. // The page's preferred zoom (magnification) factor
  2006. $this->pagedim[$this->page]['PZ'] = 1;
  2007. }
  2008. if ($this->fwPt > $this->fhPt) {
  2009. // landscape
  2010. $default_orientation = 'L';
  2011. } else {
  2012. // portrait
  2013. $default_orientation = 'P';
  2014. }
  2015. $valid_orientations = array('P', 'L');
  2016. if (empty($orientation)) {
  2017. $orientation = $default_orientation;
  2018. } else {
  2019. $orientation = strtoupper($orientation[0]);
  2020. }
  2021. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2022. $this->CurOrientation = $orientation;
  2023. $this->wPt = $this->fhPt;
  2024. $this->hPt = $this->fwPt;
  2025. } else {
  2026. $this->CurOrientation = $default_orientation;
  2027. $this->wPt = $this->fwPt;
  2028. $this->hPt = $this->fhPt;
  2029. }
  2030. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2031. // swap X and Y coordinates (change page orientation)
  2032. $this->pagedim = TCPDF_STATIC::swapPageBoxCoordinates($this->page, $this->pagedim);
  2033. }
  2034. $this->w = ($this->wPt / $this->k);
  2035. $this->h = ($this->hPt / $this->k);
  2036. if (TCPDF_STATIC::empty_string($autopagebreak)) {
  2037. if (isset($this->AutoPageBreak)) {
  2038. $autopagebreak = $this->AutoPageBreak;
  2039. } else {
  2040. $autopagebreak = true;
  2041. }
  2042. }
  2043. if (TCPDF_STATIC::empty_string($bottommargin)) {
  2044. if (isset($this->bMargin)) {
  2045. $bottommargin = $this->bMargin;
  2046. } else {
  2047. // default value = 2 cm
  2048. $bottommargin = 2 * 28.35 / $this->k;
  2049. }
  2050. }
  2051. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2052. // store page dimensions
  2053. $this->pagedim[$this->page]['w'] = $this->wPt;
  2054. $this->pagedim[$this->page]['h'] = $this->hPt;
  2055. $this->pagedim[$this->page]['wk'] = $this->w;
  2056. $this->pagedim[$this->page]['hk'] = $this->h;
  2057. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2058. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2059. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2060. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2061. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2062. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2063. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2064. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2065. }
  2066. /**
  2067. * Set regular expression to detect withespaces or word separators.
  2068. * The pattern delimiter must be the forward-slash character "/".
  2069. * Some example patterns are:
  2070. * <pre>
  2071. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2072. * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
  2073. * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
  2074. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2075. * \s : any whitespace character
  2076. * \p{Z} : any separator
  2077. * \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  2078. * \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  2079. * </pre>
  2080. * @param $re (string) regular expression (leave empty for default).
  2081. * @public
  2082. * @since 4.6.016 (2009-06-15)
  2083. */
  2084. public function setSpacesRE($re='/[^\S\xa0]/') {
  2085. $this->re_spaces = $re;
  2086. $re_parts = explode('/', $re);
  2087. // get pattern parts
  2088. $this->re_space = array();
  2089. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2090. $this->re_space['p'] = $re_parts[1];
  2091. } else {
  2092. $this->re_space['p'] = '[\s]';
  2093. }
  2094. // set pattern modifiers
  2095. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2096. $this->re_space['m'] = $re_parts[2];
  2097. } else {
  2098. $this->re_space['m'] = '';
  2099. }
  2100. }
  2101. /**
  2102. * Enable or disable Right-To-Left language mode
  2103. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2104. * @param $resetx (Boolean) if true reset the X position on direction change.
  2105. * @public
  2106. * @since 2.0.000 (2008-01-03)
  2107. */
  2108. public function setRTL($enable, $resetx=true) {
  2109. $enable = $enable ? true : false;
  2110. $resetx = ($resetx AND ($enable != $this->rtl));
  2111. $this->rtl = $enable;
  2112. $this->tmprtl = false;
  2113. if ($resetx) {
  2114. $this->Ln(0);
  2115. }
  2116. }
  2117. /**
  2118. * Return the RTL status
  2119. * @return boolean
  2120. * @public
  2121. * @since 4.0.012 (2008-07-24)
  2122. */
  2123. public function getRTL() {
  2124. return $this->rtl;
  2125. }
  2126. /**
  2127. * Force temporary RTL language direction
  2128. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2129. * @public
  2130. * @since 2.1.000 (2008-01-09)
  2131. */
  2132. public function setTempRTL($mode) {
  2133. $newmode = false;
  2134. switch (strtoupper($mode)) {
  2135. case 'LTR':
  2136. case 'L': {
  2137. if ($this->rtl) {
  2138. $newmode = 'L';
  2139. }
  2140. break;
  2141. }
  2142. case 'RTL':
  2143. case 'R': {
  2144. if (!$this->rtl) {
  2145. $newmode = 'R';
  2146. }
  2147. break;
  2148. }
  2149. case false:
  2150. default: {
  2151. $newmode = false;
  2152. break;
  2153. }
  2154. }
  2155. $this->tmprtl = $newmode;
  2156. }
  2157. /**
  2158. * Return the current temporary RTL status
  2159. * @return boolean
  2160. * @public
  2161. * @since 4.8.014 (2009-11-04)
  2162. */
  2163. public function isRTLTextDir() {
  2164. return ($this->rtl OR ($this->tmprtl == 'R'));
  2165. }
  2166. /**
  2167. * Set the last cell height.
  2168. * @param $h (float) cell height.
  2169. * @author Nicola Asuni
  2170. * @public
  2171. * @since 1.53.0.TC034
  2172. */
  2173. public function setLastH($h) {
  2174. $this->lasth = $h;
  2175. }
  2176. /**
  2177. * Return the cell height
  2178. * @param $fontsize (int) Font size in internal units
  2179. * @param $padding (boolean) If true add cell padding
  2180. * @public
  2181. */
  2182. public function getCellHeight($fontsize, $padding=TRUE) {
  2183. $height = ($fontsize * $this->cell_height_ratio);
  2184. if ($padding) {
  2185. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  2186. }
  2187. return round($height, 6);
  2188. }
  2189. /**
  2190. * Reset the last cell height.
  2191. * @public
  2192. * @since 5.9.000 (2010-10-03)
  2193. */
  2194. public function resetLastH() {
  2195. $this->lasth = $this->getCellHeight($this->FontSize);
  2196. }
  2197. /**
  2198. * Get the last cell height.
  2199. * @return last cell height
  2200. * @public
  2201. * @since 4.0.017 (2008-08-05)
  2202. */
  2203. public function getLastH() {
  2204. return $this->lasth;
  2205. }
  2206. /**
  2207. * Set the adjusting factor to convert pixels to user units.
  2208. * @param $scale (float) adjusting factor to convert pixels to user units.
  2209. * @author Nicola Asuni
  2210. * @public
  2211. * @since 1.5.2
  2212. */
  2213. public function setImageScale($scale) {
  2214. $this->imgscale = $scale;
  2215. }
  2216. /**
  2217. * Returns the adjusting factor to convert pixels to user units.
  2218. * @return float adjusting factor to convert pixels to user units.
  2219. * @author Nicola Asuni
  2220. * @public
  2221. * @since 1.5.2
  2222. */
  2223. public function getImageScale() {
  2224. return $this->imgscale;
  2225. }
  2226. /**
  2227. * Returns an array of page dimensions:
  2228. * <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>
  2229. * @param $pagenum (int) page number (empty = current page)
  2230. * @return array of page dimensions.
  2231. * @author Nicola Asuni
  2232. * @public
  2233. * @since 4.5.027 (2009-03-16)
  2234. */
  2235. public function getPageDimensions($pagenum='') {
  2236. if (empty($pagenum)) {
  2237. $pagenum = $this->page;
  2238. }
  2239. return $this->pagedim[$pagenum];
  2240. }
  2241. /**
  2242. * Returns the page width in units.
  2243. * @param $pagenum (int) page number (empty = current page)
  2244. * @return int page width.
  2245. * @author Nicola Asuni
  2246. * @public
  2247. * @since 1.5.2
  2248. * @see getPageDimensions()
  2249. */
  2250. public function getPageWidth($pagenum='') {
  2251. if (empty($pagenum)) {
  2252. return $this->w;
  2253. }
  2254. return $this->pagedim[$pagenum]['w'];
  2255. }
  2256. /**
  2257. * Returns the page height in units.
  2258. * @param $pagenum (int) page number (empty = current page)
  2259. * @return int page height.
  2260. * @author Nicola Asuni
  2261. * @public
  2262. * @since 1.5.2
  2263. * @see getPageDimensions()
  2264. */
  2265. public function getPageHeight($pagenum='') {
  2266. if (empty($pagenum)) {
  2267. return $this->h;
  2268. }
  2269. return $this->pagedim[$pagenum]['h'];
  2270. }
  2271. /**
  2272. * Returns the page break margin.
  2273. * @param $pagenum (int) page number (empty = current page)
  2274. * @return int page break margin.
  2275. * @author Nicola Asuni
  2276. * @public
  2277. * @since 1.5.2
  2278. * @see getPageDimensions()
  2279. */
  2280. public function getBreakMargin($pagenum='') {
  2281. if (empty($pagenum)) {
  2282. return $this->bMargin;
  2283. }
  2284. return $this->pagedim[$pagenum]['bm'];
  2285. }
  2286. /**
  2287. * Returns the scale factor (number of points in user unit).
  2288. * @return int scale factor.
  2289. * @author Nicola Asuni
  2290. * @public
  2291. * @since 1.5.2
  2292. */
  2293. public function getScaleFactor() {
  2294. return $this->k;
  2295. }
  2296. /**
  2297. * Defines the left, top and right margins.
  2298. * @param $left (float) Left margin.
  2299. * @param $top (float) Top margin.
  2300. * @param $right (float) Right margin. Default value is the left one.
  2301. * @param $keepmargins (boolean) if true overwrites the default page margins
  2302. * @public
  2303. * @since 1.0
  2304. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  2305. */
  2306. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  2307. //Set left, top and right margins
  2308. $this->lMargin = $left;
  2309. $this->tMargin = $top;
  2310. if ($right == -1) {
  2311. $right = $left;
  2312. }
  2313. $this->rMargin = $right;
  2314. if ($keepmargins) {
  2315. // overwrite original values
  2316. $this->original_lMargin = $this->lMargin;
  2317. $this->original_rMargin = $this->rMargin;
  2318. }
  2319. }
  2320. /**
  2321. * 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.
  2322. * @param $margin (float) The margin.
  2323. * @public
  2324. * @since 1.4
  2325. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2326. */
  2327. public function SetLeftMargin($margin) {
  2328. //Set left margin
  2329. $this->lMargin = $margin;
  2330. if (($this->page > 0) AND ($this->x < $margin)) {
  2331. $this->x = $margin;
  2332. }
  2333. }
  2334. /**
  2335. * Defines the top margin. The method can be called before creating the first page.
  2336. * @param $margin (float) The margin.
  2337. * @public
  2338. * @since 1.5
  2339. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2340. */
  2341. public function SetTopMargin($margin) {
  2342. //Set top margin
  2343. $this->tMargin = $margin;
  2344. if (($this->page > 0) AND ($this->y < $margin)) {
  2345. $this->y = $margin;
  2346. }
  2347. }
  2348. /**
  2349. * Defines the right margin. The method can be called before creating the first page.
  2350. * @param $margin (float) The margin.
  2351. * @public
  2352. * @since 1.5
  2353. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  2354. */
  2355. public function SetRightMargin($margin) {
  2356. $this->rMargin = $margin;
  2357. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  2358. $this->x = $this->w - $margin;
  2359. }
  2360. }
  2361. /**
  2362. * Set the same internal Cell padding for top, right, bottom, left-
  2363. * @param $pad (float) internal padding.
  2364. * @public
  2365. * @since 2.1.000 (2008-01-09)
  2366. * @see getCellPaddings(), setCellPaddings()
  2367. */
  2368. public function SetCellPadding($pad) {
  2369. if ($pad >= 0) {
  2370. $this->cell_padding['L'] = $pad;
  2371. $this->cell_padding['T'] = $pad;
  2372. $this->cell_padding['R'] = $pad;
  2373. $this->cell_padding['B'] = $pad;
  2374. }
  2375. }
  2376. /**
  2377. * Set the internal Cell paddings.
  2378. * @param $left (float) left padding
  2379. * @param $top (float) top padding
  2380. * @param $right (float) right padding
  2381. * @param $bottom (float) bottom padding
  2382. * @public
  2383. * @since 5.9.000 (2010-10-03)
  2384. * @see getCellPaddings(), SetCellPadding()
  2385. */
  2386. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  2387. if (($left !== '') AND ($left >= 0)) {
  2388. $this->cell_padding['L'] = $left;
  2389. }
  2390. if (($top !== '') AND ($top >= 0)) {
  2391. $this->cell_padding['T'] = $top;
  2392. }
  2393. if (($right !== '') AND ($right >= 0)) {
  2394. $this->cell_padding['R'] = $right;
  2395. }
  2396. if (($bottom !== '') AND ($bottom >= 0)) {
  2397. $this->cell_padding['B'] = $bottom;
  2398. }
  2399. }
  2400. /**
  2401. * Get the internal Cell padding array.
  2402. * @return array of padding values
  2403. * @public
  2404. * @since 5.9.000 (2010-10-03)
  2405. * @see setCellPaddings(), SetCellPadding()
  2406. */
  2407. public function getCellPaddings() {
  2408. return $this->cell_padding;
  2409. }
  2410. /**
  2411. * Set the internal Cell margins.
  2412. * @param $left (float) left margin
  2413. * @param $top (float) top margin
  2414. * @param $right (float) right margin
  2415. * @param $bottom (float) bottom margin
  2416. * @public
  2417. * @since 5.9.000 (2010-10-03)
  2418. * @see getCellMargins()
  2419. */
  2420. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  2421. if (($left !== '') AND ($left >= 0)) {
  2422. $this->cell_margin['L'] = $left;
  2423. }
  2424. if (($top !== '') AND ($top >= 0)) {
  2425. $this->cell_margin['T'] = $top;
  2426. }
  2427. if (($right !== '') AND ($right >= 0)) {
  2428. $this->cell_margin['R'] = $right;
  2429. }
  2430. if (($bottom !== '') AND ($bottom >= 0)) {
  2431. $this->cell_margin['B'] = $bottom;
  2432. }
  2433. }
  2434. /**
  2435. * Get the internal Cell margin array.
  2436. * @return array of margin values
  2437. * @public
  2438. * @since 5.9.000 (2010-10-03)
  2439. * @see setCellMargins()
  2440. */
  2441. public function getCellMargins() {
  2442. return $this->cell_margin;
  2443. }
  2444. /**
  2445. * Adjust the internal Cell padding array to take account of the line width.
  2446. * @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)))
  2447. * @return void|array of adjustments
  2448. * @public
  2449. * @since 5.9.000 (2010-10-03)
  2450. */
  2451. protected function adjustCellPadding($brd=0) {
  2452. if (empty($brd)) {
  2453. return;
  2454. }
  2455. if (is_string($brd)) {
  2456. // convert string to array
  2457. $slen = strlen($brd);
  2458. $newbrd = array();
  2459. for ($i = 0; $i < $slen; ++$i) {
  2460. $newbrd[$brd[$i]] = true;
  2461. }
  2462. $brd = $newbrd;
  2463. } elseif (
  2464. ($brd === 1)
  2465. || ($brd === true)
  2466. || (is_numeric($brd) && ((int)$brd > 0))
  2467. ) {
  2468. $brd = array('LRTB' => true);
  2469. }
  2470. if (!is_array($brd)) {
  2471. return;
  2472. }
  2473. // store current cell padding
  2474. $cp = $this->cell_padding;
  2475. // select border mode
  2476. if (isset($brd['mode'])) {
  2477. $mode = $brd['mode'];
  2478. unset($brd['mode']);
  2479. } else {
  2480. $mode = 'normal';
  2481. }
  2482. // process borders
  2483. foreach ($brd as $border => $style) {
  2484. $line_width = $this->LineWidth;
  2485. if (is_array($style) && isset($style['width'])) {
  2486. // get border width
  2487. $line_width = $style['width'];
  2488. }
  2489. $adj = 0; // line width inside the cell
  2490. switch ($mode) {
  2491. case 'ext': {
  2492. $adj = 0;
  2493. break;
  2494. }
  2495. case 'int': {
  2496. $adj = $line_width;
  2497. break;
  2498. }
  2499. case 'normal':
  2500. default: {
  2501. $adj = ($line_width / 2);
  2502. break;
  2503. }
  2504. }
  2505. // correct internal cell padding if required to avoid overlap between text and lines
  2506. if (
  2507. is_numeric($this->cell_padding['T'])
  2508. && ($this->cell_padding['T'] < $adj)
  2509. && (strpos($border, 'T') !== false)
  2510. ) {
  2511. $this->cell_padding['T'] = $adj;
  2512. }
  2513. if (
  2514. is_numeric($this->cell_padding['R'])
  2515. && ($this->cell_padding['R'] < $adj)
  2516. && (strpos($border, 'R') !== false)
  2517. ) {
  2518. $this->cell_padding['R'] = $adj;
  2519. }
  2520. if (
  2521. is_numeric($this->cell_padding['B'])
  2522. && ($this->cell_padding['B'] < $adj)
  2523. && (strpos($border, 'B') !== false)
  2524. ) {
  2525. $this->cell_padding['B'] = $adj;
  2526. }
  2527. if (
  2528. is_numeric($this->cell_padding['L'])
  2529. && ($this->cell_padding['L'] < $adj)
  2530. && (strpos($border, 'L') !== false)
  2531. ) {
  2532. $this->cell_padding['L'] = $adj;
  2533. }
  2534. }
  2535. return array(
  2536. 'T' => ($this->cell_padding['T'] - $cp['T']),
  2537. 'R' => ($this->cell_padding['R'] - $cp['R']),
  2538. 'B' => ($this->cell_padding['B'] - $cp['B']),
  2539. 'L' => ($this->cell_padding['L'] - $cp['L']),
  2540. );
  2541. }
  2542. /**
  2543. * 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.
  2544. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  2545. * @param $margin (float) Distance from the bottom of the page.
  2546. * @public
  2547. * @since 1.0
  2548. * @see Cell(), MultiCell(), AcceptPageBreak()
  2549. */
  2550. public function SetAutoPageBreak($auto, $margin=0) {
  2551. $this->AutoPageBreak = $auto ? true : false;
  2552. $this->bMargin = $margin;
  2553. $this->PageBreakTrigger = $this->h - $margin;
  2554. }
  2555. /**
  2556. * Return the auto-page-break mode (true or false).
  2557. * @return boolean auto-page-break mode
  2558. * @public
  2559. * @since 5.9.088
  2560. */
  2561. public function getAutoPageBreak() {
  2562. return $this->AutoPageBreak;
  2563. }
  2564. /**
  2565. * Defines the way the document is to be displayed by the viewer.
  2566. * @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>
  2567. * @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>
  2568. * @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>
  2569. * @public
  2570. * @since 1.2
  2571. */
  2572. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  2573. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  2574. $this->ZoomMode = $zoom;
  2575. } else {
  2576. $this->Error('Incorrect zoom display mode: '.$zoom);
  2577. }
  2578. $this->LayoutMode = TCPDF_STATIC::getPageLayoutMode($layout);
  2579. $this->PageMode = TCPDF_STATIC::getPageMode($mode);
  2580. }
  2581. /**
  2582. * 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.
  2583. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  2584. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  2585. * @public
  2586. * @since 1.4
  2587. */
  2588. public function SetCompression($compress=true) {
  2589. $this->compress = false;
  2590. if (function_exists('gzcompress')) {
  2591. if ($compress) {
  2592. if ( !$this->pdfa_mode) {
  2593. $this->compress = true;
  2594. }
  2595. }
  2596. }
  2597. }
  2598. /**
  2599. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  2600. * @param $mode (boolean) If true force sRGB output intent.
  2601. * @public
  2602. * @since 5.9.121 (2011-09-28)
  2603. */
  2604. public function setSRGBmode($mode=false) {
  2605. $this->force_srgb = $mode ? true : false;
  2606. }
  2607. /**
  2608. * Turn on/off Unicode mode for document information dictionary (meta tags).
  2609. * This has effect only when unicode mode is set to false.
  2610. * @param $unicode (boolean) if true set the meta information in Unicode
  2611. * @since 5.9.027 (2010-12-01)
  2612. * @public
  2613. */
  2614. public function SetDocInfoUnicode($unicode=true) {
  2615. $this->docinfounicode = $unicode ? true : false;
  2616. }
  2617. /**
  2618. * Defines the title of the document.
  2619. * @param $title (string) The title.
  2620. * @public
  2621. * @since 1.2
  2622. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  2623. */
  2624. public function SetTitle($title) {
  2625. $this->title = $title;
  2626. }
  2627. /**
  2628. * Defines the subject of the document.
  2629. * @param $subject (string) The subject.
  2630. * @public
  2631. * @since 1.2
  2632. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  2633. */
  2634. public function SetSubject($subject) {
  2635. $this->subject = $subject;
  2636. }
  2637. /**
  2638. * Defines the author of the document.
  2639. * @param $author (string) The name of the author.
  2640. * @public
  2641. * @since 1.2
  2642. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  2643. */
  2644. public function SetAuthor($author) {
  2645. $this->author = $author;
  2646. }
  2647. /**
  2648. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  2649. * @param $keywords (string) The list of keywords.
  2650. * @public
  2651. * @since 1.2
  2652. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  2653. */
  2654. public function SetKeywords($keywords) {
  2655. $this->keywords = $keywords;
  2656. }
  2657. /**
  2658. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  2659. * @param $creator (string) The name of the creator.
  2660. * @public
  2661. * @since 1.2
  2662. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  2663. */
  2664. public function SetCreator($creator) {
  2665. $this->creator = $creator;
  2666. }
  2667. /**
  2668. * Whether to allow local file path in image html tags, when prefixed with file://
  2669. *
  2670. * @param $allowLocalFiles bool true, when local files should be allowed. Otherwise false.
  2671. * @public
  2672. * @since 6.4
  2673. */
  2674. public function SetAllowLocalFiles($allowLocalFiles) {
  2675. $this->allowLocalFiles = (bool) $allowLocalFiles;
  2676. }
  2677. /**
  2678. * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
  2679. * @param $msg (string) The error message
  2680. * @public
  2681. * @since 1.0
  2682. */
  2683. public function Error($msg) {
  2684. // unset all class variables
  2685. $this->_destroy(true);
  2686. if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR) {
  2687. die('<strong>TCPDF ERROR: </strong>'.$msg);
  2688. } else {
  2689. throw new Exception('TCPDF ERROR: '.$msg);
  2690. }
  2691. }
  2692. /**
  2693. * This method begins the generation of the PDF document.
  2694. * It is not necessary to call it explicitly because AddPage() does it automatically.
  2695. * Note: no page is created by this method
  2696. * @public
  2697. * @since 1.0
  2698. * @see AddPage(), Close()
  2699. */
  2700. public function Open() {
  2701. $this->state = 1;
  2702. }
  2703. /**
  2704. * Terminates the PDF document.
  2705. * It is not necessary to call this method explicitly because Output() does it automatically.
  2706. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  2707. * @public
  2708. * @since 1.0
  2709. * @see Open(), Output()
  2710. */
  2711. public function Close() {
  2712. if ($this->state == 3) {
  2713. return;
  2714. }
  2715. if ($this->page == 0) {
  2716. $this->AddPage();
  2717. }
  2718. $this->endLayer();
  2719. if ($this->tcpdflink) {
  2720. // save current graphic settings
  2721. $gvars = $this->getGraphicVars();
  2722. $this->setEqualColumns();
  2723. $this->lastpage(true);
  2724. $this->SetAutoPageBreak(false);
  2725. $this->x = 0;
  2726. $this->y = $this->h - (1 / $this->k);
  2727. $this->lMargin = 0;
  2728. $this->_outSaveGraphicsState();
  2729. $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  2730. $this->SetFont($font, '', 1);
  2731. $this->setTextRenderingMode(0, false, false);
  2732. $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";
  2733. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  2734. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  2735. $this->_outRestoreGraphicsState();
  2736. // restore graphic settings
  2737. $this->setGraphicVars($gvars);
  2738. }
  2739. // close page
  2740. $this->endPage();
  2741. // close document
  2742. $this->_enddoc();
  2743. // unset all class variables (except critical ones)
  2744. $this->_destroy(false);
  2745. }
  2746. /**
  2747. * Move pointer at the specified document page and update page dimensions.
  2748. * @param $pnum (int) page number (1 ... numpages)
  2749. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2750. * @public
  2751. * @since 2.1.000 (2008-01-07)
  2752. * @see getPage(), lastpage(), getNumPages()
  2753. */
  2754. public function setPage($pnum, $resetmargins=false) {
  2755. if (($pnum == $this->page) AND ($this->state == 2)) {
  2756. return;
  2757. }
  2758. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  2759. $this->state = 2;
  2760. // save current graphic settings
  2761. //$gvars = $this->getGraphicVars();
  2762. $oldpage = $this->page;
  2763. $this->page = $pnum;
  2764. $this->wPt = $this->pagedim[$this->page]['w'];
  2765. $this->hPt = $this->pagedim[$this->page]['h'];
  2766. $this->w = $this->pagedim[$this->page]['wk'];
  2767. $this->h = $this->pagedim[$this->page]['hk'];
  2768. $this->tMargin = $this->pagedim[$this->page]['tm'];
  2769. $this->bMargin = $this->pagedim[$this->page]['bm'];
  2770. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  2771. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  2772. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  2773. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  2774. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  2775. // restore graphic settings
  2776. //$this->setGraphicVars($gvars);
  2777. if ($resetmargins) {
  2778. $this->lMargin = $this->pagedim[$this->page]['olm'];
  2779. $this->rMargin = $this->pagedim[$this->page]['orm'];
  2780. $this->SetY($this->tMargin);
  2781. } else {
  2782. // account for booklet mode
  2783. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  2784. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  2785. $this->lMargin += $deltam;
  2786. $this->rMargin -= $deltam;
  2787. }
  2788. }
  2789. } else {
  2790. $this->Error('Wrong page number on setPage() function: '.$pnum);
  2791. }
  2792. }
  2793. /**
  2794. * Reset pointer to the last document page.
  2795. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2796. * @public
  2797. * @since 2.0.000 (2008-01-04)
  2798. * @see setPage(), getPage(), getNumPages()
  2799. */
  2800. public function lastPage($resetmargins=false) {
  2801. $this->setPage($this->getNumPages(), $resetmargins);
  2802. }
  2803. /**
  2804. * Get current document page number.
  2805. * @return int page number
  2806. * @public
  2807. * @since 2.1.000 (2008-01-07)
  2808. * @see setPage(), lastpage(), getNumPages()
  2809. */
  2810. public function getPage() {
  2811. return $this->page;
  2812. }
  2813. /**
  2814. * Get the total number of insered pages.
  2815. * @return int number of pages
  2816. * @public
  2817. * @since 2.1.000 (2008-01-07)
  2818. * @see setPage(), getPage(), lastpage()
  2819. */
  2820. public function getNumPages() {
  2821. return $this->numpages;
  2822. }
  2823. /**
  2824. * Adds a new TOC (Table Of Content) page to the document.
  2825. * @param $orientation (string) page orientation.
  2826. * @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().
  2827. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2828. * @public
  2829. * @since 5.0.001 (2010-05-06)
  2830. * @see AddPage(), startPage(), endPage(), endTOCPage()
  2831. */
  2832. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  2833. $this->AddPage($orientation, $format, $keepmargins, true);
  2834. }
  2835. /**
  2836. * Terminate the current TOC (Table Of Content) page
  2837. * @public
  2838. * @since 5.0.001 (2010-05-06)
  2839. * @see AddPage(), startPage(), endPage(), addTOCPage()
  2840. */
  2841. public function endTOCPage() {
  2842. $this->endPage(true);
  2843. }
  2844. /**
  2845. * 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).
  2846. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  2847. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2848. * @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().
  2849. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2850. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  2851. * @public
  2852. * @since 1.0
  2853. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2854. */
  2855. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  2856. if ($this->inxobj) {
  2857. // we are inside an XObject template
  2858. return;
  2859. }
  2860. if (!isset($this->original_lMargin) OR $keepmargins) {
  2861. $this->original_lMargin = $this->lMargin;
  2862. }
  2863. if (!isset($this->original_rMargin) OR $keepmargins) {
  2864. $this->original_rMargin = $this->rMargin;
  2865. }
  2866. // terminate previous page
  2867. $this->endPage();
  2868. // start new page
  2869. $this->startPage($orientation, $format, $tocpage);
  2870. }
  2871. /**
  2872. * Terminate the current page
  2873. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  2874. * @public
  2875. * @since 4.2.010 (2008-11-14)
  2876. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  2877. */
  2878. public function endPage($tocpage=false) {
  2879. // check if page is already closed
  2880. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  2881. return;
  2882. }
  2883. // print page footer
  2884. $this->setFooter();
  2885. // close page
  2886. $this->_endpage();
  2887. // mark page as closed
  2888. $this->pageopen[$this->page] = false;
  2889. if ($tocpage) {
  2890. $this->tocpage = false;
  2891. }
  2892. }
  2893. /**
  2894. * Starts a new page to the document. The page must be closed using the endPage() function.
  2895. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  2896. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2897. * @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().
  2898. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  2899. * @since 4.2.010 (2008-11-14)
  2900. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2901. * @public
  2902. */
  2903. public function startPage($orientation='', $format='', $tocpage=false) {
  2904. if ($tocpage) {
  2905. $this->tocpage = true;
  2906. }
  2907. // move page numbers of documents to be attached
  2908. if ($this->tocpage) {
  2909. // move reference to unexistent pages (used for page attachments)
  2910. // adjust outlines
  2911. $tmpoutlines = $this->outlines;
  2912. foreach ($tmpoutlines as $key => $outline) {
  2913. if (!$outline['f'] AND ($outline['p'] > $this->numpages)) {
  2914. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  2915. }
  2916. }
  2917. // adjust dests
  2918. $tmpdests = $this->dests;
  2919. foreach ($tmpdests as $key => $dest) {
  2920. if (!$dest['f'] AND ($dest['p'] > $this->numpages)) {
  2921. $this->dests[$key]['p'] = ($dest['p'] + 1);
  2922. }
  2923. }
  2924. // adjust links
  2925. $tmplinks = $this->links;
  2926. foreach ($tmplinks as $key => $link) {
  2927. if (!$link['f'] AND ($link['p'] > $this->numpages)) {
  2928. $this->links[$key]['p'] = ($link['p'] + 1);
  2929. }
  2930. }
  2931. }
  2932. if ($this->numpages > $this->page) {
  2933. // this page has been already added
  2934. $this->setPage($this->page + 1);
  2935. $this->SetY($this->tMargin);
  2936. return;
  2937. }
  2938. // start a new page
  2939. if ($this->state == 0) {
  2940. $this->Open();
  2941. }
  2942. ++$this->numpages;
  2943. $this->swapMargins($this->booklet);
  2944. // save current graphic settings
  2945. $gvars = $this->getGraphicVars();
  2946. // start new page
  2947. $this->_beginpage($orientation, $format);
  2948. // mark page as open
  2949. $this->pageopen[$this->page] = true;
  2950. // restore graphic settings
  2951. $this->setGraphicVars($gvars);
  2952. // mark this point
  2953. $this->setPageMark();
  2954. // print page header
  2955. $this->setHeader();
  2956. // restore graphic settings
  2957. $this->setGraphicVars($gvars);
  2958. // mark this point
  2959. $this->setPageMark();
  2960. // print table header (if any)
  2961. $this->setTableHeader();
  2962. // set mark for empty page check
  2963. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  2964. }
  2965. /**
  2966. * Set start-writing mark on current page stream used to put borders and fills.
  2967. * Borders and fills are always created after content and inserted on the position marked by this method.
  2968. * This function must be called after calling Image() function for a background image.
  2969. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  2970. * @public
  2971. * @since 4.0.016 (2008-07-30)
  2972. */
  2973. public function setPageMark() {
  2974. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  2975. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  2976. $this->setContentMark();
  2977. }
  2978. /**
  2979. * Set start-writing mark on selected page.
  2980. * Borders and fills are always created after content and inserted on the position marked by this method.
  2981. * @param $page (int) page number (default is the current page)
  2982. * @protected
  2983. * @since 4.6.021 (2009-07-20)
  2984. */
  2985. protected function setContentMark($page=0) {
  2986. if ($page <= 0) {
  2987. $page = $this->page;
  2988. }
  2989. if (isset($this->footerlen[$page])) {
  2990. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  2991. } else {
  2992. $this->cntmrk[$page] = $this->pagelen[$page];
  2993. }
  2994. }
  2995. /**
  2996. * Set header data.
  2997. * @param $ln (string) header image logo
  2998. * @param $lw (string) header image logo width in mm
  2999. * @param $ht (string) string to print as title on document header
  3000. * @param $hs (string) string to print on document header
  3001. * @param $tc (array) RGB array color for text.
  3002. * @param $lc (array) RGB array color for line.
  3003. * @public
  3004. */
  3005. public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
  3006. $this->header_logo = $ln;
  3007. $this->header_logo_width = $lw;
  3008. $this->header_title = $ht;
  3009. $this->header_string = $hs;
  3010. $this->header_text_color = $tc;
  3011. $this->header_line_color = $lc;
  3012. }
  3013. /**
  3014. * Set footer data.
  3015. * @param $tc (array) RGB array color for text.
  3016. * @param $lc (array) RGB array color for line.
  3017. * @public
  3018. */
  3019. public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
  3020. $this->footer_text_color = $tc;
  3021. $this->footer_line_color = $lc;
  3022. }
  3023. /**
  3024. * Returns header data:
  3025. * <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>
  3026. * @return array()
  3027. * @public
  3028. * @since 4.0.012 (2008-07-24)
  3029. */
  3030. public function getHeaderData() {
  3031. $ret = array();
  3032. $ret['logo'] = $this->header_logo;
  3033. $ret['logo_width'] = $this->header_logo_width;
  3034. $ret['title'] = $this->header_title;
  3035. $ret['string'] = $this->header_string;
  3036. $ret['text_color'] = $this->header_text_color;
  3037. $ret['line_color'] = $this->header_line_color;
  3038. return $ret;
  3039. }
  3040. /**
  3041. * Set header margin.
  3042. * (minimum distance between header and top page margin)
  3043. * @param $hm (int) distance in user units
  3044. * @public
  3045. */
  3046. public function setHeaderMargin($hm=10) {
  3047. $this->header_margin = $hm;
  3048. }
  3049. /**
  3050. * Returns header margin in user units.
  3051. * @return float
  3052. * @since 4.0.012 (2008-07-24)
  3053. * @public
  3054. */
  3055. public function getHeaderMargin() {
  3056. return $this->header_margin;
  3057. }
  3058. /**
  3059. * Set footer margin.
  3060. * (minimum distance between footer and bottom page margin)
  3061. * @param $fm (int) distance in user units
  3062. * @public
  3063. */
  3064. public function setFooterMargin($fm=10) {
  3065. $this->footer_margin = $fm;
  3066. }
  3067. /**
  3068. * Returns footer margin in user units.
  3069. * @return float
  3070. * @since 4.0.012 (2008-07-24)
  3071. * @public
  3072. */
  3073. public function getFooterMargin() {
  3074. return $this->footer_margin;
  3075. }
  3076. /**
  3077. * Set a flag to print page header.
  3078. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3079. * @public
  3080. */
  3081. public function setPrintHeader($val=true) {
  3082. $this->print_header = $val ? true : false;
  3083. }
  3084. /**
  3085. * Set a flag to print page footer.
  3086. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3087. * @public
  3088. */
  3089. public function setPrintFooter($val=true) {
  3090. $this->print_footer = $val ? true : false;
  3091. }
  3092. /**
  3093. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3094. * @return float
  3095. * @public
  3096. */
  3097. public function getImageRBX() {
  3098. return $this->img_rb_x;
  3099. }
  3100. /**
  3101. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3102. * @return float
  3103. * @public
  3104. */
  3105. public function getImageRBY() {
  3106. return $this->img_rb_y;
  3107. }
  3108. /**
  3109. * Reset the xobject template used by Header() method.
  3110. * @public
  3111. */
  3112. public function resetHeaderTemplate() {
  3113. $this->header_xobjid = false;
  3114. }
  3115. /**
  3116. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3117. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3118. * @public
  3119. */
  3120. public function setHeaderTemplateAutoreset($val=true) {
  3121. $this->header_xobj_autoreset = $val ? true : false;
  3122. }
  3123. /**
  3124. * This method is used to render the page header.
  3125. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3126. * @public
  3127. */
  3128. public function Header() {
  3129. if ($this->header_xobjid === false) {
  3130. // start a new XObject Template
  3131. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3132. $headerfont = $this->getHeaderFont();
  3133. $headerdata = $this->getHeaderData();
  3134. $this->y = $this->header_margin;
  3135. if ($this->rtl) {
  3136. $this->x = $this->w - $this->original_rMargin;
  3137. } else {
  3138. $this->x = $this->original_lMargin;
  3139. }
  3140. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3141. $imgtype = TCPDF_IMAGES::getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3142. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3143. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3144. } elseif ($imgtype == 'svg') {
  3145. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3146. } else {
  3147. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3148. }
  3149. $imgy = $this->getImageRBY();
  3150. } else {
  3151. $imgy = $this->y;
  3152. }
  3153. $cell_height = $this->getCellHeight($headerfont[2] / $this->k);
  3154. // set starting margin for text data cell
  3155. if ($this->getRTL()) {
  3156. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3157. } else {
  3158. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3159. }
  3160. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3161. $this->SetTextColorArray($this->header_text_color);
  3162. // header title
  3163. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3164. $this->SetX($header_x);
  3165. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3166. // header string
  3167. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3168. $this->SetX($header_x);
  3169. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3170. // print an ending header line
  3171. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
  3172. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3173. if ($this->rtl) {
  3174. $this->SetX($this->original_rMargin);
  3175. } else {
  3176. $this->SetX($this->original_lMargin);
  3177. }
  3178. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3179. $this->endTemplate();
  3180. }
  3181. // print header template
  3182. $x = 0;
  3183. $dx = 0;
  3184. if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
  3185. // adjust margins for booklet mode
  3186. $dx = ($this->original_lMargin - $this->original_rMargin);
  3187. }
  3188. if ($this->rtl) {
  3189. $x = $this->w + $dx;
  3190. } else {
  3191. $x = 0 + $dx;
  3192. }
  3193. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  3194. if ($this->header_xobj_autoreset) {
  3195. // reset header xobject template at each page
  3196. $this->header_xobjid = false;
  3197. }
  3198. }
  3199. /**
  3200. * This method is used to render the page footer.
  3201. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3202. * @public
  3203. */
  3204. public function Footer() {
  3205. $cur_y = $this->y;
  3206. $this->SetTextColorArray($this->footer_text_color);
  3207. //set style for cell border
  3208. $line_width = (0.85 / $this->k);
  3209. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
  3210. //print document barcode
  3211. $barcode = $this->getBarcode();
  3212. if (!empty($barcode)) {
  3213. $this->Ln($line_width);
  3214. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  3215. $style = array(
  3216. 'position' => $this->rtl?'R':'L',
  3217. 'align' => $this->rtl?'R':'L',
  3218. 'stretch' => false,
  3219. 'fitwidth' => true,
  3220. 'cellfitalign' => '',
  3221. 'border' => false,
  3222. 'padding' => 0,
  3223. 'fgcolor' => array(0,0,0),
  3224. 'bgcolor' => false,
  3225. 'text' => false
  3226. );
  3227. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  3228. }
  3229. $w_page = isset($this->l['w_page']) ? $this->l['w_page'].' ' : '';
  3230. if (empty($this->pagegroups)) {
  3231. $pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  3232. } else {
  3233. $pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  3234. }
  3235. $this->SetY($cur_y);
  3236. //Print page number
  3237. if ($this->getRTL()) {
  3238. $this->SetX($this->original_rMargin);
  3239. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  3240. } else {
  3241. $this->SetX($this->original_lMargin);
  3242. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  3243. }
  3244. }
  3245. /**
  3246. * This method is used to render the page header.
  3247. * @protected
  3248. * @since 4.0.012 (2008-07-24)
  3249. */
  3250. protected function setHeader() {
  3251. if (!$this->print_header OR ($this->state != 2)) {
  3252. return;
  3253. }
  3254. $this->InHeader = true;
  3255. $this->setGraphicVars($this->default_graphic_vars);
  3256. $temp_thead = $this->thead;
  3257. $temp_theadMargins = $this->theadMargins;
  3258. $lasth = $this->lasth;
  3259. $newline = $this->newline;
  3260. $this->_outSaveGraphicsState();
  3261. $this->rMargin = $this->original_rMargin;
  3262. $this->lMargin = $this->original_lMargin;
  3263. $this->SetCellPadding(0);
  3264. //set current position
  3265. if ($this->rtl) {
  3266. $this->SetXY($this->original_rMargin, $this->header_margin);
  3267. } else {
  3268. $this->SetXY($this->original_lMargin, $this->header_margin);
  3269. }
  3270. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  3271. $this->Header();
  3272. //restore position
  3273. if ($this->rtl) {
  3274. $this->SetXY($this->original_rMargin, $this->tMargin);
  3275. } else {
  3276. $this->SetXY($this->original_lMargin, $this->tMargin);
  3277. }
  3278. $this->_outRestoreGraphicsState();
  3279. $this->lasth = $lasth;
  3280. $this->thead = $temp_thead;
  3281. $this->theadMargins = $temp_theadMargins;
  3282. $this->newline = $newline;
  3283. $this->InHeader = false;
  3284. }
  3285. /**
  3286. * This method is used to render the page footer.
  3287. * @protected
  3288. * @since 4.0.012 (2008-07-24)
  3289. */
  3290. protected function setFooter() {
  3291. if ($this->state != 2) {
  3292. return;
  3293. }
  3294. $this->InFooter = true;
  3295. // save current graphic settings
  3296. $gvars = $this->getGraphicVars();
  3297. // mark this point
  3298. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  3299. $this->_out("\n");
  3300. if ($this->print_footer) {
  3301. $this->setGraphicVars($this->default_graphic_vars);
  3302. $this->current_column = 0;
  3303. $this->num_columns = 1;
  3304. $temp_thead = $this->thead;
  3305. $temp_theadMargins = $this->theadMargins;
  3306. $lasth = $this->lasth;
  3307. $this->_outSaveGraphicsState();
  3308. $this->rMargin = $this->original_rMargin;
  3309. $this->lMargin = $this->original_lMargin;
  3310. $this->SetCellPadding(0);
  3311. //set current position
  3312. $footer_y = $this->h - $this->footer_margin;
  3313. if ($this->rtl) {
  3314. $this->SetXY($this->original_rMargin, $footer_y);
  3315. } else {
  3316. $this->SetXY($this->original_lMargin, $footer_y);
  3317. }
  3318. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  3319. $this->Footer();
  3320. //restore position
  3321. if ($this->rtl) {
  3322. $this->SetXY($this->original_rMargin, $this->tMargin);
  3323. } else {
  3324. $this->SetXY($this->original_lMargin, $this->tMargin);
  3325. }
  3326. $this->_outRestoreGraphicsState();
  3327. $this->lasth = $lasth;
  3328. $this->thead = $temp_thead;
  3329. $this->theadMargins = $temp_theadMargins;
  3330. }
  3331. // restore graphic settings
  3332. $this->setGraphicVars($gvars);
  3333. $this->current_column = $gvars['current_column'];
  3334. $this->num_columns = $gvars['num_columns'];
  3335. // calculate footer length
  3336. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  3337. $this->InFooter = false;
  3338. }
  3339. /**
  3340. * Check if we are on the page body (excluding page header and footer).
  3341. * @return true if we are not in page header nor in page footer, false otherwise.
  3342. * @protected
  3343. * @since 5.9.091 (2011-06-15)
  3344. */
  3345. protected function inPageBody() {
  3346. return (($this->InHeader === false) AND ($this->InFooter === false));
  3347. }
  3348. /**
  3349. * This method is used to render the table header on new page (if any).
  3350. * @protected
  3351. * @since 4.5.030 (2009-03-25)
  3352. */
  3353. protected function setTableHeader() {
  3354. if ($this->num_columns > 1) {
  3355. // multi column mode
  3356. return;
  3357. }
  3358. if (isset($this->theadMargins['top'])) {
  3359. // restore the original top-margin
  3360. $this->tMargin = $this->theadMargins['top'];
  3361. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3362. $this->y = $this->tMargin;
  3363. }
  3364. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  3365. // set margins
  3366. $prev_lMargin = $this->lMargin;
  3367. $prev_rMargin = $this->rMargin;
  3368. $prev_cell_padding = $this->cell_padding;
  3369. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  3370. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  3371. $this->cell_padding = $this->theadMargins['cell_padding'];
  3372. if ($this->rtl) {
  3373. $this->x = $this->w - $this->rMargin;
  3374. } else {
  3375. $this->x = $this->lMargin;
  3376. }
  3377. // account for special "cell" mode
  3378. if ($this->theadMargins['cell']) {
  3379. if ($this->rtl) {
  3380. $this->x -= $this->cell_padding['R'];
  3381. } else {
  3382. $this->x += $this->cell_padding['L'];
  3383. }
  3384. }
  3385. $gvars = $this->getGraphicVars();
  3386. if (!empty($this->theadMargins['gvars'])) {
  3387. // set the correct graphic style
  3388. $this->setGraphicVars($this->theadMargins['gvars']);
  3389. $this->rMargin = $gvars['rMargin'];
  3390. $this->lMargin = $gvars['lMargin'];
  3391. }
  3392. // print table header
  3393. $this->writeHTML($this->thead, false, false, false, false, '');
  3394. $this->setGraphicVars($gvars);
  3395. // set new top margin to skip the table headers
  3396. if (!isset($this->theadMargins['top'])) {
  3397. $this->theadMargins['top'] = $this->tMargin;
  3398. }
  3399. // store end of header position
  3400. if (!isset($this->columns[0]['th'])) {
  3401. $this->columns[0]['th'] = array();
  3402. }
  3403. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  3404. $this->tMargin = $this->y;
  3405. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3406. $this->lasth = 0;
  3407. $this->lMargin = $prev_lMargin;
  3408. $this->rMargin = $prev_rMargin;
  3409. $this->cell_padding = $prev_cell_padding;
  3410. }
  3411. }
  3412. /**
  3413. * Returns the current page number.
  3414. * @return int page number
  3415. * @public
  3416. * @since 1.0
  3417. * @see getAliasNbPages()
  3418. */
  3419. public function PageNo() {
  3420. return $this->page;
  3421. }
  3422. /**
  3423. * Returns the array of spot colors.
  3424. * @return (array) Spot colors array.
  3425. * @public
  3426. * @since 6.0.038 (2013-09-30)
  3427. */
  3428. public function getAllSpotColors() {
  3429. return $this->spot_colors;
  3430. }
  3431. /**
  3432. * Defines a new spot color.
  3433. * It can be expressed in RGB components or gray scale.
  3434. * The method can be called before the first page is created and the value is retained from page to page.
  3435. * @param $name (string) Full name of the spot color.
  3436. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  3437. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  3438. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  3439. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  3440. * @public
  3441. * @since 4.0.024 (2008-09-12)
  3442. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3443. */
  3444. public function AddSpotColor($name, $c, $m, $y, $k) {
  3445. if (!isset($this->spot_colors[$name])) {
  3446. $i = (1 + count($this->spot_colors));
  3447. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  3448. }
  3449. }
  3450. /**
  3451. * Set the spot color for the specified type ('draw', 'fill', 'text').
  3452. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3453. * @param $name (string) Name of the spot color.
  3454. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3455. * @return (string) PDF color command.
  3456. * @public
  3457. * @since 5.9.125 (2011-10-03)
  3458. */
  3459. public function setSpotColor($type, $name, $tint=100) {
  3460. $spotcolor = TCPDF_COLORS::getSpotColor($name, $this->spot_colors);
  3461. if ($spotcolor === false) {
  3462. $this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
  3463. }
  3464. $tint = (max(0, min(100, $tint)) / 100);
  3465. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  3466. switch ($type) {
  3467. case 'draw': {
  3468. $pdfcolor .= sprintf('CS %F SCN', $tint);
  3469. $this->DrawColor = $pdfcolor;
  3470. $this->strokecolor = $spotcolor;
  3471. break;
  3472. }
  3473. case 'fill': {
  3474. $pdfcolor .= sprintf('cs %F scn', $tint);
  3475. $this->FillColor = $pdfcolor;
  3476. $this->bgcolor = $spotcolor;
  3477. break;
  3478. }
  3479. case 'text': {
  3480. $pdfcolor .= sprintf('cs %F scn', $tint);
  3481. $this->TextColor = $pdfcolor;
  3482. $this->fgcolor = $spotcolor;
  3483. break;
  3484. }
  3485. }
  3486. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3487. if ($this->state == 2) {
  3488. $this->_out($pdfcolor);
  3489. }
  3490. if ($this->inxobj) {
  3491. // we are inside an XObject template
  3492. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  3493. }
  3494. return $pdfcolor;
  3495. }
  3496. /**
  3497. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  3498. * @param $name (string) Name of the spot color.
  3499. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3500. * @public
  3501. * @since 4.0.024 (2008-09-12)
  3502. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3503. */
  3504. public function SetDrawSpotColor($name, $tint=100) {
  3505. $this->setSpotColor('draw', $name, $tint);
  3506. }
  3507. /**
  3508. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  3509. * @param $name (string) Name of the spot color.
  3510. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3511. * @public
  3512. * @since 4.0.024 (2008-09-12)
  3513. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  3514. */
  3515. public function SetFillSpotColor($name, $tint=100) {
  3516. $this->setSpotColor('fill', $name, $tint);
  3517. }
  3518. /**
  3519. * Defines the spot color used for text.
  3520. * @param $name (string) Name of the spot color.
  3521. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3522. * @public
  3523. * @since 4.0.024 (2008-09-12)
  3524. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  3525. */
  3526. public function SetTextSpotColor($name, $tint=100) {
  3527. $this->setSpotColor('text', $name, $tint);
  3528. }
  3529. /**
  3530. * Set the color array for the specified type ('draw', 'fill', 'text').
  3531. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3532. * The method can be called before the first page is created and the value is retained from page to page.
  3533. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3534. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  3535. * @param $ret (boolean) If true do not send the PDF command.
  3536. * @return (string) The PDF command or empty string.
  3537. * @public
  3538. * @since 3.1.000 (2008-06-11)
  3539. */
  3540. public function setColorArray($type, $color, $ret=false) {
  3541. if (is_array($color)) {
  3542. $color = array_values($color);
  3543. // component: grey, RGB red or CMYK cyan
  3544. $c = isset($color[0]) ? $color[0] : -1;
  3545. // component: RGB green or CMYK magenta
  3546. $m = isset($color[1]) ? $color[1] : -1;
  3547. // component: RGB blue or CMYK yellow
  3548. $y = isset($color[2]) ? $color[2] : -1;
  3549. // component: CMYK black
  3550. $k = isset($color[3]) ? $color[3] : -1;
  3551. // color name
  3552. $name = isset($color[4]) ? $color[4] : '';
  3553. if ($c >= 0) {
  3554. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  3555. }
  3556. }
  3557. return '';
  3558. }
  3559. /**
  3560. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  3561. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3562. * The method can be called before the first page is created and the value is retained from page to page.
  3563. * @param $color (array) Array of colors (1, 3 or 4 values).
  3564. * @param $ret (boolean) If true do not send the PDF command.
  3565. * @return string the PDF command
  3566. * @public
  3567. * @since 3.1.000 (2008-06-11)
  3568. * @see SetDrawColor()
  3569. */
  3570. public function SetDrawColorArray($color, $ret=false) {
  3571. return $this->setColorArray('draw', $color, $ret);
  3572. }
  3573. /**
  3574. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  3575. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3576. * The method can be called before the first page is created and the value is retained from page to page.
  3577. * @param $color (array) Array of colors (1, 3 or 4 values).
  3578. * @param $ret (boolean) If true do not send the PDF command.
  3579. * @public
  3580. * @since 3.1.000 (2008-6-11)
  3581. * @see SetFillColor()
  3582. */
  3583. public function SetFillColorArray($color, $ret=false) {
  3584. return $this->setColorArray('fill', $color, $ret);
  3585. }
  3586. /**
  3587. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  3588. * The method can be called before the first page is created and the value is retained from page to page.
  3589. * @param $color (array) Array of colors (1, 3 or 4 values).
  3590. * @param $ret (boolean) If true do not send the PDF command.
  3591. * @public
  3592. * @since 3.1.000 (2008-6-11)
  3593. * @see SetFillColor()
  3594. */
  3595. public function SetTextColorArray($color, $ret=false) {
  3596. return $this->setColorArray('text', $color, $ret);
  3597. }
  3598. /**
  3599. * Defines the color used by the specified type ('draw', 'fill', 'text').
  3600. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3601. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3602. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3603. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3604. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3605. * @param $ret (boolean) If true do not send the command.
  3606. * @param $name (string) spot color name (if any)
  3607. * @return (string) The PDF command or empty string.
  3608. * @public
  3609. * @since 5.9.125 (2011-10-03)
  3610. */
  3611. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3612. // set default values
  3613. if (!is_numeric($col1)) {
  3614. $col1 = 0;
  3615. }
  3616. if (!is_numeric($col2)) {
  3617. $col2 = -1;
  3618. }
  3619. if (!is_numeric($col3)) {
  3620. $col3 = -1;
  3621. }
  3622. if (!is_numeric($col4)) {
  3623. $col4 = -1;
  3624. }
  3625. // set color by case
  3626. $suffix = '';
  3627. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  3628. // Grey scale
  3629. $col1 = max(0, min(255, $col1));
  3630. $intcolor = array('G' => $col1);
  3631. $pdfcolor = sprintf('%F ', ($col1 / 255));
  3632. $suffix = 'g';
  3633. } elseif ($col4 == -1) {
  3634. // RGB
  3635. $col1 = max(0, min(255, $col1));
  3636. $col2 = max(0, min(255, $col2));
  3637. $col3 = max(0, min(255, $col3));
  3638. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  3639. $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  3640. $suffix = 'rg';
  3641. } else {
  3642. $col1 = max(0, min(100, $col1));
  3643. $col2 = max(0, min(100, $col2));
  3644. $col3 = max(0, min(100, $col3));
  3645. $col4 = max(0, min(100, $col4));
  3646. if (empty($name)) {
  3647. // CMYK
  3648. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  3649. $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  3650. $suffix = 'k';
  3651. } else {
  3652. // SPOT COLOR
  3653. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  3654. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  3655. $pdfcolor = $this->setSpotColor($type, $name, 100);
  3656. }
  3657. }
  3658. switch ($type) {
  3659. case 'draw': {
  3660. $pdfcolor .= strtoupper($suffix);
  3661. $this->DrawColor = $pdfcolor;
  3662. $this->strokecolor = $intcolor;
  3663. break;
  3664. }
  3665. case 'fill': {
  3666. $pdfcolor .= $suffix;
  3667. $this->FillColor = $pdfcolor;
  3668. $this->bgcolor = $intcolor;
  3669. break;
  3670. }
  3671. case 'text': {
  3672. $pdfcolor .= $suffix;
  3673. $this->TextColor = $pdfcolor;
  3674. $this->fgcolor = $intcolor;
  3675. break;
  3676. }
  3677. }
  3678. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3679. if (($type != 'text') AND ($this->state == 2)) {
  3680. if (!$ret) {
  3681. $this->_out($pdfcolor);
  3682. }
  3683. return $pdfcolor;
  3684. }
  3685. return '';
  3686. }
  3687. /**
  3688. * 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.
  3689. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3690. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3691. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3692. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3693. * @param $ret (boolean) If true do not send the command.
  3694. * @param $name (string) spot color name (if any)
  3695. * @return string the PDF command
  3696. * @public
  3697. * @since 1.3
  3698. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  3699. */
  3700. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3701. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  3702. }
  3703. /**
  3704. * 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.
  3705. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3706. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3707. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3708. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3709. * @param $ret (boolean) If true do not send the command.
  3710. * @param $name (string) Spot color name (if any).
  3711. * @return (string) The PDF command.
  3712. * @public
  3713. * @since 1.3
  3714. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  3715. */
  3716. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3717. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  3718. }
  3719. /**
  3720. * 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.
  3721. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3722. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3723. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3724. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3725. * @param $ret (boolean) If true do not send the command.
  3726. * @param $name (string) Spot color name (if any).
  3727. * @return (string) Empty string.
  3728. * @public
  3729. * @since 1.3
  3730. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  3731. */
  3732. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3733. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  3734. }
  3735. /**
  3736. * Returns the length of a string in user unit. A font must be selected.<br>
  3737. * @param $s (string) The string whose length is to be computed
  3738. * @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.
  3739. * @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.
  3740. * @param $fontsize (float) Font size in points. The default value is the current size.
  3741. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3742. * @return mixed int total string length or array of characted widths
  3743. * @author Nicola Asuni
  3744. * @public
  3745. * @since 1.2
  3746. */
  3747. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3748. 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);
  3749. }
  3750. /**
  3751. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  3752. * @param $sa (string) The array of chars whose total length is to be computed
  3753. * @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.
  3754. * @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.
  3755. * @param $fontsize (float) Font size in points. The default value is the current size.
  3756. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3757. * @return mixed int total string length or array of characted widths
  3758. * @author Nicola Asuni
  3759. * @public
  3760. * @since 2.4.000 (2008-03-06)
  3761. */
  3762. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3763. // store current values
  3764. if (!TCPDF_STATIC::empty_string($fontname)) {
  3765. $prev_FontFamily = $this->FontFamily;
  3766. $prev_FontStyle = $this->FontStyle;
  3767. $prev_FontSizePt = $this->FontSizePt;
  3768. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  3769. }
  3770. // convert UTF-8 array to Latin1 if required
  3771. if ($this->isunicode AND (!$this->isUnicodeFont())) {
  3772. $sa = TCPDF_FONTS::UTF8ArrToLatin1Arr($sa);
  3773. }
  3774. $w = 0; // total width
  3775. $wa = array(); // array of characters widths
  3776. foreach ($sa as $ck => $char) {
  3777. // character width
  3778. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  3779. $wa[] = $cw;
  3780. $w += $cw;
  3781. }
  3782. // restore previous values
  3783. if (!TCPDF_STATIC::empty_string($fontname)) {
  3784. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  3785. }
  3786. if ($getarray) {
  3787. return $wa;
  3788. }
  3789. return $w;
  3790. }
  3791. /**
  3792. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
  3793. * @param $char (int) The char code whose length is to be returned
  3794. * @param $notlast (boolean) If false ignore the font-spacing.
  3795. * @return float char width
  3796. * @author Nicola Asuni
  3797. * @public
  3798. * @since 2.4.000 (2008-03-06)
  3799. */
  3800. public function GetCharWidth($char, $notlast=true) {
  3801. // get raw width
  3802. $chw = $this->getRawCharWidth($char);
  3803. if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
  3804. // increase/decrease font spacing
  3805. $chw += $this->font_spacing;
  3806. }
  3807. if ($this->font_stretching != 100) {
  3808. // fixed stretching mode
  3809. $chw *= ($this->font_stretching / 100);
  3810. }
  3811. return $chw;
  3812. }
  3813. /**
  3814. * Returns the length of the char in user unit for the current font.
  3815. * @param $char (int) The char code whose length is to be returned
  3816. * @return float char width
  3817. * @author Nicola Asuni
  3818. * @public
  3819. * @since 5.9.000 (2010-09-28)
  3820. */
  3821. public function getRawCharWidth($char) {
  3822. if ($char == 173) {
  3823. // SHY character will not be printed
  3824. return (0);
  3825. }
  3826. if (isset($this->CurrentFont['cw'][$char])) {
  3827. $w = $this->CurrentFont['cw'][$char];
  3828. } elseif (isset($this->CurrentFont['dw'])) {
  3829. // default width
  3830. $w = $this->CurrentFont['dw'];
  3831. } elseif (isset($this->CurrentFont['cw'][32])) {
  3832. // default width
  3833. $w = $this->CurrentFont['cw'][32];
  3834. } else {
  3835. $w = 600;
  3836. }
  3837. return $this->getAbsFontMeasure($w);
  3838. }
  3839. /**
  3840. * Returns the numbero of characters in a string.
  3841. * @param $s (string) The input string.
  3842. * @return int number of characters
  3843. * @public
  3844. * @since 2.0.0001 (2008-01-07)
  3845. */
  3846. public function GetNumChars($s) {
  3847. if ($this->isUnicodeFont()) {
  3848. return count(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont));
  3849. }
  3850. return strlen($s);
  3851. }
  3852. /**
  3853. * Fill the list of available fonts ($this->fontlist).
  3854. * @protected
  3855. * @since 4.0.013 (2008-07-28)
  3856. */
  3857. protected function getFontsList() {
  3858. if (($fontsdir = opendir(TCPDF_FONTS::_getfontpath())) !== false) {
  3859. while (($file = readdir($fontsdir)) !== false) {
  3860. if (substr($file, -4) == '.php') {
  3861. array_push($this->fontlist, strtolower(basename($file, '.php')));
  3862. }
  3863. }
  3864. closedir($fontsdir);
  3865. }
  3866. }
  3867. /**
  3868. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  3869. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  3870. * 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.
  3871. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  3872. * @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>
  3873. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  3874. * @return array containing the font data, or false in case of error.
  3875. * @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.
  3876. * @public
  3877. * @since 1.5
  3878. * @see SetFont(), setFontSubsetting()
  3879. */
  3880. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  3881. if ($subset === 'default') {
  3882. $subset = $this->font_subsetting;
  3883. }
  3884. if ($this->pdfa_mode) {
  3885. $subset = false;
  3886. }
  3887. if (TCPDF_STATIC::empty_string($family)) {
  3888. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  3889. $family = $this->FontFamily;
  3890. } else {
  3891. $this->Error('Empty font family');
  3892. }
  3893. }
  3894. // move embedded styles on $style
  3895. if (substr($family, -1) == 'I') {
  3896. $style .= 'I';
  3897. $family = substr($family, 0, -1);
  3898. }
  3899. if (substr($family, -1) == 'B') {
  3900. $style .= 'B';
  3901. $family = substr($family, 0, -1);
  3902. }
  3903. // normalize family name
  3904. $family = strtolower($family);
  3905. if ((!$this->isunicode) AND ($family == 'arial')) {
  3906. $family = 'helvetica';
  3907. }
  3908. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  3909. $style = '';
  3910. }
  3911. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  3912. // all fonts must be embedded
  3913. $family = 'pdfa'.$family;
  3914. }
  3915. $tempstyle = strtoupper($style);
  3916. $style = '';
  3917. // underline
  3918. if (strpos($tempstyle, 'U') !== false) {
  3919. $this->underline = true;
  3920. } else {
  3921. $this->underline = false;
  3922. }
  3923. // line-through (deleted)
  3924. if (strpos($tempstyle, 'D') !== false) {
  3925. $this->linethrough = true;
  3926. } else {
  3927. $this->linethrough = false;
  3928. }
  3929. // overline
  3930. if (strpos($tempstyle, 'O') !== false) {
  3931. $this->overline = true;
  3932. } else {
  3933. $this->overline = false;
  3934. }
  3935. // bold
  3936. if (strpos($tempstyle, 'B') !== false) {
  3937. $style .= 'B';
  3938. }
  3939. // oblique
  3940. if (strpos($tempstyle, 'I') !== false) {
  3941. $style .= 'I';
  3942. }
  3943. $bistyle = $style;
  3944. $fontkey = $family.$style;
  3945. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  3946. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  3947. // check if the font has been already added
  3948. $fb = $this->getFontBuffer($fontkey);
  3949. if ($fb !== false) {
  3950. if ($this->inxobj) {
  3951. // we are inside an XObject template
  3952. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  3953. }
  3954. return $fontdata;
  3955. }
  3956. // get specified font directory (if any)
  3957. $fontdir = false;
  3958. if (!TCPDF_STATIC::empty_string($fontfile)) {
  3959. $fontdir = dirname($fontfile);
  3960. if (TCPDF_STATIC::empty_string($fontdir) OR ($fontdir == '.')) {
  3961. $fontdir = '';
  3962. } else {
  3963. $fontdir .= '/';
  3964. }
  3965. }
  3966. // true when the font style variation is missing
  3967. $missing_style = false;
  3968. // search and include font file
  3969. if (TCPDF_STATIC::empty_string($fontfile) OR (!@TCPDF_STATIC::file_exists($fontfile))) {
  3970. // build a standard filenames for specified font
  3971. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  3972. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3973. if (TCPDF_STATIC::empty_string($fontfile)) {
  3974. $missing_style = true;
  3975. // try to remove the style part
  3976. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  3977. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3978. }
  3979. }
  3980. // include font file
  3981. if (!TCPDF_STATIC::empty_string($fontfile) AND (@TCPDF_STATIC::file_exists($fontfile))) {
  3982. include($fontfile);
  3983. } else {
  3984. $this->Error('Could not include font definition file: '.$family.'');
  3985. }
  3986. // check font parameters
  3987. if ((!isset($type)) OR (!isset($cw))) {
  3988. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  3989. }
  3990. // SET default parameters
  3991. if (!isset($file) OR TCPDF_STATIC::empty_string($file)) {
  3992. $file = '';
  3993. }
  3994. if (!isset($enc) OR TCPDF_STATIC::empty_string($enc)) {
  3995. $enc = '';
  3996. }
  3997. if (!isset($cidinfo) OR TCPDF_STATIC::empty_string($cidinfo)) {
  3998. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  3999. $cidinfo['uni2cid'] = array();
  4000. }
  4001. if (!isset($ctg) OR TCPDF_STATIC::empty_string($ctg)) {
  4002. $ctg = '';
  4003. }
  4004. if (!isset($desc) OR TCPDF_STATIC::empty_string($desc)) {
  4005. $desc = array();
  4006. }
  4007. if (!isset($up) OR TCPDF_STATIC::empty_string($up)) {
  4008. $up = -100;
  4009. }
  4010. if (!isset($ut) OR TCPDF_STATIC::empty_string($ut)) {
  4011. $ut = 50;
  4012. }
  4013. if (!isset($cw) OR TCPDF_STATIC::empty_string($cw)) {
  4014. $cw = array();
  4015. }
  4016. if (!isset($dw) OR TCPDF_STATIC::empty_string($dw)) {
  4017. // set default width
  4018. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  4019. $dw = $desc['MissingWidth'];
  4020. } elseif (isset($cw[32])) {
  4021. $dw = $cw[32];
  4022. } else {
  4023. $dw = 600;
  4024. }
  4025. }
  4026. ++$this->numfonts;
  4027. if ($type == 'core') {
  4028. $name = $this->CoreFonts[$fontkey];
  4029. $subset = false;
  4030. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  4031. $subset = false;
  4032. } elseif ($type == 'TrueTypeUnicode') {
  4033. $enc = 'Identity-H';
  4034. } elseif ($type == 'cidfont0') {
  4035. if ($this->pdfa_mode) {
  4036. $this->Error('All fonts must be embedded in PDF/A mode!');
  4037. }
  4038. } else {
  4039. $this->Error('Unknow font type: '.$type.'');
  4040. }
  4041. // set name if unset
  4042. if (!isset($name) OR empty($name)) {
  4043. $name = $fontkey;
  4044. }
  4045. // create artificial font style variations if missing (only works with non-embedded fonts)
  4046. if (($type != 'core') AND $missing_style) {
  4047. // style variations
  4048. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4049. $name .= $styles[$bistyle];
  4050. // artificial bold
  4051. if (strpos($bistyle, 'B') !== false) {
  4052. if (isset($desc['StemV'])) {
  4053. // from normal to bold
  4054. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4055. } else {
  4056. // bold
  4057. $desc['StemV'] = 123;
  4058. }
  4059. }
  4060. // artificial italic
  4061. if (strpos($bistyle, 'I') !== false) {
  4062. if (isset($desc['ItalicAngle'])) {
  4063. $desc['ItalicAngle'] -= 11;
  4064. } else {
  4065. $desc['ItalicAngle'] = -11;
  4066. }
  4067. if (isset($desc['Flags'])) {
  4068. $desc['Flags'] |= 64; //bit 7
  4069. } else {
  4070. $desc['Flags'] = 64;
  4071. }
  4072. }
  4073. }
  4074. // check if the array of characters bounding boxes is defined
  4075. if (!isset($cbbox)) {
  4076. $cbbox = array();
  4077. }
  4078. // initialize subsetchars
  4079. $subsetchars = array_fill(0, 255, true);
  4080. $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));
  4081. if ($this->inxobj) {
  4082. // we are inside an XObject template
  4083. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4084. }
  4085. if (isset($diff) AND (!empty($diff))) {
  4086. //Search existing encodings
  4087. $d = 0;
  4088. $nb = count($this->diffs);
  4089. for ($i=1; $i <= $nb; ++$i) {
  4090. if ($this->diffs[$i] == $diff) {
  4091. $d = $i;
  4092. break;
  4093. }
  4094. }
  4095. if ($d == 0) {
  4096. $d = $nb + 1;
  4097. $this->diffs[$d] = $diff;
  4098. }
  4099. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4100. }
  4101. if (!TCPDF_STATIC::empty_string($file)) {
  4102. if (!isset($this->FontFiles[$file])) {
  4103. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4104. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4105. } elseif ($type != 'core') {
  4106. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4107. }
  4108. } else {
  4109. // update fontkeys that are sharing this font file
  4110. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4111. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4112. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4113. }
  4114. }
  4115. }
  4116. return $fontdata;
  4117. }
  4118. /**
  4119. * Sets the font used to print character strings.
  4120. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4121. * The method can be called before the first page is created and the font is retained from page to page.
  4122. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4123. * 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 />
  4124. * @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.
  4125. * @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.
  4126. * @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
  4127. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4128. * @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.
  4129. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4130. * @author Nicola Asuni
  4131. * @public
  4132. * @since 1.0
  4133. * @see AddFont(), SetFontSize()
  4134. */
  4135. public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
  4136. //Select a font; size given in points
  4137. if ($size === null) {
  4138. $size = $this->FontSizePt;
  4139. }
  4140. if ($size < 0) {
  4141. $size = 0;
  4142. }
  4143. // try to add font (if not already added)
  4144. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4145. $this->FontFamily = $fontdata['family'];
  4146. $this->FontStyle = $fontdata['style'];
  4147. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  4148. // save subset chars of the previous font
  4149. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4150. }
  4151. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4152. $this->SetFontSize($size, $out);
  4153. }
  4154. /**
  4155. * Defines the size of the current font.
  4156. * @param $size (float) The font size in points.
  4157. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4158. * @public
  4159. * @since 1.0
  4160. * @see SetFont()
  4161. */
  4162. public function SetFontSize($size, $out=true) {
  4163. $size = (float)$size;
  4164. // font size in points
  4165. $this->FontSizePt = $size;
  4166. // font size in user units
  4167. $this->FontSize = $size / $this->k;
  4168. // calculate some font metrics
  4169. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4170. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4171. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  4172. } else {
  4173. $font_height = $size * 1.219;
  4174. }
  4175. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  4176. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  4177. }
  4178. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  4179. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  4180. }
  4181. if (!isset($font_ascent) AND !isset($font_descent)) {
  4182. // core font
  4183. $font_ascent = 0.76 * $font_height;
  4184. $font_descent = $font_height - $font_ascent;
  4185. } elseif (!isset($font_descent)) {
  4186. $font_descent = $font_height - $font_ascent;
  4187. } elseif (!isset($font_ascent)) {
  4188. $font_ascent = $font_height - $font_descent;
  4189. }
  4190. $this->FontAscent = ($font_ascent / $this->k);
  4191. $this->FontDescent = ($font_descent / $this->k);
  4192. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i'])) AND ($this->state == 2)) {
  4193. $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  4194. }
  4195. }
  4196. /**
  4197. * Returns the bounding box of the current font in user units.
  4198. * @return array
  4199. * @public
  4200. * @since 5.9.152 (2012-03-23)
  4201. */
  4202. public function getFontBBox() {
  4203. $fbbox = array();
  4204. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4205. $tmpbbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4206. $fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
  4207. } else {
  4208. // Find max width
  4209. if (isset($this->CurrentFont['desc']['MaxWidth'])) {
  4210. $maxw = $this->getAbsFontMeasure(intval($this->CurrentFont['desc']['MaxWidth']));
  4211. } else {
  4212. $maxw = 0;
  4213. if (isset($this->CurrentFont['desc']['MissingWidth'])) {
  4214. $maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
  4215. }
  4216. if (isset($this->CurrentFont['desc']['AvgWidth'])) {
  4217. $maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
  4218. }
  4219. if (isset($this->CurrentFont['dw'])) {
  4220. $maxw = max($maxw, $this->CurrentFont['dw']);
  4221. }
  4222. foreach ($this->CurrentFont['cw'] as $char => $w) {
  4223. $maxw = max($maxw, $w);
  4224. }
  4225. if ($maxw == 0) {
  4226. $maxw = 600;
  4227. }
  4228. $maxw = $this->getAbsFontMeasure($maxw);
  4229. }
  4230. $fbbox = array(0, (0 - $this->FontDescent), $maxw, $this->FontAscent);
  4231. }
  4232. return $fbbox;
  4233. }
  4234. /**
  4235. * Convert a relative font measure into absolute value.
  4236. * @param $s (int) Font measure.
  4237. * @return float Absolute measure.
  4238. * @since 5.9.186 (2012-09-13)
  4239. */
  4240. public function getAbsFontMeasure($s) {
  4241. return ($s * $this->FontSize / 1000);
  4242. }
  4243. /**
  4244. * Returns the glyph bounding box of the specified character in the current font in user units.
  4245. * @param $char (int) Input character code.
  4246. * @return mixed array(xMin, yMin, xMax, yMax) or FALSE if not defined.
  4247. * @since 5.9.186 (2012-09-13)
  4248. */
  4249. public function getCharBBox($char) {
  4250. $c = intval($char);
  4251. if (isset($this->CurrentFont['cw'][$c])) {
  4252. // glyph is defined ... use zero width & height for glyphs without outlines
  4253. $result = array(0,0,0,0);
  4254. if (isset($this->CurrentFont['cbbox'][$c])) {
  4255. $result = $this->CurrentFont['cbbox'][$c];
  4256. }
  4257. return array_map(array($this,'getAbsFontMeasure'), $result);
  4258. }
  4259. return false;
  4260. }
  4261. /**
  4262. * Return the font descent value
  4263. * @param $font (string) font name
  4264. * @param $style (string) font style
  4265. * @param $size (float) The size (in points)
  4266. * @return int font descent
  4267. * @public
  4268. * @author Nicola Asuni
  4269. * @since 4.9.003 (2010-03-30)
  4270. */
  4271. public function getFontDescent($font, $style='', $size=0) {
  4272. $fontdata = $this->AddFont($font, $style);
  4273. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4274. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  4275. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  4276. } else {
  4277. $descent = (1.219 * 0.24 * $size);
  4278. }
  4279. return ($descent / $this->k);
  4280. }
  4281. /**
  4282. * Return the font ascent value.
  4283. * @param $font (string) font name
  4284. * @param $style (string) font style
  4285. * @param $size (float) The size (in points)
  4286. * @return int font ascent
  4287. * @public
  4288. * @author Nicola Asuni
  4289. * @since 4.9.003 (2010-03-30)
  4290. */
  4291. public function getFontAscent($font, $style='', $size=0) {
  4292. $fontdata = $this->AddFont($font, $style);
  4293. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4294. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  4295. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  4296. } else {
  4297. $ascent = 1.219 * 0.76 * $size;
  4298. }
  4299. return ($ascent / $this->k);
  4300. }
  4301. /**
  4302. * Return true in the character is present in the specified font.
  4303. * @param $char (mixed) Character to check (integer value or string)
  4304. * @param $font (string) Font name (family name).
  4305. * @param $style (string) Font style.
  4306. * @return (boolean) true if the char is defined, false otherwise.
  4307. * @public
  4308. * @since 5.9.153 (2012-03-28)
  4309. */
  4310. public function isCharDefined($char, $font='', $style='') {
  4311. if (is_string($char)) {
  4312. // get character code
  4313. $char = TCPDF_FONTS::UTF8StringToArray($char, $this->isunicode, $this->CurrentFont);
  4314. $char = $char[0];
  4315. }
  4316. if (TCPDF_STATIC::empty_string($font)) {
  4317. if (TCPDF_STATIC::empty_string($style)) {
  4318. return (isset($this->CurrentFont['cw'][intval($char)]));
  4319. }
  4320. $font = $this->FontFamily;
  4321. }
  4322. $fontdata = $this->AddFont($font, $style);
  4323. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4324. return (isset($fontinfo['cw'][intval($char)]));
  4325. }
  4326. /**
  4327. * Replace missing font characters on selected font with specified substitutions.
  4328. * @param $text (string) Text to process.
  4329. * @param $font (string) Font name (family name).
  4330. * @param $style (string) Font style.
  4331. * @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.
  4332. * @return (string) Processed text.
  4333. * @public
  4334. * @since 5.9.153 (2012-03-28)
  4335. */
  4336. public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
  4337. if (empty($subs)) {
  4338. return $text;
  4339. }
  4340. if (TCPDF_STATIC::empty_string($font)) {
  4341. $font = $this->FontFamily;
  4342. }
  4343. $fontdata = $this->AddFont($font, $style);
  4344. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4345. $uniarr = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  4346. foreach ($uniarr as $k => $chr) {
  4347. if (!isset($fontinfo['cw'][$chr])) {
  4348. // this character is missing on the selected font
  4349. if (isset($subs[$chr])) {
  4350. // we have available substitutions
  4351. if (is_array($subs[$chr])) {
  4352. foreach($subs[$chr] as $s) {
  4353. if (isset($fontinfo['cw'][$s])) {
  4354. $uniarr[$k] = $s;
  4355. break;
  4356. }
  4357. }
  4358. } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
  4359. $uniarr[$k] = $subs[$chr];
  4360. }
  4361. }
  4362. }
  4363. }
  4364. return TCPDF_FONTS::UniArrSubString(TCPDF_FONTS::UTF8ArrayToUniArray($uniarr, $this->isunicode));
  4365. }
  4366. /**
  4367. * Defines the default monospaced font.
  4368. * @param $font (string) Font name.
  4369. * @public
  4370. * @since 4.5.025
  4371. */
  4372. public function SetDefaultMonospacedFont($font) {
  4373. $this->default_monospaced_font = $font;
  4374. }
  4375. /**
  4376. * 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 />
  4377. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  4378. * @public
  4379. * @since 1.5
  4380. * @see Cell(), Write(), Image(), Link(), SetLink()
  4381. */
  4382. public function AddLink() {
  4383. // create a new internal link
  4384. $n = count($this->links) + 1;
  4385. $this->links[$n] = array('p' => 0, 'y' => 0, 'f' => false);
  4386. return $n;
  4387. }
  4388. /**
  4389. * Defines the page and position a link points to.
  4390. * @param $link (int) The link identifier returned by AddLink()
  4391. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  4392. * @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.
  4393. * @public
  4394. * @since 1.5
  4395. * @see AddLink()
  4396. */
  4397. public function SetLink($link, $y=0, $page=-1) {
  4398. $fixed = false;
  4399. if (!empty($page) AND (substr($page, 0, 1) == '*')) {
  4400. $page = intval(substr($page, 1));
  4401. // this page number will not be changed when moving/add/deleting pages
  4402. $fixed = true;
  4403. }
  4404. if ($page < 0) {
  4405. $page = $this->page;
  4406. }
  4407. if ($y == -1) {
  4408. $y = $this->y;
  4409. }
  4410. $this->links[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
  4411. }
  4412. /**
  4413. * Puts a link on a rectangular area of the page.
  4414. * 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.
  4415. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4416. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4417. * @param $w (float) Width of the rectangle
  4418. * @param $h (float) Height of the rectangle
  4419. * @param $link (mixed) URL or identifier returned by AddLink()
  4420. * @param $spaces (int) number of spaces on the text to link
  4421. * @public
  4422. * @since 1.5
  4423. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  4424. */
  4425. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  4426. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  4427. }
  4428. /**
  4429. * Puts a markup annotation on a rectangular area of the page.
  4430. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  4431. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4432. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4433. * @param $w (float) Width of the rectangle
  4434. * @param $h (float) Height of the rectangle
  4435. * @param $text (string) annotation text or alternate content
  4436. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  4437. * @param $spaces (int) number of spaces on the text to link
  4438. * @public
  4439. * @since 4.0.018 (2008-08-06)
  4440. */
  4441. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  4442. if ($this->inxobj) {
  4443. // store parameters for later use on template
  4444. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  4445. return;
  4446. }
  4447. if ($x === '') {
  4448. $x = $this->x;
  4449. }
  4450. if ($y === '') {
  4451. $y = $this->y;
  4452. }
  4453. // check page for no-write regions and adapt page margins if necessary
  4454. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  4455. // recalculate coordinates to account for graphic transformations
  4456. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  4457. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  4458. $maxid = count($this->transfmatrix[$i]) - 1;
  4459. for ($j=$maxid; $j >= 0; --$j) {
  4460. $ctm = $this->transfmatrix[$i][$j];
  4461. if (isset($ctm['a'])) {
  4462. $x = $x * $this->k;
  4463. $y = ($this->h - $y) * $this->k;
  4464. $w = $w * $this->k;
  4465. $h = $h * $this->k;
  4466. // top left
  4467. $xt = $x;
  4468. $yt = $y;
  4469. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4470. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4471. // top right
  4472. $xt = $x + $w;
  4473. $yt = $y;
  4474. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4475. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4476. // bottom left
  4477. $xt = $x;
  4478. $yt = $y - $h;
  4479. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4480. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4481. // bottom right
  4482. $xt = $x + $w;
  4483. $yt = $y - $h;
  4484. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4485. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4486. // new coordinates (rectangle area)
  4487. $x = min($x1, $x2, $x3, $x4);
  4488. $y = max($y1, $y2, $y3, $y4);
  4489. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  4490. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  4491. $x = $x / $this->k;
  4492. $y = $this->h - ($y / $this->k);
  4493. }
  4494. }
  4495. }
  4496. }
  4497. if ($this->page <= 0) {
  4498. $page = 1;
  4499. } else {
  4500. $page = $this->page;
  4501. }
  4502. if (!isset($this->PageAnnots[$page])) {
  4503. $this->PageAnnots[$page] = array();
  4504. }
  4505. $this->PageAnnots[$page][] = array('n' => ++$this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  4506. if (!$this->pdfa_mode || ($this->pdfa_mode && $this->pdfa_version == 3)) {
  4507. if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC::empty_string($opt['FS']))
  4508. AND (@TCPDF_STATIC::file_exists($opt['FS']) OR TCPDF_STATIC::isValidURL($opt['FS']))
  4509. AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  4510. $this->embeddedfiles[basename($opt['FS'])] = array('f' => ++$this->n, 'n' => ++$this->n, 'file' => $opt['FS']);
  4511. }
  4512. }
  4513. // Add widgets annotation's icons
  4514. if (isset($opt['mk']['i']) AND @TCPDF_STATIC::file_exists($opt['mk']['i'])) {
  4515. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  4516. }
  4517. if (isset($opt['mk']['ri']) AND @TCPDF_STATIC::file_exists($opt['mk']['ri'])) {
  4518. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4519. }
  4520. if (isset($opt['mk']['ix']) AND @TCPDF_STATIC::file_exists($opt['mk']['ix'])) {
  4521. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4522. }
  4523. }
  4524. /**
  4525. * Embedd the attached files.
  4526. * @since 4.4.000 (2008-12-07)
  4527. * @protected
  4528. * @see Annotation()
  4529. */
  4530. protected function _putEmbeddedFiles() {
  4531. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  4532. // embedded files are not allowed in PDF/A mode version 1 and 2
  4533. return;
  4534. }
  4535. reset($this->embeddedfiles);
  4536. foreach ($this->embeddedfiles as $filename => $filedata) {
  4537. $data = $this->getCachedFileContents($filedata['file']);
  4538. if ($data !== FALSE) {
  4539. $rawsize = strlen($data);
  4540. if ($rawsize > 0) {
  4541. // update name tree
  4542. $this->efnames[$filename] = $filedata['f'].' 0 R';
  4543. // embedded file specification object
  4544. $out = $this->_getobj($filedata['f'])."\n";
  4545. $out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
  4546. $out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
  4547. $out .= ' /AFRelationship /Source';
  4548. $out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
  4549. $out .= "\n".'endobj';
  4550. $this->_out($out);
  4551. // embedded file object
  4552. $filter = '';
  4553. if ($this->compress) {
  4554. $data = gzcompress($data);
  4555. $filter = ' /Filter /FlateDecode';
  4556. }
  4557. if ($this->pdfa_version == 3) {
  4558. $filter = ' /Subtype /text#2Fxml';
  4559. }
  4560. $stream = $this->_getrawstream($data, $filedata['n']);
  4561. $out = $this->_getobj($filedata['n'])."\n";
  4562. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
  4563. $out .= ' stream'."\n".$stream."\n".'endstream';
  4564. $out .= "\n".'endobj';
  4565. $this->_out($out);
  4566. }
  4567. }
  4568. }
  4569. }
  4570. /**
  4571. * Prints a text cell at the specified position.
  4572. * This method allows to place a string precisely on the page.
  4573. * @param $x (float) Abscissa of the cell origin
  4574. * @param $y (float) Ordinate of the cell origin
  4575. * @param $txt (string) String to print
  4576. * @param $fstroke (int) outline size in user units (false = disable)
  4577. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  4578. * @param $ffill (boolean) if true fills the text
  4579. * @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)))
  4580. * @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.
  4581. * @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>
  4582. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4583. * @param $link (mixed) URL or identifier returned by AddLink().
  4584. * @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.
  4585. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4586. * @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>
  4587. * @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>
  4588. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  4589. * @public
  4590. * @since 1.0
  4591. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  4592. */
  4593. 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) {
  4594. $textrendermode = $this->textrendermode;
  4595. $textstrokewidth = $this->textstrokewidth;
  4596. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  4597. $this->SetXY($x, $y, $rtloff);
  4598. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  4599. // restore previous rendering mode
  4600. $this->textrendermode = $textrendermode;
  4601. $this->textstrokewidth = $textstrokewidth;
  4602. }
  4603. /**
  4604. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  4605. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  4606. * This method is called automatically and should not be called directly by the application.
  4607. * @return boolean
  4608. * @public
  4609. * @since 1.4
  4610. * @see SetAutoPageBreak()
  4611. */
  4612. public function AcceptPageBreak() {
  4613. if ($this->num_columns > 1) {
  4614. // multi column mode
  4615. if ($this->current_column < ($this->num_columns - 1)) {
  4616. // go to next column
  4617. $this->selectColumn($this->current_column + 1);
  4618. } elseif ($this->AutoPageBreak) {
  4619. // add a new page
  4620. $this->AddPage();
  4621. // set first column
  4622. $this->selectColumn(0);
  4623. }
  4624. // avoid page breaking from checkPageBreak()
  4625. return false;
  4626. }
  4627. return $this->AutoPageBreak;
  4628. }
  4629. /**
  4630. * Add page if needed.
  4631. * @param $h (float) Cell height. Default value: 0.
  4632. * @param $y (mixed) starting y position, leave empty for current position.
  4633. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  4634. * @return boolean true in case of page break, false otherwise.
  4635. * @since 3.2.000 (2008-07-01)
  4636. * @protected
  4637. */
  4638. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  4639. if (TCPDF_STATIC::empty_string($y)) {
  4640. $y = $this->y;
  4641. }
  4642. $current_page = $this->page;
  4643. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  4644. if ($addpage) {
  4645. //Automatic page break
  4646. $x = $this->x;
  4647. $this->AddPage($this->CurOrientation);
  4648. $this->y = $this->tMargin;
  4649. $oldpage = $this->page - 1;
  4650. if ($this->rtl) {
  4651. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  4652. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  4653. } else {
  4654. $this->x = $x;
  4655. }
  4656. } else {
  4657. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  4658. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  4659. } else {
  4660. $this->x = $x;
  4661. }
  4662. }
  4663. }
  4664. return true;
  4665. }
  4666. if ($current_page != $this->page) {
  4667. // account for columns mode
  4668. return true;
  4669. }
  4670. return false;
  4671. }
  4672. /**
  4673. * 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 />
  4674. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4675. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4676. * @param $h (float) Cell height. Default value: 0.
  4677. * @param $txt (string) String to print. Default value: empty string.
  4678. * @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)))
  4679. * @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.
  4680. * @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>
  4681. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4682. * @param $link (mixed) URL or identifier returned by AddLink().
  4683. * @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.
  4684. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4685. * @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>
  4686. * @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>
  4687. * @public
  4688. * @since 1.0
  4689. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  4690. */
  4691. 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') {
  4692. $prev_cell_margin = $this->cell_margin;
  4693. $prev_cell_padding = $this->cell_padding;
  4694. $this->adjustCellPadding($border);
  4695. if (!$ignore_min_height) {
  4696. $min_cell_height = $this->getCellHeight($this->FontSize);
  4697. if ($h < $min_cell_height) {
  4698. $h = $min_cell_height;
  4699. }
  4700. }
  4701. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  4702. // apply text shadow if enabled
  4703. if ($this->txtshadow['enabled']) {
  4704. // save data
  4705. $x = $this->x;
  4706. $y = $this->y;
  4707. $bc = $this->bgcolor;
  4708. $fc = $this->fgcolor;
  4709. $sc = $this->strokecolor;
  4710. $alpha = $this->alpha;
  4711. // print shadow
  4712. $this->x += $this->txtshadow['depth_w'];
  4713. $this->y += $this->txtshadow['depth_h'];
  4714. $this->SetFillColorArray($this->txtshadow['color']);
  4715. $this->SetTextColorArray($this->txtshadow['color']);
  4716. $this->SetDrawColorArray($this->txtshadow['color']);
  4717. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4718. $this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
  4719. }
  4720. if ($this->state == 2) {
  4721. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4722. }
  4723. //restore data
  4724. $this->x = $x;
  4725. $this->y = $y;
  4726. $this->SetFillColorArray($bc);
  4727. $this->SetTextColorArray($fc);
  4728. $this->SetDrawColorArray($sc);
  4729. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4730. $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
  4731. }
  4732. }
  4733. if ($this->state == 2) {
  4734. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4735. }
  4736. $this->cell_padding = $prev_cell_padding;
  4737. $this->cell_margin = $prev_cell_margin;
  4738. }
  4739. /**
  4740. * 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 />
  4741. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4742. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4743. * @param $h (float) Cell height. Default value: 0.
  4744. * @param $txt (string) String to print. Default value: empty string.
  4745. * @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)))
  4746. * @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.
  4747. * @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>
  4748. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4749. * @param $link (mixed) URL or identifier returned by AddLink().
  4750. * @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.
  4751. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4752. * @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>
  4753. * @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>
  4754. * @return string containing cell code
  4755. * @protected
  4756. * @since 1.0
  4757. * @see Cell()
  4758. */
  4759. 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') {
  4760. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  4761. $txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);
  4762. $prev_cell_margin = $this->cell_margin;
  4763. $prev_cell_padding = $this->cell_padding;
  4764. $txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);
  4765. $rs = ''; //string to be returned
  4766. $this->adjustCellPadding($border);
  4767. if (!$ignore_min_height) {
  4768. $min_cell_height = $this->getCellHeight($this->FontSize);
  4769. if ($h < $min_cell_height) {
  4770. $h = $min_cell_height;
  4771. }
  4772. }
  4773. $k = $this->k;
  4774. // check page for no-write regions and adapt page margins if necessary
  4775. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  4776. if ($this->rtl) {
  4777. $x = $this->x - $this->cell_margin['R'];
  4778. } else {
  4779. $x = $this->x + $this->cell_margin['L'];
  4780. }
  4781. $y = $this->y + $this->cell_margin['T'];
  4782. $prev_font_stretching = $this->font_stretching;
  4783. $prev_font_spacing = $this->font_spacing;
  4784. // cell vertical alignment
  4785. switch ($calign) {
  4786. case 'A': {
  4787. // font top
  4788. switch ($valign) {
  4789. case 'T': {
  4790. // top
  4791. $y -= $this->cell_padding['T'];
  4792. break;
  4793. }
  4794. case 'B': {
  4795. // bottom
  4796. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  4797. break;
  4798. }
  4799. default:
  4800. case 'C':
  4801. case 'M': {
  4802. // center
  4803. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  4804. break;
  4805. }
  4806. }
  4807. break;
  4808. }
  4809. case 'L': {
  4810. // font baseline
  4811. switch ($valign) {
  4812. case 'T': {
  4813. // top
  4814. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  4815. break;
  4816. }
  4817. case 'B': {
  4818. // bottom
  4819. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  4820. break;
  4821. }
  4822. default:
  4823. case 'C':
  4824. case 'M': {
  4825. // center
  4826. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  4827. break;
  4828. }
  4829. }
  4830. break;
  4831. }
  4832. case 'D': {
  4833. // font bottom
  4834. switch ($valign) {
  4835. case 'T': {
  4836. // top
  4837. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  4838. break;
  4839. }
  4840. case 'B': {
  4841. // bottom
  4842. $y -= ($h - $this->cell_padding['B']);
  4843. break;
  4844. }
  4845. default:
  4846. case 'C':
  4847. case 'M': {
  4848. // center
  4849. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  4850. break;
  4851. }
  4852. }
  4853. break;
  4854. }
  4855. case 'B': {
  4856. // cell bottom
  4857. $y -= $h;
  4858. break;
  4859. }
  4860. case 'C':
  4861. case 'M': {
  4862. // cell center
  4863. $y -= ($h / 2);
  4864. break;
  4865. }
  4866. default:
  4867. case 'T': {
  4868. // cell top
  4869. break;
  4870. }
  4871. }
  4872. // text vertical alignment
  4873. switch ($valign) {
  4874. case 'T': {
  4875. // top
  4876. $yt = $y + $this->cell_padding['T'];
  4877. break;
  4878. }
  4879. case 'B': {
  4880. // bottom
  4881. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  4882. break;
  4883. }
  4884. default:
  4885. case 'C':
  4886. case 'M': {
  4887. // center
  4888. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  4889. break;
  4890. }
  4891. }
  4892. $basefonty = $yt + $this->FontAscent;
  4893. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  4894. if ($this->rtl) {
  4895. $w = $x - $this->lMargin;
  4896. } else {
  4897. $w = $this->w - $this->rMargin - $x;
  4898. }
  4899. }
  4900. $s = '';
  4901. // fill and borders
  4902. if (is_string($border) AND (strlen($border) == 4)) {
  4903. // full border
  4904. $border = 1;
  4905. }
  4906. if ($fill OR ($border == 1)) {
  4907. if ($fill) {
  4908. $op = ($border == 1) ? 'B' : 'f';
  4909. } else {
  4910. $op = 'S';
  4911. }
  4912. if ($this->rtl) {
  4913. $xk = (($x - $w) * $k);
  4914. } else {
  4915. $xk = ($x * $k);
  4916. }
  4917. $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  4918. }
  4919. // draw borders
  4920. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  4921. if ($txt != '') {
  4922. $txt2 = $txt;
  4923. if ($this->isunicode) {
  4924. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  4925. $txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);
  4926. } else {
  4927. $unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values
  4928. $unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);
  4929. // replace thai chars (if any)
  4930. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  4931. // number of chars
  4932. $numchars = count($unicode);
  4933. // po pla, for far, for fan
  4934. $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
  4935. // do chada, to patak
  4936. $lowtail = array(0x0e0e, 0x0e0f);
  4937. // mai hun arkad, sara i, sara ii, sara ue, sara uee
  4938. $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
  4939. // mai ek, mai tho, mai tri, mai chattawa, karan
  4940. $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
  4941. // sara u, sara uu, pinthu
  4942. $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
  4943. $output = array();
  4944. for ($i = 0; $i < $numchars; $i++) {
  4945. if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
  4946. $ch0 = $unicode[$i];
  4947. $ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
  4948. $ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
  4949. $chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
  4950. if (in_array($ch0, $tonemark)) {
  4951. if ($chn == 0x0e33) {
  4952. // sara um
  4953. if (in_array($ch1, $longtail)) {
  4954. // tonemark at upper left
  4955. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4956. } else {
  4957. // tonemark at upper right (normal position)
  4958. $output[] = $ch0;
  4959. }
  4960. } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
  4961. // tonemark at lower left
  4962. $output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
  4963. } elseif (in_array($ch1, $upvowel)) {
  4964. if (in_array($ch2, $longtail)) {
  4965. // tonemark at upper left
  4966. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4967. } else {
  4968. // tonemark at upper right (normal position)
  4969. $output[] = $ch0;
  4970. }
  4971. } else {
  4972. // tonemark at lower right
  4973. $output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
  4974. }
  4975. } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
  4976. // add lower left nikhahit and sara aa
  4977. if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
  4978. $output[] = 0xf711;
  4979. $this->CurrentFont['subsetchars'][0xf711] = true;
  4980. $output[] = 0x0e32;
  4981. $this->CurrentFont['subsetchars'][0x0e32] = true;
  4982. } else {
  4983. $output[] = $ch0;
  4984. }
  4985. } elseif (in_array($ch1, $longtail)) {
  4986. if ($ch0 == 0x0e31) {
  4987. // lower left mai hun arkad
  4988. $output[] = $this->replaceChar($ch0, 0xf710);
  4989. } elseif (in_array($ch0, $upvowel)) {
  4990. // lower left
  4991. $output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
  4992. } elseif ($ch0 == 0x0e47) {
  4993. // lower left mai tai koo
  4994. $output[] = $this->replaceChar($ch0, 0xf712);
  4995. } else {
  4996. // normal character
  4997. $output[] = $ch0;
  4998. }
  4999. } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
  5000. // lower vowel
  5001. $output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
  5002. } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
  5003. // yo ying without lower part
  5004. $output[] = $this->replaceChar($ch0, 0xf70f);
  5005. } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
  5006. // tho santan without lower part
  5007. $output[] = $this->replaceChar($ch0, 0xf700);
  5008. } else {
  5009. $output[] = $ch0;
  5010. }
  5011. } else {
  5012. // non-thai character
  5013. $output[] = $unicode[$i];
  5014. }
  5015. }
  5016. $unicode = $output;
  5017. // update font subsetchars
  5018. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  5019. } // end of K_THAI_TOPCHARS
  5020. $txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);
  5021. }
  5022. }
  5023. $txt2 = TCPDF_STATIC::_escape($txt2);
  5024. // get current text width (considering general font stretching and spacing)
  5025. $txwidth = $this->GetStringWidth($txt);
  5026. $width = $txwidth;
  5027. // check for stretch mode
  5028. if ($stretch > 0) {
  5029. // calculate ratio between cell width and text width
  5030. if ($width <= 0) {
  5031. $ratio = 1;
  5032. } else {
  5033. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  5034. }
  5035. // check if stretching is required
  5036. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5037. // the text will be stretched to fit cell width
  5038. if ($stretch > 2) {
  5039. // set new character spacing
  5040. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5041. } else {
  5042. // set new horizontal stretching
  5043. $this->font_stretching *= $ratio;
  5044. }
  5045. // recalculate text width (the text fills the entire cell)
  5046. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5047. // reset alignment
  5048. $align = '';
  5049. }
  5050. }
  5051. if ($this->font_stretching != 100) {
  5052. // apply font stretching
  5053. $rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
  5054. }
  5055. if ($this->font_spacing != 0) {
  5056. // increase/decrease font spacing
  5057. $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
  5058. }
  5059. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5060. $s .= 'q '.$this->TextColor.' ';
  5061. }
  5062. // rendering mode
  5063. $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
  5064. // count number of spaces
  5065. $ns = substr_count($txt, chr(32));
  5066. // Justification
  5067. $spacewidth = 0;
  5068. if (($align == 'J') AND ($ns > 0)) {
  5069. if ($this->isUnicodeFont()) {
  5070. // get string width without spaces
  5071. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5072. // calculate average space width
  5073. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);
  5074. if ($this->font_stretching != 100) {
  5075. // word spacing is affected by stretching
  5076. $spacewidth /= ($this->font_stretching / 100);
  5077. }
  5078. // set word position to be used with TJ operator
  5079. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
  5080. $unicode_justification = true;
  5081. } else {
  5082. // get string width
  5083. $width = $txwidth;
  5084. // new space width
  5085. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5086. if ($this->font_stretching != 100) {
  5087. // word spacing (Tw) is affected by stretching
  5088. $spacewidth /= ($this->font_stretching / 100);
  5089. }
  5090. // set word spacing
  5091. $rs .= sprintf('BT %F Tw ET ', $spacewidth);
  5092. }
  5093. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5094. }
  5095. // replace carriage return characters
  5096. $txt2 = str_replace("\r", ' ', $txt2);
  5097. switch ($align) {
  5098. case 'C': {
  5099. $dx = ($w - $width) / 2;
  5100. break;
  5101. }
  5102. case 'R': {
  5103. if ($this->rtl) {
  5104. $dx = $this->cell_padding['R'];
  5105. } else {
  5106. $dx = $w - $width - $this->cell_padding['R'];
  5107. }
  5108. break;
  5109. }
  5110. case 'L': {
  5111. if ($this->rtl) {
  5112. $dx = $w - $width - $this->cell_padding['L'];
  5113. } else {
  5114. $dx = $this->cell_padding['L'];
  5115. }
  5116. break;
  5117. }
  5118. case 'J':
  5119. default: {
  5120. if ($this->rtl) {
  5121. $dx = $this->cell_padding['R'];
  5122. } else {
  5123. $dx = $this->cell_padding['L'];
  5124. }
  5125. break;
  5126. }
  5127. }
  5128. if ($this->rtl) {
  5129. $xdx = $x - $dx - $width;
  5130. } else {
  5131. $xdx = $x + $dx;
  5132. }
  5133. $xdk = $xdx * $k;
  5134. // print text
  5135. $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5136. if (isset($uniblock)) {
  5137. // print overlapping characters as separate string
  5138. $xshift = 0; // horizontal shift
  5139. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5140. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5141. foreach ($uniblock as $uk => $uniarr) {
  5142. if (($uk % 2) == 0) {
  5143. // x space to skip
  5144. if ($spacewidth != 0) {
  5145. // justification shift
  5146. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5147. }
  5148. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5149. } else {
  5150. // character to print
  5151. $topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);
  5152. $topchr = TCPDF_STATIC::_escape($topchr);
  5153. $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5154. }
  5155. }
  5156. }
  5157. if ($this->underline) {
  5158. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5159. }
  5160. if ($this->linethrough) {
  5161. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5162. }
  5163. if ($this->overline) {
  5164. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5165. }
  5166. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5167. $s .= ' Q';
  5168. }
  5169. if ($link) {
  5170. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5171. }
  5172. }
  5173. // output cell
  5174. if ($s) {
  5175. // output cell
  5176. $rs .= $s;
  5177. if ($this->font_spacing != 0) {
  5178. // reset font spacing mode
  5179. $rs .= ' BT 0 Tc ET';
  5180. }
  5181. if ($this->font_stretching != 100) {
  5182. // reset font stretching mode
  5183. $rs .= ' BT 100 Tz ET';
  5184. }
  5185. }
  5186. // reset word spacing
  5187. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  5188. $rs .= ' BT 0 Tw ET';
  5189. }
  5190. // reset stretching and spacing
  5191. $this->font_stretching = $prev_font_stretching;
  5192. $this->font_spacing = $prev_font_spacing;
  5193. $this->lasth = $h;
  5194. if ($ln > 0) {
  5195. //Go to the beginning of the next line
  5196. $this->y = $y + $h + $this->cell_margin['B'];
  5197. if ($ln == 1) {
  5198. if ($this->rtl) {
  5199. $this->x = $this->w - $this->rMargin;
  5200. } else {
  5201. $this->x = $this->lMargin;
  5202. }
  5203. }
  5204. } else {
  5205. // go left or right by case
  5206. if ($this->rtl) {
  5207. $this->x = $x - $w - $this->cell_margin['L'];
  5208. } else {
  5209. $this->x = $x + $w + $this->cell_margin['R'];
  5210. }
  5211. }
  5212. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  5213. $rs = $gstyles.$rs;
  5214. $this->cell_padding = $prev_cell_padding;
  5215. $this->cell_margin = $prev_cell_margin;
  5216. return $rs;
  5217. }
  5218. /**
  5219. * Replace a char if is defined on the current font.
  5220. * @param $oldchar (int) Integer code (unicode) of the character to replace.
  5221. * @param $newchar (int) Integer code (unicode) of the new character.
  5222. * @return int the replaced char or the old char in case the new char i not defined
  5223. * @protected
  5224. * @since 5.9.167 (2012-06-22)
  5225. */
  5226. protected function replaceChar($oldchar, $newchar) {
  5227. if ($this->isCharDefined($newchar)) {
  5228. // add the new char on the subset list
  5229. $this->CurrentFont['subsetchars'][$newchar] = true;
  5230. // return the new character
  5231. return $newchar;
  5232. }
  5233. // return the old char
  5234. return $oldchar;
  5235. }
  5236. /**
  5237. * Returns the code to draw the cell border
  5238. * @param $x (float) X coordinate.
  5239. * @param $y (float) Y coordinate.
  5240. * @param $w (float) Cell width.
  5241. * @param $h (float) Cell height.
  5242. * @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)))
  5243. * @return string containing cell border code
  5244. * @protected
  5245. * @see SetLineStyle()
  5246. * @since 5.7.000 (2010-08-02)
  5247. */
  5248. protected function getCellBorder($x, $y, $w, $h, $brd) {
  5249. $s = ''; // string to be returned
  5250. if (empty($brd)) {
  5251. return $s;
  5252. }
  5253. if ($brd == 1) {
  5254. $brd = array('LRTB' => true);
  5255. }
  5256. // calculate coordinates for border
  5257. $k = $this->k;
  5258. if ($this->rtl) {
  5259. $xeL = ($x - $w) * $k;
  5260. $xeR = $x * $k;
  5261. } else {
  5262. $xeL = $x * $k;
  5263. $xeR = ($x + $w) * $k;
  5264. }
  5265. $yeL = (($this->h - ($y + $h)) * $k);
  5266. $yeT = (($this->h - $y) * $k);
  5267. $xeT = $xeL;
  5268. $xeB = $xeR;
  5269. $yeR = $yeT;
  5270. $yeB = $yeL;
  5271. if (is_string($brd)) {
  5272. // convert string to array
  5273. $slen = strlen($brd);
  5274. $newbrd = array();
  5275. for ($i = 0; $i < $slen; ++$i) {
  5276. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  5277. }
  5278. $brd = $newbrd;
  5279. }
  5280. if (isset($brd['mode'])) {
  5281. $mode = $brd['mode'];
  5282. unset($brd['mode']);
  5283. } else {
  5284. $mode = 'normal';
  5285. }
  5286. foreach ($brd as $border => $style) {
  5287. if (is_array($style) AND !empty($style)) {
  5288. // apply border style
  5289. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  5290. $s .= $this->SetLineStyle($style, true)."\n";
  5291. }
  5292. switch ($mode) {
  5293. case 'ext': {
  5294. $off = (($this->LineWidth / 2) * $k);
  5295. $xL = $xeL - $off;
  5296. $xR = $xeR + $off;
  5297. $yT = $yeT + $off;
  5298. $yL = $yeL - $off;
  5299. $xT = $xL;
  5300. $xB = $xR;
  5301. $yR = $yT;
  5302. $yB = $yL;
  5303. $w += $this->LineWidth;
  5304. $h += $this->LineWidth;
  5305. break;
  5306. }
  5307. case 'int': {
  5308. $off = ($this->LineWidth / 2) * $k;
  5309. $xL = $xeL + $off;
  5310. $xR = $xeR - $off;
  5311. $yT = $yeT - $off;
  5312. $yL = $yeL + $off;
  5313. $xT = $xL;
  5314. $xB = $xR;
  5315. $yR = $yT;
  5316. $yB = $yL;
  5317. $w -= $this->LineWidth;
  5318. $h -= $this->LineWidth;
  5319. break;
  5320. }
  5321. case 'normal':
  5322. default: {
  5323. $xL = $xeL;
  5324. $xT = $xeT;
  5325. $xB = $xeB;
  5326. $xR = $xeR;
  5327. $yL = $yeL;
  5328. $yT = $yeT;
  5329. $yB = $yeB;
  5330. $yR = $yeR;
  5331. break;
  5332. }
  5333. }
  5334. // draw borders by case
  5335. if (strlen($border) == 4) {
  5336. $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  5337. } elseif (strlen($border) == 3) {
  5338. if (strpos($border,'B') === false) { // LTR
  5339. $s .= sprintf('%F %F m ', $xL, $yL);
  5340. $s .= sprintf('%F %F l ', $xT, $yT);
  5341. $s .= sprintf('%F %F l ', $xR, $yR);
  5342. $s .= sprintf('%F %F l ', $xB, $yB);
  5343. $s .= 'S ';
  5344. } elseif (strpos($border,'L') === false) { // TRB
  5345. $s .= sprintf('%F %F m ', $xT, $yT);
  5346. $s .= sprintf('%F %F l ', $xR, $yR);
  5347. $s .= sprintf('%F %F l ', $xB, $yB);
  5348. $s .= sprintf('%F %F l ', $xL, $yL);
  5349. $s .= 'S ';
  5350. } elseif (strpos($border,'T') === false) { // RBL
  5351. $s .= sprintf('%F %F m ', $xR, $yR);
  5352. $s .= sprintf('%F %F l ', $xB, $yB);
  5353. $s .= sprintf('%F %F l ', $xL, $yL);
  5354. $s .= sprintf('%F %F l ', $xT, $yT);
  5355. $s .= 'S ';
  5356. } elseif (strpos($border,'R') === false) { // BLT
  5357. $s .= sprintf('%F %F m ', $xB, $yB);
  5358. $s .= sprintf('%F %F l ', $xL, $yL);
  5359. $s .= sprintf('%F %F l ', $xT, $yT);
  5360. $s .= sprintf('%F %F l ', $xR, $yR);
  5361. $s .= 'S ';
  5362. }
  5363. } elseif (strlen($border) == 2) {
  5364. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  5365. $s .= sprintf('%F %F m ', $xL, $yL);
  5366. $s .= sprintf('%F %F l ', $xT, $yT);
  5367. $s .= sprintf('%F %F l ', $xR, $yR);
  5368. $s .= 'S ';
  5369. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  5370. $s .= sprintf('%F %F m ', $xT, $yT);
  5371. $s .= sprintf('%F %F l ', $xR, $yR);
  5372. $s .= sprintf('%F %F l ', $xB, $yB);
  5373. $s .= 'S ';
  5374. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  5375. $s .= sprintf('%F %F m ', $xR, $yR);
  5376. $s .= sprintf('%F %F l ', $xB, $yB);
  5377. $s .= sprintf('%F %F l ', $xL, $yL);
  5378. $s .= 'S ';
  5379. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  5380. $s .= sprintf('%F %F m ', $xB, $yB);
  5381. $s .= sprintf('%F %F l ', $xL, $yL);
  5382. $s .= sprintf('%F %F l ', $xT, $yT);
  5383. $s .= 'S ';
  5384. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  5385. $s .= sprintf('%F %F m ', $xL, $yL);
  5386. $s .= sprintf('%F %F l ', $xT, $yT);
  5387. $s .= 'S ';
  5388. $s .= sprintf('%F %F m ', $xR, $yR);
  5389. $s .= sprintf('%F %F l ', $xB, $yB);
  5390. $s .= 'S ';
  5391. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  5392. $s .= sprintf('%F %F m ', $xT, $yT);
  5393. $s .= sprintf('%F %F l ', $xR, $yR);
  5394. $s .= 'S ';
  5395. $s .= sprintf('%F %F m ', $xB, $yB);
  5396. $s .= sprintf('%F %F l ', $xL, $yL);
  5397. $s .= 'S ';
  5398. }
  5399. } else { // strlen($border) == 1
  5400. if (strpos($border,'L') !== false) { // L
  5401. $s .= sprintf('%F %F m ', $xL, $yL);
  5402. $s .= sprintf('%F %F l ', $xT, $yT);
  5403. $s .= 'S ';
  5404. } elseif (strpos($border,'T') !== false) { // T
  5405. $s .= sprintf('%F %F m ', $xT, $yT);
  5406. $s .= sprintf('%F %F l ', $xR, $yR);
  5407. $s .= 'S ';
  5408. } elseif (strpos($border,'R') !== false) { // R
  5409. $s .= sprintf('%F %F m ', $xR, $yR);
  5410. $s .= sprintf('%F %F l ', $xB, $yB);
  5411. $s .= 'S ';
  5412. } elseif (strpos($border,'B') !== false) { // B
  5413. $s .= sprintf('%F %F m ', $xB, $yB);
  5414. $s .= sprintf('%F %F l ', $xL, $yL);
  5415. $s .= 'S ';
  5416. }
  5417. }
  5418. if (is_array($style) AND !empty($style)) {
  5419. // reset border style to previous value
  5420. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  5421. }
  5422. }
  5423. return $s;
  5424. }
  5425. /**
  5426. * This method allows printing text with line breaks.
  5427. * 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 />
  5428. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  5429. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5430. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  5431. * @param $txt (string) String to print
  5432. * @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)))
  5433. * @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>
  5434. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5435. * @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>
  5436. * @param $x (float) x position in user units
  5437. * @param $y (float) y position in user units
  5438. * @param $reseth (boolean) if true reset the last cell height (default true).
  5439. * @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.
  5440. * @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.
  5441. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  5442. * @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.
  5443. * @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.
  5444. * @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.
  5445. * @return int Return the number of cells or 1 for html mode.
  5446. * @public
  5447. * @since 1.3
  5448. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  5449. */
  5450. 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) {
  5451. $prev_cell_margin = $this->cell_margin;
  5452. $prev_cell_padding = $this->cell_padding;
  5453. // adjust internal padding
  5454. $this->adjustCellPadding($border);
  5455. $mc_padding = $this->cell_padding;
  5456. $mc_margin = $this->cell_margin;
  5457. $this->cell_padding['T'] = 0;
  5458. $this->cell_padding['B'] = 0;
  5459. $this->setCellMargins(0, 0, 0, 0);
  5460. if (TCPDF_STATIC::empty_string($this->lasth) OR $reseth) {
  5461. // reset row height
  5462. $this->resetLastH();
  5463. }
  5464. if (!TCPDF_STATIC::empty_string($y)) {
  5465. $this->SetY($y); // set y in order to convert negative y values to positive ones
  5466. }
  5467. $y = $this->GetY();
  5468. $resth = 0;
  5469. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  5470. // spit cell in more pages/columns
  5471. $newh = ($this->PageBreakTrigger - $y);
  5472. $resth = ($h - $newh); // cell to be printed on the next page/column
  5473. $h = $newh;
  5474. }
  5475. // get current page number
  5476. $startpage = $this->page;
  5477. // get current column
  5478. $startcolumn = $this->current_column;
  5479. if (!TCPDF_STATIC::empty_string($x)) {
  5480. $this->SetX($x);
  5481. } else {
  5482. $x = $this->GetX();
  5483. }
  5484. // check page for no-write regions and adapt page margins if necessary
  5485. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  5486. // apply margins
  5487. $oy = $y + $mc_margin['T'];
  5488. if ($this->rtl) {
  5489. $ox = ($this->w - $x - $mc_margin['R']);
  5490. } else {
  5491. $ox = ($x + $mc_margin['L']);
  5492. }
  5493. $this->x = $ox;
  5494. $this->y = $oy;
  5495. // set width
  5496. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5497. if ($this->rtl) {
  5498. $w = ($this->x - $this->lMargin - $mc_margin['L']);
  5499. } else {
  5500. $w = ($this->w - $this->x - $this->rMargin - $mc_margin['R']);
  5501. }
  5502. }
  5503. // store original margin values
  5504. $lMargin = $this->lMargin;
  5505. $rMargin = $this->rMargin;
  5506. if ($this->rtl) {
  5507. $this->rMargin = ($this->w - $this->x);
  5508. $this->lMargin = ($this->x - $w);
  5509. } else {
  5510. $this->lMargin = ($this->x);
  5511. $this->rMargin = ($this->w - $this->x - $w);
  5512. }
  5513. $this->clMargin = $this->lMargin;
  5514. $this->crMargin = $this->rMargin;
  5515. if ($autopadding) {
  5516. // add top padding
  5517. $this->y += $mc_padding['T'];
  5518. }
  5519. if ($ishtml) { // ******* Write HTML text
  5520. $this->writeHTML($txt, true, false, $reseth, true, $align);
  5521. $nl = 1;
  5522. } else { // ******* Write simple text
  5523. $prev_FontSizePt = $this->FontSizePt;
  5524. if ($fitcell) {
  5525. // ajust height values
  5526. $tobottom = ($this->h - $this->y - $this->bMargin - $this->cell_padding['T'] - $this->cell_padding['B']);
  5527. $h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
  5528. }
  5529. // vertical alignment
  5530. if ($maxh > 0) {
  5531. // get text height
  5532. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5533. if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt > 1)) {
  5534. // try to reduce font size to fit text on cell (use a quick search algorithm)
  5535. $fmin = 1;
  5536. $fmax = $this->FontSizePt;
  5537. $diff_epsilon = (1 / $this->k); // one point (min resolution)
  5538. $maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
  5539. while ($maxit >= 0) {
  5540. $fmid = (($fmax + $fmin) / 2);
  5541. $this->SetFontSize($fmid, false);
  5542. $this->resetLastH();
  5543. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5544. $diff = ($maxh - $text_height);
  5545. if ($diff >= 0) {
  5546. if ($diff <= $diff_epsilon) {
  5547. break;
  5548. }
  5549. $fmin = $fmid;
  5550. } else {
  5551. $fmax = $fmid;
  5552. }
  5553. --$maxit;
  5554. }
  5555. if ($maxit < 0) {
  5556. // premature exit, we get the minimum font value to fit the cell
  5557. $this->SetFontSize($fmin);
  5558. $this->resetLastH();
  5559. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5560. } else {
  5561. $this->SetFontSize($fmid);
  5562. $this->resetLastH();
  5563. }
  5564. }
  5565. if ($text_height < $maxh) {
  5566. if ($valign == 'M') {
  5567. // text vertically centered
  5568. $this->y += (($maxh - $text_height) / 2);
  5569. } elseif ($valign == 'B') {
  5570. // text vertically aligned on bottom
  5571. $this->y += ($maxh - $text_height);
  5572. }
  5573. }
  5574. }
  5575. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  5576. if ($fitcell) {
  5577. // restore font size
  5578. $this->SetFontSize($prev_FontSizePt);
  5579. }
  5580. }
  5581. if ($autopadding) {
  5582. // add bottom padding
  5583. $this->y += $mc_padding['B'];
  5584. }
  5585. // Get end-of-text Y position
  5586. $currentY = $this->y;
  5587. // get latest page number
  5588. $endpage = $this->page;
  5589. if ($resth > 0) {
  5590. $skip = ($endpage - $startpage);
  5591. $tmpresth = $resth;
  5592. while ($tmpresth > 0) {
  5593. if ($skip <= 0) {
  5594. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  5595. $this->checkPageBreak($this->PageBreakTrigger + 1);
  5596. }
  5597. if ($this->num_columns > 1) {
  5598. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  5599. } else {
  5600. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  5601. }
  5602. --$skip;
  5603. }
  5604. $currentY = $this->y;
  5605. $endpage = $this->page;
  5606. }
  5607. // get latest column
  5608. $endcolumn = $this->current_column;
  5609. if ($this->num_columns == 0) {
  5610. $this->num_columns = 1;
  5611. }
  5612. // disable page regions check
  5613. $check_page_regions = $this->check_page_regions;
  5614. $this->check_page_regions = false;
  5615. // get border modes
  5616. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  5617. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  5618. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  5619. // design borders around HTML cells.
  5620. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  5621. $ccode = '';
  5622. $this->setPage($page);
  5623. if ($this->num_columns < 2) {
  5624. // single-column mode
  5625. $this->SetX($x);
  5626. $this->y = $this->tMargin;
  5627. }
  5628. // account for margin changes
  5629. if ($page > $startpage) {
  5630. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  5631. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  5632. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  5633. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  5634. }
  5635. }
  5636. if ($startpage == $endpage) {
  5637. // single page
  5638. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  5639. if ($column != $this->current_column) {
  5640. $this->selectColumn($column);
  5641. }
  5642. if ($this->rtl) {
  5643. $this->x -= $mc_margin['R'];
  5644. } else {
  5645. $this->x += $mc_margin['L'];
  5646. }
  5647. if ($startcolumn == $endcolumn) { // single column
  5648. $cborder = $border;
  5649. $h = max($h, ($currentY - $oy));
  5650. $this->y = $oy;
  5651. } elseif ($column == $startcolumn) { // first column
  5652. $cborder = $border_start;
  5653. $this->y = $oy;
  5654. $h = $this->h - $this->y - $this->bMargin;
  5655. } elseif ($column == $endcolumn) { // end column
  5656. $cborder = $border_end;
  5657. $h = $currentY - $this->y;
  5658. if ($resth > $h) {
  5659. $h = $resth;
  5660. }
  5661. } else { // middle column
  5662. $cborder = $border_middle;
  5663. $h = $this->h - $this->y - $this->bMargin;
  5664. $resth -= $h;
  5665. }
  5666. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5667. } // end for each column
  5668. } elseif ($page == $startpage) { // first page
  5669. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  5670. if ($column != $this->current_column) {
  5671. $this->selectColumn($column);
  5672. }
  5673. if ($this->rtl) {
  5674. $this->x -= $mc_margin['R'];
  5675. } else {
  5676. $this->x += $mc_margin['L'];
  5677. }
  5678. if ($column == $startcolumn) { // first column
  5679. $cborder = $border_start;
  5680. $this->y = $oy;
  5681. $h = $this->h - $this->y - $this->bMargin;
  5682. } else { // middle column
  5683. $cborder = $border_middle;
  5684. $h = $this->h - $this->y - $this->bMargin;
  5685. $resth -= $h;
  5686. }
  5687. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5688. } // end for each column
  5689. } elseif ($page == $endpage) { // last page
  5690. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  5691. if ($column != $this->current_column) {
  5692. $this->selectColumn($column);
  5693. }
  5694. if ($this->rtl) {
  5695. $this->x -= $mc_margin['R'];
  5696. } else {
  5697. $this->x += $mc_margin['L'];
  5698. }
  5699. if ($column == $endcolumn) {
  5700. // end column
  5701. $cborder = $border_end;
  5702. $h = $currentY - $this->y;
  5703. if ($resth > $h) {
  5704. $h = $resth;
  5705. }
  5706. } else {
  5707. // middle column
  5708. $cborder = $border_middle;
  5709. $h = $this->h - $this->y - $this->bMargin;
  5710. $resth -= $h;
  5711. }
  5712. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5713. } // end for each column
  5714. } else { // middle page
  5715. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  5716. $this->selectColumn($column);
  5717. if ($this->rtl) {
  5718. $this->x -= $mc_margin['R'];
  5719. } else {
  5720. $this->x += $mc_margin['L'];
  5721. }
  5722. $cborder = $border_middle;
  5723. $h = $this->h - $this->y - $this->bMargin;
  5724. $resth -= $h;
  5725. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5726. } // end for each column
  5727. }
  5728. if ($cborder OR $fill) {
  5729. $offsetlen = strlen($ccode);
  5730. // draw border and fill
  5731. if ($this->inxobj) {
  5732. // we are inside an XObject template
  5733. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  5734. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  5735. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  5736. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  5737. } else {
  5738. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  5739. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  5740. }
  5741. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  5742. $pstart = substr($pagebuff, 0, $pagemark);
  5743. $pend = substr($pagebuff, $pagemark);
  5744. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  5745. } else {
  5746. if (end($this->transfmrk[$this->page]) !== false) {
  5747. $pagemarkkey = key($this->transfmrk[$this->page]);
  5748. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  5749. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  5750. } elseif ($this->InFooter) {
  5751. $pagemark = $this->footerpos[$this->page];
  5752. $this->footerpos[$this->page] += $offsetlen;
  5753. } else {
  5754. $pagemark = $this->intmrk[$this->page];
  5755. $this->intmrk[$this->page] += $offsetlen;
  5756. }
  5757. $pagebuff = $this->getPageBuffer($this->page);
  5758. $pstart = substr($pagebuff, 0, $pagemark);
  5759. $pend = substr($pagebuff, $pagemark);
  5760. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  5761. }
  5762. }
  5763. } // end for each page
  5764. // restore page regions check
  5765. $this->check_page_regions = $check_page_regions;
  5766. // Get end-of-cell Y position
  5767. $currentY = $this->GetY();
  5768. // restore previous values
  5769. if ($this->num_columns > 1) {
  5770. $this->selectColumn();
  5771. } else {
  5772. // restore original margins
  5773. $this->lMargin = $lMargin;
  5774. $this->rMargin = $rMargin;
  5775. if ($this->page > $startpage) {
  5776. // check for margin variations between pages (i.e. booklet mode)
  5777. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  5778. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  5779. if (($dl != 0) OR ($dr != 0)) {
  5780. $this->lMargin += $dl;
  5781. $this->rMargin += $dr;
  5782. }
  5783. }
  5784. }
  5785. if ($ln > 0) {
  5786. //Go to the beginning of the next line
  5787. $this->SetY($currentY + $mc_margin['B']);
  5788. if ($ln == 2) {
  5789. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5790. }
  5791. } else {
  5792. // go left or right by case
  5793. $this->setPage($startpage);
  5794. $this->y = $y;
  5795. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5796. }
  5797. $this->setContentMark();
  5798. $this->cell_padding = $prev_cell_padding;
  5799. $this->cell_margin = $prev_cell_margin;
  5800. $this->clMargin = $this->lMargin;
  5801. $this->crMargin = $this->rMargin;
  5802. return $nl;
  5803. }
  5804. /**
  5805. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  5806. * @param $txt (string) String for calculating his height
  5807. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5808. * @param $reseth (boolean) if true reset the last cell height (default false).
  5809. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5810. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5811. * @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)))
  5812. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5813. * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
  5814. * @public
  5815. * @since 4.5.011
  5816. */
  5817. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5818. if ($txt === NULL) {
  5819. return 0;
  5820. }
  5821. if ($txt === '') {
  5822. // empty string
  5823. return 1;
  5824. }
  5825. // adjust internal padding
  5826. $prev_cell_padding = $this->cell_padding;
  5827. $prev_lasth = $this->lasth;
  5828. if (is_array($cellpadding)) {
  5829. $this->cell_padding = $cellpadding;
  5830. }
  5831. $this->adjustCellPadding($border);
  5832. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5833. if ($this->rtl) {
  5834. $w = $this->x - $this->lMargin;
  5835. } else {
  5836. $w = $this->w - $this->rMargin - $this->x;
  5837. }
  5838. }
  5839. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5840. if ($reseth) {
  5841. // reset row height
  5842. $this->resetLastH();
  5843. }
  5844. $lines = 1;
  5845. $sum = 0;
  5846. $chars = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont), $txt, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  5847. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  5848. $length = count($chars);
  5849. $lastSeparator = -1;
  5850. for ($i = 0; $i < $length; ++$i) {
  5851. $c = $chars[$i];
  5852. $charWidth = $charsWidth[$i];
  5853. if (($c != 160)
  5854. AND (($c == 173)
  5855. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  5856. OR (($c == 45)
  5857. AND ($i > 0) AND ($i < ($length - 1))
  5858. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i - 1)], $this->isunicode))
  5859. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  5860. )
  5861. )
  5862. ) {
  5863. $lastSeparator = $i;
  5864. }
  5865. if ((($sum + $charWidth) > $wmax) OR ($c == 10)) {
  5866. ++$lines;
  5867. if ($c == 10) {
  5868. $lastSeparator = -1;
  5869. $sum = 0;
  5870. } elseif ($lastSeparator != -1) {
  5871. $i = $lastSeparator;
  5872. $lastSeparator = -1;
  5873. $sum = 0;
  5874. } else {
  5875. $sum = $charWidth;
  5876. }
  5877. } else {
  5878. $sum += $charWidth;
  5879. }
  5880. }
  5881. if ($chars[($length - 1)] == 10) {
  5882. --$lines;
  5883. }
  5884. $this->cell_padding = $prev_cell_padding;
  5885. $this->lasth = $prev_lasth;
  5886. return $lines;
  5887. }
  5888. /**
  5889. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  5890. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  5891. * @pre
  5892. * // store current object
  5893. * $pdf->startTransaction();
  5894. * // store starting values
  5895. * $start_y = $pdf->GetY();
  5896. * $start_page = $pdf->getPage();
  5897. * // call your printing functions with your parameters
  5898. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5899. * $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);
  5900. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5901. * // get the new Y
  5902. * $end_y = $pdf->GetY();
  5903. * $end_page = $pdf->getPage();
  5904. * // calculate height
  5905. * $height = 0;
  5906. * if ($end_page == $start_page) {
  5907. * $height = $end_y - $start_y;
  5908. * } else {
  5909. * for ($page=$start_page; $page <= $end_page; ++$page) {
  5910. * $this->setPage($page);
  5911. * if ($page == $start_page) {
  5912. * // first page
  5913. * $height += $this->h - $start_y - $this->bMargin;
  5914. * } elseif ($page == $end_page) {
  5915. * // last page
  5916. * $height += $end_y - $this->tMargin;
  5917. * } else {
  5918. * $height += $this->h - $this->tMargin - $this->bMargin;
  5919. * }
  5920. * }
  5921. * }
  5922. * // restore previous object
  5923. * $pdf = $pdf->rollbackTransaction();
  5924. *
  5925. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5926. * @param $txt (string) String for calculating his height
  5927. * @param $reseth (boolean) if true reset the last cell height (default false).
  5928. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5929. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5930. * @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)))
  5931. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5932. * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
  5933. * @public
  5934. */
  5935. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5936. // adjust internal padding
  5937. $prev_cell_padding = $this->cell_padding;
  5938. $prev_lasth = $this->lasth;
  5939. if (is_array($cellpadding)) {
  5940. $this->cell_padding = $cellpadding;
  5941. }
  5942. $this->adjustCellPadding($border);
  5943. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  5944. $height = $this->getCellHeight(($lines * $this->FontSize), $autopadding);
  5945. $this->cell_padding = $prev_cell_padding;
  5946. $this->lasth = $prev_lasth;
  5947. return $height;
  5948. }
  5949. /**
  5950. * This method prints text from the current position.<br />
  5951. * @param $h (float) Line height
  5952. * @param $txt (string) String to print
  5953. * @param $link (mixed) URL or identifier returned by AddLink()
  5954. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5955. * @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>
  5956. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  5957. * @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.
  5958. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  5959. * @param $firstblock (boolean) if true the string is the starting of a line.
  5960. * @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.
  5961. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  5962. * @param $margin (array) margin array of the parent container
  5963. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  5964. * @public
  5965. * @since 1.5
  5966. */
  5967. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  5968. // check page for no-write regions and adapt page margins if necessary
  5969. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5970. if (strlen($txt) == 0) {
  5971. // fix empty text
  5972. $txt = ' ';
  5973. }
  5974. if ($margin === '') {
  5975. // set default margins
  5976. $margin = $this->cell_margin;
  5977. }
  5978. // remove carriage returns
  5979. $s = str_replace("\r", '', $txt);
  5980. // check if string contains arabic text
  5981. if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {
  5982. $arabic = true;
  5983. } else {
  5984. $arabic = false;
  5985. }
  5986. // check if string contains RTL text
  5987. if ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {
  5988. $rtlmode = true;
  5989. } else {
  5990. $rtlmode = false;
  5991. }
  5992. // get a char width
  5993. $chrwidth = $this->GetCharWidth(46); // dot character
  5994. // get array of unicode values
  5995. $chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);
  5996. // calculate maximum width for a single character on string
  5997. $chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
  5998. array_walk($chrw, array($this, 'getRawCharWidth'));
  5999. $maxchwidth = max($chrw);
  6000. // get array of chars
  6001. $uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);
  6002. // get the number of characters
  6003. $nb = count($chars);
  6004. // replacement for SHY character (minus symbol)
  6005. $shy_replacement = 45;
  6006. $shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);
  6007. // widht for SHY replacement
  6008. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  6009. // page width
  6010. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  6011. // calculate remaining line width ($w)
  6012. if ($this->rtl) {
  6013. $w = $this->x - $this->lMargin;
  6014. } else {
  6015. $w = $this->w - $this->rMargin - $this->x;
  6016. }
  6017. // max column width
  6018. $wmax = ($w - $wadj);
  6019. if (!$firstline) {
  6020. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  6021. }
  6022. if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
  6023. // the maximum width character do not fit on column
  6024. return '';
  6025. }
  6026. // minimum row height
  6027. $row_height = max($h, $this->getCellHeight($this->FontSize));
  6028. // max Y
  6029. $maxy = $this->y + $maxh - max($row_height, $h);
  6030. $start_page = $this->page;
  6031. $i = 0; // character position
  6032. $j = 0; // current starting position
  6033. $sep = -1; // position of the last blank space
  6034. $prevsep = $sep; // previous separator
  6035. $shy = false; // true if the last blank is a soft hypen (SHY)
  6036. $prevshy = $shy; // previous shy mode
  6037. $l = 0; // current string length
  6038. $nl = 0; //number of lines
  6039. $linebreak = false;
  6040. $pc = 0; // previous character
  6041. // for each character
  6042. while ($i < $nb) {
  6043. if (($maxh > 0) AND ($this->y > $maxy) ) {
  6044. break;
  6045. }
  6046. //Get the current character
  6047. $c = $chars[$i];
  6048. if ($c == 10) { // 10 = "\n" = new line
  6049. //Explicit line break
  6050. if ($align == 'J') {
  6051. if ($this->rtl) {
  6052. $talign = 'R';
  6053. } else {
  6054. $talign = 'L';
  6055. }
  6056. } else {
  6057. $talign = $align;
  6058. }
  6059. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6060. if ($firstline) {
  6061. $startx = $this->x;
  6062. $tmparr = array_slice($chars, $j, ($i - $j));
  6063. if ($rtlmode) {
  6064. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6065. }
  6066. $linew = $this->GetArrStringWidth($tmparr);
  6067. unset($tmparr);
  6068. if ($this->rtl) {
  6069. $this->endlinex = $startx - $linew;
  6070. } else {
  6071. $this->endlinex = $startx + $linew;
  6072. }
  6073. $w = $linew;
  6074. $tmpcellpadding = $this->cell_padding;
  6075. if ($maxh == 0) {
  6076. $this->SetCellPadding(0);
  6077. }
  6078. }
  6079. if ($firstblock AND $this->isRTLTextDir()) {
  6080. $tmpstr = $this->stringRightTrim($tmpstr);
  6081. }
  6082. // Skip newlines at the beginning of a page or column
  6083. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6084. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6085. }
  6086. unset($tmpstr);
  6087. if ($firstline) {
  6088. $this->cell_padding = $tmpcellpadding;
  6089. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6090. }
  6091. ++$nl;
  6092. $j = $i + 1;
  6093. $l = 0;
  6094. $sep = -1;
  6095. $prevsep = $sep;
  6096. $shy = false;
  6097. // account for margin changes
  6098. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6099. $this->AcceptPageBreak();
  6100. if ($this->rtl) {
  6101. $this->x -= $margin['R'];
  6102. } else {
  6103. $this->x += $margin['L'];
  6104. }
  6105. $this->lMargin += $margin['L'];
  6106. $this->rMargin += $margin['R'];
  6107. }
  6108. $w = $this->getRemainingWidth();
  6109. $wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
  6110. } else {
  6111. // 160 is the non-breaking space.
  6112. // 173 is SHY (Soft Hypen).
  6113. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6114. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6115. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6116. if (($c != 160)
  6117. AND (($c == 173)
  6118. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  6119. OR (($c == 45)
  6120. AND ($i < ($nb - 1))
  6121. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))
  6122. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  6123. )
  6124. )
  6125. ) {
  6126. // update last blank space position
  6127. $prevsep = $sep;
  6128. $sep = $i;
  6129. // check if is a SHY
  6130. if (($c == 173) OR ($c == 45)) {
  6131. $prevshy = $shy;
  6132. $shy = true;
  6133. if ($pc == 45) {
  6134. $tmp_shy_replacement_width = 0;
  6135. $tmp_shy_replacement_char = '';
  6136. } else {
  6137. $tmp_shy_replacement_width = $shy_replacement_width;
  6138. $tmp_shy_replacement_char = $shy_replacement_char;
  6139. }
  6140. } else {
  6141. $shy = false;
  6142. }
  6143. }
  6144. // update string length
  6145. if ($this->isUnicodeFont() AND ($arabic)) {
  6146. // with bidirectional algorithm some chars may be changed affecting the line length
  6147. // *** very slow ***
  6148. $l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));
  6149. } else {
  6150. $l += $this->GetCharWidth($c, ($i+1 < $nb));
  6151. }
  6152. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {
  6153. if (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {
  6154. $sep = $prevsep;
  6155. $shy = $prevshy;
  6156. }
  6157. // we have reached the end of column
  6158. if ($sep == -1) {
  6159. // check if the line was already started
  6160. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
  6161. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
  6162. // print a void cell and go to next line
  6163. $this->Cell($w, $h, '', 0, 1);
  6164. $linebreak = true;
  6165. if ($firstline) {
  6166. return (TCPDF_FONTS::UniArrSubString($uchars, $j));
  6167. }
  6168. } else {
  6169. // truncate the word because do not fit on column
  6170. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6171. if ($firstline) {
  6172. $startx = $this->x;
  6173. $tmparr = array_slice($chars, $j, ($i - $j));
  6174. if ($rtlmode) {
  6175. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6176. }
  6177. $linew = $this->GetArrStringWidth($tmparr);
  6178. unset($tmparr);
  6179. if ($this->rtl) {
  6180. $this->endlinex = $startx - $linew;
  6181. } else {
  6182. $this->endlinex = $startx + $linew;
  6183. }
  6184. $w = $linew;
  6185. $tmpcellpadding = $this->cell_padding;
  6186. if ($maxh == 0) {
  6187. $this->SetCellPadding(0);
  6188. }
  6189. }
  6190. if ($firstblock AND $this->isRTLTextDir()) {
  6191. $tmpstr = $this->stringRightTrim($tmpstr);
  6192. }
  6193. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6194. unset($tmpstr);
  6195. if ($firstline) {
  6196. $this->cell_padding = $tmpcellpadding;
  6197. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6198. }
  6199. $j = $i;
  6200. --$i;
  6201. }
  6202. } else {
  6203. // word wrapping
  6204. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  6205. $endspace = 1;
  6206. } else {
  6207. $endspace = 0;
  6208. }
  6209. // check the length of the next string
  6210. $strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));
  6211. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));
  6212. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  6213. // truncate the word because do not fit on a full page width
  6214. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6215. if ($firstline) {
  6216. $startx = $this->x;
  6217. $tmparr = array_slice($chars, $j, ($i - $j));
  6218. if ($rtlmode) {
  6219. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6220. }
  6221. $linew = $this->GetArrStringWidth($tmparr);
  6222. unset($tmparr);
  6223. if ($this->rtl) {
  6224. $this->endlinex = ($startx - $linew);
  6225. } else {
  6226. $this->endlinex = ($startx + $linew);
  6227. }
  6228. $w = $linew;
  6229. $tmpcellpadding = $this->cell_padding;
  6230. if ($maxh == 0) {
  6231. $this->SetCellPadding(0);
  6232. }
  6233. }
  6234. if ($firstblock AND $this->isRTLTextDir()) {
  6235. $tmpstr = $this->stringRightTrim($tmpstr);
  6236. }
  6237. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6238. unset($tmpstr);
  6239. if ($firstline) {
  6240. $this->cell_padding = $tmpcellpadding;
  6241. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6242. }
  6243. $j = $i;
  6244. --$i;
  6245. } else {
  6246. // word wrapping
  6247. if ($shy) {
  6248. // add hypen (minus symbol) at the end of the line
  6249. $shy_width = $tmp_shy_replacement_width;
  6250. if ($this->rtl) {
  6251. $shy_char_left = $tmp_shy_replacement_char;
  6252. $shy_char_right = '';
  6253. } else {
  6254. $shy_char_left = '';
  6255. $shy_char_right = $tmp_shy_replacement_char;
  6256. }
  6257. } else {
  6258. $shy_width = 0;
  6259. $shy_char_left = '';
  6260. $shy_char_right = '';
  6261. }
  6262. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));
  6263. if ($firstline) {
  6264. $startx = $this->x;
  6265. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  6266. if ($rtlmode) {
  6267. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6268. }
  6269. $linew = $this->GetArrStringWidth($tmparr);
  6270. unset($tmparr);
  6271. if ($this->rtl) {
  6272. $this->endlinex = $startx - $linew - $shy_width;
  6273. } else {
  6274. $this->endlinex = $startx + $linew + $shy_width;
  6275. }
  6276. $w = $linew;
  6277. $tmpcellpadding = $this->cell_padding;
  6278. if ($maxh == 0) {
  6279. $this->SetCellPadding(0);
  6280. }
  6281. }
  6282. // print the line
  6283. if ($firstblock AND $this->isRTLTextDir()) {
  6284. $tmpstr = $this->stringRightTrim($tmpstr);
  6285. }
  6286. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  6287. unset($tmpstr);
  6288. if ($firstline) {
  6289. if ($chars[$sep] == 45) {
  6290. $endspace += 1;
  6291. }
  6292. // return the remaining text
  6293. $this->cell_padding = $tmpcellpadding;
  6294. return (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));
  6295. }
  6296. $i = $sep;
  6297. $sep = -1;
  6298. $shy = false;
  6299. $j = ($i + 1);
  6300. }
  6301. }
  6302. // account for margin changes
  6303. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6304. $this->AcceptPageBreak();
  6305. if ($this->rtl) {
  6306. $this->x -= $margin['R'];
  6307. } else {
  6308. $this->x += $margin['L'];
  6309. }
  6310. $this->lMargin += $margin['L'];
  6311. $this->rMargin += $margin['R'];
  6312. }
  6313. $w = $this->getRemainingWidth();
  6314. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6315. if ($linebreak) {
  6316. $linebreak = false;
  6317. } else {
  6318. ++$nl;
  6319. $l = 0;
  6320. }
  6321. }
  6322. }
  6323. // save last character
  6324. $pc = $c;
  6325. ++$i;
  6326. } // end while i < nb
  6327. // print last substring (if any)
  6328. if ($l > 0) {
  6329. switch ($align) {
  6330. case 'J':
  6331. case 'C': {
  6332. $w = $w;
  6333. break;
  6334. }
  6335. case 'L': {
  6336. if ($this->rtl) {
  6337. $w = $w;
  6338. } else {
  6339. $w = $l;
  6340. }
  6341. break;
  6342. }
  6343. case 'R': {
  6344. if ($this->rtl) {
  6345. $w = $l;
  6346. } else {
  6347. $w = $w;
  6348. }
  6349. break;
  6350. }
  6351. default: {
  6352. $w = $l;
  6353. break;
  6354. }
  6355. }
  6356. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);
  6357. if ($firstline) {
  6358. $startx = $this->x;
  6359. $tmparr = array_slice($chars, $j, ($nb - $j));
  6360. if ($rtlmode) {
  6361. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6362. }
  6363. $linew = $this->GetArrStringWidth($tmparr);
  6364. unset($tmparr);
  6365. if ($this->rtl) {
  6366. $this->endlinex = $startx - $linew;
  6367. } else {
  6368. $this->endlinex = $startx + $linew;
  6369. }
  6370. $w = $linew;
  6371. $tmpcellpadding = $this->cell_padding;
  6372. if ($maxh == 0) {
  6373. $this->SetCellPadding(0);
  6374. }
  6375. }
  6376. if ($firstblock AND $this->isRTLTextDir()) {
  6377. $tmpstr = $this->stringRightTrim($tmpstr);
  6378. }
  6379. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  6380. unset($tmpstr);
  6381. if ($firstline) {
  6382. $this->cell_padding = $tmpcellpadding;
  6383. return (TCPDF_FONTS::UniArrSubString($uchars, $nb));
  6384. }
  6385. ++$nl;
  6386. }
  6387. if ($firstline) {
  6388. return '';
  6389. }
  6390. return $nl;
  6391. }
  6392. /**
  6393. * Returns the remaining width between the current position and margins.
  6394. * @return int Return the remaining width
  6395. * @protected
  6396. */
  6397. protected function getRemainingWidth() {
  6398. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  6399. if ($this->rtl) {
  6400. return ($this->x - $this->lMargin);
  6401. } else {
  6402. return ($this->w - $this->rMargin - $this->x);
  6403. }
  6404. }
  6405. /**
  6406. * Set the block dimensions accounting for page breaks and page/column fitting
  6407. * @param $w (float) width
  6408. * @param $h (float) height
  6409. * @param $x (float) X coordinate
  6410. * @param $y (float) Y coodiante
  6411. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  6412. * @return array($w, $h, $x, $y)
  6413. * @protected
  6414. * @since 5.5.009 (2010-07-05)
  6415. */
  6416. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  6417. if ($w <= 0) {
  6418. // set maximum width
  6419. $w = ($this->w - $this->lMargin - $this->rMargin);
  6420. if ($w <= 0) {
  6421. $w = 1;
  6422. }
  6423. }
  6424. if ($h <= 0) {
  6425. // set maximum height
  6426. $h = ($this->PageBreakTrigger - $this->tMargin);
  6427. if ($h <= 0) {
  6428. $h = 1;
  6429. }
  6430. }
  6431. // resize the block to be vertically contained on a single page or single column
  6432. if ($fitonpage OR $this->AutoPageBreak) {
  6433. $ratio_wh = ($w / $h);
  6434. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  6435. $h = $this->PageBreakTrigger - $this->tMargin;
  6436. $w = ($h * $ratio_wh);
  6437. }
  6438. // resize the block to be horizontally contained on a single page or single column
  6439. if ($fitonpage) {
  6440. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  6441. if ($w > $maxw) {
  6442. $w = $maxw;
  6443. $h = ($w / $ratio_wh);
  6444. }
  6445. }
  6446. }
  6447. // Check whether we need a new page or new column first as this does not fit
  6448. $prev_x = $this->x;
  6449. $prev_y = $this->y;
  6450. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  6451. $y = $this->y;
  6452. if ($this->rtl) {
  6453. $x += ($prev_x - $this->x);
  6454. } else {
  6455. $x += ($this->x - $prev_x);
  6456. }
  6457. $this->newline = true;
  6458. }
  6459. // resize the block to be contained on the remaining available page or column space
  6460. if ($fitonpage) {
  6461. $ratio_wh = ($w / $h);
  6462. if (($y + $h) > $this->PageBreakTrigger) {
  6463. $h = $this->PageBreakTrigger - $y;
  6464. $w = ($h * $ratio_wh);
  6465. }
  6466. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  6467. $w = $this->w - $this->rMargin - $x;
  6468. $h = ($w / $ratio_wh);
  6469. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  6470. $w = $x - $this->lMargin;
  6471. $h = ($w / $ratio_wh);
  6472. }
  6473. }
  6474. return array($w, $h, $x, $y);
  6475. }
  6476. /**
  6477. * Puts an image in the page.
  6478. * The upper-left corner must be given.
  6479. * The dimensions can be specified in different ways:<ul>
  6480. * <li>explicit width and height (expressed in user unit)</li>
  6481. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  6482. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  6483. * 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;
  6484. * The format can be specified explicitly or inferred from the file extension.<br />
  6485. * It is possible to put a link on the image.<br />
  6486. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  6487. * @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').
  6488. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  6489. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  6490. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6491. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6492. * @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.
  6493. * @param $link (mixed) URL or identifier returned by AddLink().
  6494. * @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>
  6495. * @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).
  6496. * @param $dpi (int) dot-per-inch resolution used on resize
  6497. * @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>
  6498. * @param $ismask (boolean) true if this image is a mask, false otherwise
  6499. * @param $imgmask (mixed) image object returned by this function or false
  6500. * @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)))
  6501. * @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).
  6502. * @param $hidden (boolean) If true do not display the image.
  6503. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  6504. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  6505. * @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.
  6506. * @return image information
  6507. * @public
  6508. * @since 1.1
  6509. */
  6510. 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()) {
  6511. if ($this->state != 2) {
  6512. return;
  6513. }
  6514. if (strcmp($x, '') === 0) {
  6515. $x = $this->x;
  6516. }
  6517. if (strcmp($y, '') === 0) {
  6518. $y = $this->y;
  6519. }
  6520. // check page for no-write regions and adapt page margins if necessary
  6521. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  6522. $exurl = ''; // external streams
  6523. $imsize = FALSE;
  6524. // Make sure the file variable is not empty or null because accessing $file[0] later
  6525. // results in error when running PHP 7.4
  6526. if (empty($file)) {
  6527. return false;
  6528. }
  6529. // check if we are passing an image as file or string
  6530. if ($file[0] === '@') {
  6531. // image from string
  6532. $imgdata = substr($file, 1);
  6533. } else { // image file
  6534. if ($file[0] === '*') {
  6535. // image as external stream
  6536. $file = substr($file, 1);
  6537. $exurl = $file;
  6538. }
  6539. // check if file exist and it is valid
  6540. if (!@$this->fileExists($file)) {
  6541. return false;
  6542. }
  6543. if (false !== $info = $this->getImageBuffer($file)) {
  6544. $imsize = array($info['w'], $info['h']);
  6545. } elseif (($imsize = @getimagesize($file)) === FALSE && strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE){
  6546. $imgdata = $this->getCachedFileContents($file);
  6547. }
  6548. }
  6549. if (!empty($imgdata)) {
  6550. // copy image to cache
  6551. $original_file = $file;
  6552. $file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6553. $fp = TCPDF_STATIC::fopenLocal($file, 'w');
  6554. if (!$fp) {
  6555. $this->Error('Unable to write file: '.$file);
  6556. }
  6557. fwrite($fp, $imgdata);
  6558. fclose($fp);
  6559. unset($imgdata);
  6560. $imsize = @getimagesize($file);
  6561. if ($imsize === FALSE) {
  6562. unlink($file);
  6563. $file = $original_file;
  6564. }
  6565. }
  6566. if ($imsize === FALSE) {
  6567. if (($w > 0) AND ($h > 0)) {
  6568. // get measures from specified data
  6569. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6570. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6571. $imsize = array($pw, $ph);
  6572. } else {
  6573. $this->Error('[Image] Unable to get the size of the image: '.$file);
  6574. }
  6575. }
  6576. // file hash
  6577. $filehash = md5($file);
  6578. // get original image width and height in pixels
  6579. list($pixw, $pixh) = $imsize;
  6580. // calculate image width and height on document
  6581. if (($w <= 0) AND ($h <= 0)) {
  6582. // convert image size to document unit
  6583. $w = $this->pixelsToUnits($pixw);
  6584. $h = $this->pixelsToUnits($pixh);
  6585. } elseif ($w <= 0) {
  6586. $w = $h * $pixw / $pixh;
  6587. } elseif ($h <= 0) {
  6588. $h = $w * $pixh / $pixw;
  6589. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  6590. if (strlen($fitbox) !== 2) {
  6591. // set default alignment
  6592. $fitbox = '--';
  6593. }
  6594. // scale image dimensions proportionally to fit within the ($w, $h) box
  6595. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  6596. // store current height
  6597. $oldh = $h;
  6598. // calculate new height
  6599. $h = $w * $pixh / $pixw;
  6600. // height difference
  6601. $hdiff = ($oldh - $h);
  6602. // vertical alignment
  6603. switch (strtoupper($fitbox[1])) {
  6604. case 'T': {
  6605. break;
  6606. }
  6607. case 'M': {
  6608. $y += ($hdiff / 2);
  6609. break;
  6610. }
  6611. case 'B': {
  6612. $y += $hdiff;
  6613. break;
  6614. }
  6615. }
  6616. } else {
  6617. // store current width
  6618. $oldw = $w;
  6619. // calculate new width
  6620. $w = $h * $pixw / $pixh;
  6621. // width difference
  6622. $wdiff = ($oldw - $w);
  6623. // horizontal alignment
  6624. switch (strtoupper($fitbox[0])) {
  6625. case 'L': {
  6626. if ($this->rtl) {
  6627. $x -= $wdiff;
  6628. }
  6629. break;
  6630. }
  6631. case 'C': {
  6632. if ($this->rtl) {
  6633. $x -= ($wdiff / 2);
  6634. } else {
  6635. $x += ($wdiff / 2);
  6636. }
  6637. break;
  6638. }
  6639. case 'R': {
  6640. if (!$this->rtl) {
  6641. $x += $wdiff;
  6642. }
  6643. break;
  6644. }
  6645. }
  6646. }
  6647. }
  6648. // fit the image on available space
  6649. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  6650. // calculate new minimum dimensions in pixels
  6651. $neww = round($w * $this->k * $dpi / $this->dpi);
  6652. $newh = round($h * $this->k * $dpi / $this->dpi);
  6653. // check if resize is necessary (resize is used only to reduce the image)
  6654. $newsize = ($neww * $newh);
  6655. $pixsize = ($pixw * $pixh);
  6656. if (intval($resize) == 2) {
  6657. $resize = true;
  6658. } elseif ($newsize >= $pixsize) {
  6659. $resize = false;
  6660. }
  6661. // check if image has been already added on document
  6662. $newimage = true;
  6663. if (in_array($file, $this->imagekeys)) {
  6664. $newimage = false;
  6665. // get existing image data
  6666. $info = $this->getImageBuffer($file);
  6667. if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
  6668. // check if the newer image is larger
  6669. $oldsize = ($info['w'] * $info['h']);
  6670. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6671. $newimage = true;
  6672. }
  6673. }
  6674. } elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
  6675. // create temp image file (without alpha channel)
  6676. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6677. // create temp alpha file
  6678. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6679. // check for cached images
  6680. if (in_array($tempfile_plain, $this->imagekeys)) {
  6681. // get existing image data
  6682. $info = $this->getImageBuffer($tempfile_plain);
  6683. // check if the newer image is larger
  6684. $oldsize = ($info['w'] * $info['h']);
  6685. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6686. $newimage = true;
  6687. } else {
  6688. $newimage = false;
  6689. // embed mask image
  6690. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6691. // embed image, masked with previously embedded mask
  6692. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6693. }
  6694. }
  6695. }
  6696. if ($newimage) {
  6697. //First use of image, get info
  6698. $type = strtolower($type);
  6699. if ($type == '') {
  6700. $type = TCPDF_IMAGES::getImageFileType($file, $imsize);
  6701. } elseif ($type == 'jpg') {
  6702. $type = 'jpeg';
  6703. }
  6704. $mqr = TCPDF_STATIC::get_mqr();
  6705. TCPDF_STATIC::set_mqr(false);
  6706. // Specific image handlers (defined on TCPDF_IMAGES CLASS)
  6707. $mtd = '_parse'.$type;
  6708. // GD image handler function
  6709. $gdfunction = 'imagecreatefrom'.$type;
  6710. $info = false;
  6711. if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  6712. // TCPDF image functions
  6713. $info = TCPDF_IMAGES::$mtd($file);
  6714. if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
  6715. AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
  6716. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  6717. }
  6718. }
  6719. if (($info === false) AND function_exists($gdfunction)) {
  6720. try {
  6721. // GD library
  6722. $img = $gdfunction($file);
  6723. if ($img !== false) {
  6724. if ($resize) {
  6725. $imgr = imagecreatetruecolor($neww, $newh);
  6726. if (($type == 'gif') OR ($type == 'png')) {
  6727. $imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
  6728. }
  6729. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  6730. $img = $imgr;
  6731. }
  6732. if (($type == 'gif') OR ($type == 'png')) {
  6733. $info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6734. } else {
  6735. $info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6736. }
  6737. }
  6738. } catch(Exception $e) {
  6739. $info = false;
  6740. }
  6741. }
  6742. if (($info === false) AND extension_loaded('imagick')) {
  6743. try {
  6744. // ImageMagick library
  6745. $img = new Imagick();
  6746. if ($type == 'svg') {
  6747. if ($file[0] === '@') {
  6748. // image from string
  6749. $svgimg = substr($file, 1);
  6750. } else {
  6751. // get SVG file content
  6752. $svgimg = $this->getCachedFileContents($file);
  6753. }
  6754. if ($svgimg !== FALSE) {
  6755. // get width and height
  6756. $regs = array();
  6757. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  6758. $svgtag = $regs[1];
  6759. $tmp = array();
  6760. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6761. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6762. $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
  6763. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  6764. } else {
  6765. $ow = $w;
  6766. }
  6767. $tmp = array();
  6768. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6769. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6770. $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
  6771. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  6772. } else {
  6773. $oh = $h;
  6774. }
  6775. $tmp = array();
  6776. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  6777. $vbw = ($ow * $this->imgscale * $this->k);
  6778. $vbh = ($oh * $this->imgscale * $this->k);
  6779. $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
  6780. $svgtag = $vbox.$svgtag;
  6781. }
  6782. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  6783. }
  6784. $img->readImageBlob($svgimg);
  6785. }
  6786. } else {
  6787. $img->readImage($file);
  6788. }
  6789. if ($resize) {
  6790. $img->resizeImage($neww, $newh, 10, 1, false);
  6791. }
  6792. $img->setCompressionQuality($this->jpeg_quality);
  6793. $img->setImageFormat('jpeg');
  6794. $tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6795. $img->writeImage($tempname);
  6796. $info = TCPDF_IMAGES::_parsejpeg($tempname);
  6797. unlink($tempname);
  6798. $img->destroy();
  6799. } catch(Exception $e) {
  6800. $info = false;
  6801. }
  6802. }
  6803. if ($info === false) {
  6804. // unable to process image
  6805. return;
  6806. }
  6807. TCPDF_STATIC::set_mqr($mqr);
  6808. if ($ismask) {
  6809. // force grayscale
  6810. $info['cs'] = 'DeviceGray';
  6811. }
  6812. if ($imgmask !== false) {
  6813. $info['masked'] = $imgmask;
  6814. }
  6815. if (!empty($exurl)) {
  6816. $info['exurl'] = $exurl;
  6817. }
  6818. // array of alternative images
  6819. $info['altimgs'] = $altimgs;
  6820. // add image to document
  6821. $info['i'] = $this->setImageBuffer($file, $info);
  6822. }
  6823. // set alignment
  6824. $this->img_rb_x = $x + $w;
  6825. $this->img_rb_y = $y + $h;
  6826. // set alignment
  6827. if ($palign == 'L') {
  6828. $ximg = $this->lMargin;
  6829. } elseif ($palign == 'C') {
  6830. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6831. } elseif ($palign == 'R') {
  6832. $ximg = $this->w - $this->rMargin - $w;
  6833. } else {
  6834. $ximg = $x;
  6835. }
  6836. if ($ismask OR $hidden) {
  6837. // image is not displayed
  6838. return $info['i'];
  6839. }
  6840. $xkimg = $ximg * $this->k;
  6841. if (!$alt) {
  6842. // only non-alternative immages will be set
  6843. $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']));
  6844. }
  6845. if (!empty($border)) {
  6846. $bx = $this->x;
  6847. $by = $this->y;
  6848. $this->x = $ximg;
  6849. if ($this->rtl) {
  6850. $this->x += $w;
  6851. }
  6852. $this->y = $y;
  6853. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  6854. $this->x = $bx;
  6855. $this->y = $by;
  6856. }
  6857. if ($link) {
  6858. $this->Link($ximg, $y, $w, $h, $link, 0);
  6859. }
  6860. // set pointer to align the next text/objects
  6861. switch($align) {
  6862. case 'T': {
  6863. $this->y = $y;
  6864. $this->x = $this->img_rb_x;
  6865. break;
  6866. }
  6867. case 'M': {
  6868. $this->y = $y + round($h/2);
  6869. $this->x = $this->img_rb_x;
  6870. break;
  6871. }
  6872. case 'B': {
  6873. $this->y = $this->img_rb_y;
  6874. $this->x = $this->img_rb_x;
  6875. break;
  6876. }
  6877. case 'N': {
  6878. $this->SetY($this->img_rb_y);
  6879. break;
  6880. }
  6881. default:{
  6882. break;
  6883. }
  6884. }
  6885. $this->endlinex = $this->img_rb_x;
  6886. if ($this->inxobj) {
  6887. // we are inside an XObject template
  6888. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  6889. }
  6890. return $info['i'];
  6891. }
  6892. /**
  6893. * Extract info from a PNG image with alpha channel using the Imagick or GD library.
  6894. * @param $file (string) Name of the file containing the image.
  6895. * @param $x (float) Abscissa of the upper-left corner.
  6896. * @param $y (float) Ordinate of the upper-left corner.
  6897. * @param $wpx (float) Original width of the image in pixels.
  6898. * @param $hpx (float) original height of the image in pixels.
  6899. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6900. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6901. * @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.
  6902. * @param $link (mixed) URL or identifier returned by AddLink().
  6903. * @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>
  6904. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  6905. * @param $dpi (int) dot-per-inch resolution used on resize
  6906. * @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>
  6907. * @param $filehash (string) File hash used to build unique file names.
  6908. * @author Nicola Asuni
  6909. * @protected
  6910. * @since 4.3.007 (2008-12-04)
  6911. * @see Image()
  6912. */
  6913. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  6914. // create temp images
  6915. if (empty($filehash)) {
  6916. $filehash = md5($file);
  6917. }
  6918. // create temp image file (without alpha channel)
  6919. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6920. // create temp alpha file
  6921. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6922. $parsed = false;
  6923. $parse_error = '';
  6924. // ImageMagick extension
  6925. if (($parsed === false) AND extension_loaded('imagick')) {
  6926. try {
  6927. // ImageMagick library
  6928. $img = new Imagick();
  6929. $img->readImage($file);
  6930. // clone image object
  6931. $imga = TCPDF_STATIC::objclone($img);
  6932. // extract alpha channel
  6933. if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
  6934. $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
  6935. } else {
  6936. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  6937. $img->negateImage(true);
  6938. }
  6939. $img->setImageFormat('png');
  6940. $img->writeImage($tempfile_alpha);
  6941. // remove alpha channel
  6942. if (method_exists($imga, 'setImageMatte')) {
  6943. $imga->setImageMatte(false);
  6944. } else {
  6945. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  6946. }
  6947. $imga->setImageFormat('png');
  6948. $imga->writeImage($tempfile_plain);
  6949. $parsed = true;
  6950. } catch (Exception $e) {
  6951. // Imagemagick fails, try with GD
  6952. $parse_error = 'Imagick library error: '.$e->getMessage();
  6953. }
  6954. }
  6955. // GD extension
  6956. if (($parsed === false) AND function_exists('imagecreatefrompng')) {
  6957. try {
  6958. // generate images
  6959. $img = imagecreatefrompng($file);
  6960. $imgalpha = imagecreate($wpx, $hpx);
  6961. // generate gray scale palette (0 -> 255)
  6962. for ($c = 0; $c < 256; ++$c) {
  6963. ImageColorAllocate($imgalpha, $c, $c, $c);
  6964. }
  6965. // extract alpha channel
  6966. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  6967. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  6968. $color = imagecolorat($img, $xpx, $ypx);
  6969. // get and correct gamma color
  6970. $alpha = $this->getGDgamma($img, $color);
  6971. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  6972. }
  6973. }
  6974. imagepng($imgalpha, $tempfile_alpha);
  6975. imagedestroy($imgalpha);
  6976. // extract image without alpha channel
  6977. $imgplain = imagecreatetruecolor($wpx, $hpx);
  6978. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  6979. imagepng($imgplain, $tempfile_plain);
  6980. imagedestroy($imgplain);
  6981. $parsed = true;
  6982. } catch (Exception $e) {
  6983. // GD fails
  6984. $parse_error = 'GD library error: '.$e->getMessage();
  6985. }
  6986. }
  6987. if ($parsed === false) {
  6988. if (empty($parse_error)) {
  6989. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  6990. } else {
  6991. $this->Error($parse_error);
  6992. }
  6993. }
  6994. // embed mask image
  6995. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6996. // embed image, masked with previously embedded mask
  6997. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6998. }
  6999. /**
  7000. * Get the GD-corrected PNG gamma value from alpha color
  7001. * @param $img (int) GD image Resource ID.
  7002. * @param $c (int) alpha color
  7003. * @protected
  7004. * @since 4.3.007 (2008-12-04)
  7005. */
  7006. protected function getGDgamma($img, $c) {
  7007. if (!isset($this->gdgammacache['#'.$c])) {
  7008. $colors = imagecolorsforindex($img, $c);
  7009. // GD alpha is only 7 bit (0 -> 127)
  7010. $this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
  7011. // correct gamma
  7012. $this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
  7013. // store the latest values on cache to improve performances
  7014. if (count($this->gdgammacache) > 8) {
  7015. // remove one element from the cache array
  7016. array_shift($this->gdgammacache);
  7017. }
  7018. }
  7019. return $this->gdgammacache['#'.$c];
  7020. }
  7021. /**
  7022. * Performs a line break.
  7023. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  7024. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  7025. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  7026. * @public
  7027. * @since 1.0
  7028. * @see Cell()
  7029. */
  7030. public function Ln($h='', $cell=false) {
  7031. 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'])) {
  7032. // revove vertical space from the top of the column
  7033. return;
  7034. }
  7035. if ($cell) {
  7036. if ($this->rtl) {
  7037. $cellpadding = $this->cell_padding['R'];
  7038. } else {
  7039. $cellpadding = $this->cell_padding['L'];
  7040. }
  7041. } else {
  7042. $cellpadding = 0;
  7043. }
  7044. if ($this->rtl) {
  7045. $this->x = $this->w - $this->rMargin - $cellpadding;
  7046. } else {
  7047. $this->x = $this->lMargin + $cellpadding;
  7048. }
  7049. if (is_string($h)) {
  7050. $h = $this->lasth;
  7051. }
  7052. $this->y += $h;
  7053. $this->newline = true;
  7054. }
  7055. /**
  7056. * Returns the relative X value of current position.
  7057. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  7058. * @return float
  7059. * @public
  7060. * @since 1.2
  7061. * @see SetX(), GetY(), SetY()
  7062. */
  7063. public function GetX() {
  7064. //Get x position
  7065. if ($this->rtl) {
  7066. return ($this->w - $this->x);
  7067. } else {
  7068. return $this->x;
  7069. }
  7070. }
  7071. /**
  7072. * Returns the absolute X value of current position.
  7073. * @return float
  7074. * @public
  7075. * @since 1.2
  7076. * @see SetX(), GetY(), SetY()
  7077. */
  7078. public function GetAbsX() {
  7079. return $this->x;
  7080. }
  7081. /**
  7082. * Returns the ordinate of the current position.
  7083. * @return float
  7084. * @public
  7085. * @since 1.0
  7086. * @see SetY(), GetX(), SetX()
  7087. */
  7088. public function GetY() {
  7089. return $this->y;
  7090. }
  7091. /**
  7092. * Defines the abscissa of the current position.
  7093. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  7094. * @param $x (float) The value of the abscissa in user units.
  7095. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7096. * @public
  7097. * @since 1.2
  7098. * @see GetX(), GetY(), SetY(), SetXY()
  7099. */
  7100. public function SetX($x, $rtloff=false) {
  7101. $x = floatval($x);
  7102. if (!$rtloff AND $this->rtl) {
  7103. if ($x >= 0) {
  7104. $this->x = $this->w - $x;
  7105. } else {
  7106. $this->x = abs($x);
  7107. }
  7108. } else {
  7109. if ($x >= 0) {
  7110. $this->x = $x;
  7111. } else {
  7112. $this->x = $this->w + $x;
  7113. }
  7114. }
  7115. if ($this->x < 0) {
  7116. $this->x = 0;
  7117. }
  7118. if ($this->x > $this->w) {
  7119. $this->x = $this->w;
  7120. }
  7121. }
  7122. /**
  7123. * Moves the current abscissa back to the left margin and sets the ordinate.
  7124. * If the passed value is negative, it is relative to the bottom of the page.
  7125. * @param $y (float) The value of the ordinate in user units.
  7126. * @param $resetx (bool) if true (default) reset the X position.
  7127. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7128. * @public
  7129. * @since 1.0
  7130. * @see GetX(), GetY(), SetY(), SetXY()
  7131. */
  7132. public function SetY($y, $resetx=true, $rtloff=false) {
  7133. $y = floatval($y);
  7134. if ($resetx) {
  7135. //reset x
  7136. if (!$rtloff AND $this->rtl) {
  7137. $this->x = $this->w - $this->rMargin;
  7138. } else {
  7139. $this->x = $this->lMargin;
  7140. }
  7141. }
  7142. if ($y >= 0) {
  7143. $this->y = $y;
  7144. } else {
  7145. $this->y = $this->h + $y;
  7146. }
  7147. if ($this->y < 0) {
  7148. $this->y = 0;
  7149. }
  7150. if ($this->y > $this->h) {
  7151. $this->y = $this->h;
  7152. }
  7153. }
  7154. /**
  7155. * Defines the abscissa and ordinate of the current position.
  7156. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  7157. * @param $x (float) The value of the abscissa.
  7158. * @param $y (float) The value of the ordinate.
  7159. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7160. * @public
  7161. * @since 1.2
  7162. * @see SetX(), SetY()
  7163. */
  7164. public function SetXY($x, $y, $rtloff=false) {
  7165. $this->SetY($y, false, $rtloff);
  7166. $this->SetX($x, $rtloff);
  7167. }
  7168. /**
  7169. * Set the absolute X coordinate of the current pointer.
  7170. * @param $x (float) The value of the abscissa in user units.
  7171. * @public
  7172. * @since 5.9.186 (2012-09-13)
  7173. * @see setAbsX(), setAbsY(), SetAbsXY()
  7174. */
  7175. public function SetAbsX($x) {
  7176. $this->x = floatval($x);
  7177. }
  7178. /**
  7179. * Set the absolute Y coordinate of the current pointer.
  7180. * @param $y (float) (float) The value of the ordinate in user units.
  7181. * @public
  7182. * @since 5.9.186 (2012-09-13)
  7183. * @see setAbsX(), setAbsY(), SetAbsXY()
  7184. */
  7185. public function SetAbsY($y) {
  7186. $this->y = floatval($y);
  7187. }
  7188. /**
  7189. * Set the absolute X and Y coordinates of the current pointer.
  7190. * @param $x (float) The value of the abscissa in user units.
  7191. * @param $y (float) (float) The value of the ordinate in user units.
  7192. * @public
  7193. * @since 5.9.186 (2012-09-13)
  7194. * @see setAbsX(), setAbsY(), SetAbsXY()
  7195. */
  7196. public function SetAbsXY($x, $y) {
  7197. $this->SetAbsX($x);
  7198. $this->SetAbsY($y);
  7199. }
  7200. /**
  7201. * Send the document to a given destination: string, local file or browser.
  7202. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  7203. * The method first calls Close() if necessary to terminate the document.
  7204. * @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.
  7205. * @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>
  7206. * @return string
  7207. * @public
  7208. * @since 1.0
  7209. * @see Close()
  7210. */
  7211. public function Output($name='doc.pdf', $dest='I') {
  7212. //Output PDF to some destination
  7213. //Finish document if necessary
  7214. if ($this->state < 3) {
  7215. $this->Close();
  7216. }
  7217. //Normalize parameters
  7218. if (is_bool($dest)) {
  7219. $dest = $dest ? 'D' : 'F';
  7220. }
  7221. $dest = strtoupper($dest);
  7222. if ($dest[0] != 'F') {
  7223. $name = preg_replace('/[\s]+/', '_', $name);
  7224. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  7225. }
  7226. if ($this->sign) {
  7227. // *** apply digital signature to the document ***
  7228. // get the document content
  7229. $pdfdoc = $this->getBuffer();
  7230. // remove last newline
  7231. $pdfdoc = substr($pdfdoc, 0, -1);
  7232. // remove filler space
  7233. $byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
  7234. // define the ByteRange
  7235. $byte_range = array();
  7236. $byte_range[0] = 0;
  7237. $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
  7238. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  7239. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  7240. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  7241. // replace the ByteRange
  7242. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  7243. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  7244. $pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
  7245. // write the document to a temporary folder
  7246. $tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
  7247. $f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
  7248. if (!$f) {
  7249. $this->Error('Unable to create temporary file: '.$tempdoc);
  7250. }
  7251. $pdfdoc_length = strlen($pdfdoc);
  7252. fwrite($f, $pdfdoc, $pdfdoc_length);
  7253. fclose($f);
  7254. // get digital signature via openssl library
  7255. $tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
  7256. if (empty($this->signature_data['extracerts'])) {
  7257. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  7258. } else {
  7259. 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']);
  7260. }
  7261. // read signature
  7262. $signature = file_get_contents($tempsign);
  7263. // extract signature
  7264. $signature = substr($signature, $pdfdoc_length);
  7265. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  7266. $tmparr = explode("\n\n", $signature);
  7267. $signature = $tmparr[1];
  7268. // decode signature
  7269. $signature = base64_decode(trim($signature));
  7270. // add TSA timestamp to signature
  7271. $signature = $this->applyTSA($signature);
  7272. // convert signature to hex
  7273. $signature = current(unpack('H*', $signature));
  7274. $signature = str_pad($signature, $this->signature_max_length, '0');
  7275. // Add signature to the document
  7276. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  7277. $this->bufferlen = strlen($this->buffer);
  7278. }
  7279. switch($dest) {
  7280. case 'I': {
  7281. // Send PDF to the standard output
  7282. if (ob_get_contents()) {
  7283. $this->Error('Some data has already been output, can\'t send PDF file');
  7284. }
  7285. if (php_sapi_name() != 'cli') {
  7286. // send output to a browser
  7287. header('Content-Type: application/pdf');
  7288. if (headers_sent()) {
  7289. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7290. }
  7291. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7292. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7293. header('Pragma: public');
  7294. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7295. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7296. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7297. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7298. } else {
  7299. echo $this->getBuffer();
  7300. }
  7301. break;
  7302. }
  7303. case 'D': {
  7304. // download PDF as file
  7305. if (ob_get_contents()) {
  7306. $this->Error('Some data has already been output, can\'t send PDF file');
  7307. }
  7308. header('Content-Description: File Transfer');
  7309. if (headers_sent()) {
  7310. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7311. }
  7312. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7313. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7314. header('Pragma: public');
  7315. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7316. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7317. // force download dialog
  7318. if (strpos(php_sapi_name(), 'cgi') === false) {
  7319. header('Content-Type: application/force-download');
  7320. header('Content-Type: application/octet-stream', false);
  7321. header('Content-Type: application/download', false);
  7322. header('Content-Type: application/pdf', false);
  7323. } else {
  7324. header('Content-Type: application/pdf');
  7325. }
  7326. // use the Content-Disposition header to supply a recommended filename
  7327. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7328. header('Content-Transfer-Encoding: binary');
  7329. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7330. break;
  7331. }
  7332. case 'F':
  7333. case 'FI':
  7334. case 'FD': {
  7335. // save PDF to a local file
  7336. $f = TCPDF_STATIC::fopenLocal($name, 'wb');
  7337. if (!$f) {
  7338. $this->Error('Unable to create output file: '.$name);
  7339. }
  7340. fwrite($f, $this->getBuffer(), $this->bufferlen);
  7341. fclose($f);
  7342. if ($dest == 'FI') {
  7343. // send headers to browser
  7344. header('Content-Type: application/pdf');
  7345. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7346. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7347. header('Pragma: public');
  7348. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7349. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7350. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7351. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7352. } elseif ($dest == 'FD') {
  7353. // send headers to browser
  7354. if (ob_get_contents()) {
  7355. $this->Error('Some data has already been output, can\'t send PDF file');
  7356. }
  7357. header('Content-Description: File Transfer');
  7358. if (headers_sent()) {
  7359. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7360. }
  7361. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7362. header('Pragma: public');
  7363. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7364. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7365. // force download dialog
  7366. if (strpos(php_sapi_name(), 'cgi') === false) {
  7367. header('Content-Type: application/force-download');
  7368. header('Content-Type: application/octet-stream', false);
  7369. header('Content-Type: application/download', false);
  7370. header('Content-Type: application/pdf', false);
  7371. } else {
  7372. header('Content-Type: application/pdf');
  7373. }
  7374. // use the Content-Disposition header to supply a recommended filename
  7375. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7376. header('Content-Transfer-Encoding: binary');
  7377. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7378. }
  7379. break;
  7380. }
  7381. case 'E': {
  7382. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  7383. $retval = 'Content-Type: application/pdf;'."\r\n";
  7384. $retval .= ' name="'.$name.'"'."\r\n";
  7385. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  7386. $retval .= 'Content-Disposition: attachment;'."\r\n";
  7387. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  7388. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  7389. return $retval;
  7390. }
  7391. case 'S': {
  7392. // returns PDF as a string
  7393. return $this->getBuffer();
  7394. }
  7395. default: {
  7396. $this->Error('Incorrect output destination: '.$dest);
  7397. }
  7398. }
  7399. return '';
  7400. }
  7401. protected static $cleaned_ids = array();
  7402. /**
  7403. * Unset all class variables except the following critical variables.
  7404. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  7405. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  7406. * @public
  7407. * @since 4.5.016 (2009-02-24)
  7408. */
  7409. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  7410. if (isset(self::$cleaned_ids[$this->file_id])) {
  7411. $destroyall = false;
  7412. }
  7413. if ($destroyall AND !$preserve_objcopy && isset($this->file_id)) {
  7414. self::$cleaned_ids[$this->file_id] = true;
  7415. // remove all temporary files
  7416. if ($handle = @opendir(K_PATH_CACHE)) {
  7417. while ( false !== ( $file_name = readdir( $handle ) ) ) {
  7418. if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
  7419. unlink(K_PATH_CACHE.$file_name);
  7420. }
  7421. }
  7422. closedir($handle);
  7423. }
  7424. if (isset($this->imagekeys)) {
  7425. foreach($this->imagekeys as $file) {
  7426. if (strpos($file, K_PATH_CACHE) === 0 && TCPDF_STATIC::file_exists($file)) {
  7427. @unlink($file);
  7428. }
  7429. }
  7430. }
  7431. }
  7432. $preserve = array(
  7433. 'file_id',
  7434. 'state',
  7435. 'bufferlen',
  7436. 'buffer',
  7437. 'cached_files',
  7438. 'imagekeys',
  7439. 'sign',
  7440. 'signature_data',
  7441. 'signature_max_length',
  7442. 'byterange_string',
  7443. 'tsa_timestamp',
  7444. 'tsa_data'
  7445. );
  7446. foreach (array_keys(get_object_vars($this)) as $val) {
  7447. if ($destroyall OR !in_array($val, $preserve)) {
  7448. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
  7449. unset($this->$val);
  7450. }
  7451. }
  7452. }
  7453. }
  7454. /**
  7455. * Check for locale-related bug
  7456. * @protected
  7457. */
  7458. protected function _dochecks() {
  7459. //Check for locale-related bug
  7460. if (1.1 == 1) {
  7461. $this->Error('Don\'t alter the locale before including class file');
  7462. }
  7463. //Check for decimal separator
  7464. if (sprintf('%.1F', 1.0) != '1.0') {
  7465. setlocale(LC_NUMERIC, 'C');
  7466. }
  7467. }
  7468. /**
  7469. * Return an array containing variations for the basic page number alias.
  7470. * @param $a (string) Base alias.
  7471. * @return array of page number aliases
  7472. * @protected
  7473. */
  7474. protected function getInternalPageNumberAliases($a= '') {
  7475. $alias = array();
  7476. // build array of Unicode + ASCII variants (the order is important)
  7477. $alias = array('u' => array(), 'a' => array());
  7478. $u = '{'.$a.'}';
  7479. $alias['u'][] = TCPDF_STATIC::_escape($u);
  7480. if ($this->isunicode) {
  7481. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
  7482. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7483. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
  7484. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7485. }
  7486. $alias['a'][] = TCPDF_STATIC::_escape($a);
  7487. return $alias;
  7488. }
  7489. /**
  7490. * Return an array containing all internal page aliases.
  7491. * @return array of page number aliases
  7492. * @protected
  7493. */
  7494. protected function getAllInternalPageNumberAliases() {
  7495. $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);
  7496. $pnalias = array();
  7497. foreach($basic_alias as $k => $a) {
  7498. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  7499. }
  7500. return $pnalias;
  7501. }
  7502. /**
  7503. * Replace right shift page number aliases with spaces to correct right alignment.
  7504. * This works perfectly only when using monospaced fonts.
  7505. * @param $page (string) Page content.
  7506. * @param $aliases (array) Array of page aliases.
  7507. * @param $diff (int) initial difference to add.
  7508. * @return replaced page content.
  7509. * @protected
  7510. */
  7511. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  7512. foreach ($aliases as $type => $alias) {
  7513. foreach ($alias as $a) {
  7514. // find position of compensation factor
  7515. $startnum = (strpos($a, ':') + 1);
  7516. $a = substr($a, 0, $startnum);
  7517. if (($pos = strpos($page, $a)) !== false) {
  7518. // end of alias
  7519. $endnum = strpos($page, '}', $pos);
  7520. // string to be replaced
  7521. $aa = substr($page, $pos, ($endnum - $pos + 1));
  7522. // get compensation factor
  7523. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  7524. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  7525. $ratio = floatval($ratio);
  7526. if ($type == 'u') {
  7527. $chrdiff = floor(($diff + 12) * $ratio);
  7528. $shift = str_repeat(' ', $chrdiff);
  7529. $shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
  7530. } else {
  7531. $chrdiff = floor(($diff + 11) * $ratio);
  7532. $shift = str_repeat(' ', $chrdiff);
  7533. }
  7534. $page = str_replace($aa, $shift, $page);
  7535. }
  7536. }
  7537. }
  7538. return $page;
  7539. }
  7540. /**
  7541. * Set page boxes to be included on page descriptions.
  7542. * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
  7543. * @protected
  7544. */
  7545. protected function setPageBoxTypes($boxes) {
  7546. $this->page_boxes = array();
  7547. foreach ($boxes as $box) {
  7548. if (in_array($box, TCPDF_STATIC::$pageboxes)) {
  7549. $this->page_boxes[] = $box;
  7550. }
  7551. }
  7552. }
  7553. /**
  7554. * Output pages (and replace page number aliases).
  7555. * @protected
  7556. */
  7557. protected function _putpages() {
  7558. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  7559. // get internal aliases for page numbers
  7560. $pnalias = $this->getAllInternalPageNumberAliases();
  7561. $num_pages = $this->numpages;
  7562. $ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
  7563. $ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
  7564. $ptp_num_chars = $this->GetNumChars($ptpa);
  7565. $pagegroupnum = 0;
  7566. $groupnum = 0;
  7567. $ptgu = 1;
  7568. $ptga = 1;
  7569. $ptg_num_chars = 1;
  7570. for ($n = 1; $n <= $num_pages; ++$n) {
  7571. // get current page
  7572. $temppage = $this->getPageBuffer($n);
  7573. $pagelen = strlen($temppage);
  7574. // set replacements for total pages number
  7575. $pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
  7576. $pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
  7577. $pnp_num_chars = $this->GetNumChars($pnpa);
  7578. $pdiff = 0; // difference used for right shift alignment of page numbers
  7579. $gdiff = 0; // difference used for right shift alignment of page group numbers
  7580. if (!empty($this->pagegroups)) {
  7581. if (isset($this->newpagegroup[$n])) {
  7582. $pagegroupnum = 0;
  7583. ++$groupnum;
  7584. $ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
  7585. $ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
  7586. $ptg_num_chars = $this->GetNumChars($ptga);
  7587. }
  7588. ++$pagegroupnum;
  7589. $pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
  7590. $pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
  7591. $png_num_chars = $this->GetNumChars($pnga);
  7592. // replace page numbers
  7593. $replace = array();
  7594. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  7595. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  7596. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  7597. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  7598. list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
  7599. }
  7600. // replace page numbers
  7601. $replace = array();
  7602. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  7603. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  7604. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  7605. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  7606. list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
  7607. // replace right shift alias
  7608. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  7609. // replace EPS marker
  7610. $temppage = str_replace($this->epsmarker, '', $temppage);
  7611. //Page
  7612. $this->page_obj_id[$n] = $this->_newobj();
  7613. $out = '<<';
  7614. $out .= ' /Type /Page';
  7615. $out .= ' /Parent 1 0 R';
  7616. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  7617. $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
  7618. }
  7619. $out .= ' /Resources 2 0 R';
  7620. foreach ($this->page_boxes as $box) {
  7621. $out .= ' /'.$box;
  7622. $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']);
  7623. }
  7624. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  7625. $out .= ' /BoxColorInfo <<';
  7626. foreach ($this->page_boxes as $box) {
  7627. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  7628. $out .= ' /'.$box.' <<';
  7629. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  7630. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  7631. $out .= ' /C [';
  7632. $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  7633. $out .= ' ]';
  7634. }
  7635. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  7636. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  7637. }
  7638. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  7639. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  7640. }
  7641. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  7642. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  7643. $out .= ' /D [';
  7644. foreach ($dashes as $dash) {
  7645. $out .= sprintf(' %F', ($dash * $this->k));
  7646. }
  7647. $out .= ' ]';
  7648. }
  7649. $out .= ' >>';
  7650. }
  7651. }
  7652. $out .= ' >>';
  7653. }
  7654. $out .= ' /Contents '.($this->n + 1).' 0 R';
  7655. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  7656. if (!$this->pdfa_mode) {
  7657. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  7658. }
  7659. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  7660. // page transitions
  7661. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  7662. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  7663. }
  7664. $out .= ' /Trans <<';
  7665. $out .= ' /Type /Trans';
  7666. if (isset($this->pagedim[$n]['trans']['S'])) {
  7667. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  7668. }
  7669. if (isset($this->pagedim[$n]['trans']['D'])) {
  7670. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  7671. }
  7672. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  7673. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  7674. }
  7675. if (isset($this->pagedim[$n]['trans']['M'])) {
  7676. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  7677. }
  7678. if (isset($this->pagedim[$n]['trans']['Di'])) {
  7679. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  7680. }
  7681. if (isset($this->pagedim[$n]['trans']['SS'])) {
  7682. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  7683. }
  7684. if (isset($this->pagedim[$n]['trans']['B'])) {
  7685. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  7686. }
  7687. $out .= ' >>';
  7688. }
  7689. $out .= $this->_getannotsrefs($n);
  7690. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  7691. $out .= ' >>';
  7692. $out .= "\n".'endobj';
  7693. $this->_out($out);
  7694. //Page content
  7695. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  7696. $this->_newobj();
  7697. $p = $this->_getrawstream($p);
  7698. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  7699. }
  7700. //Pages root
  7701. $out = $this->_getobj(1)."\n";
  7702. $out .= '<< /Type /Pages /Kids [';
  7703. foreach($this->page_obj_id as $page_obj) {
  7704. $out .= ' '.$page_obj.' 0 R';
  7705. }
  7706. $out .= ' ] /Count '.$num_pages.' >>';
  7707. $out .= "\n".'endobj';
  7708. $this->_out($out);
  7709. }
  7710. /**
  7711. * Get references to page annotations.
  7712. * @param $n (int) page number
  7713. * @return string
  7714. * @protected
  7715. * @author Nicola Asuni
  7716. * @since 5.0.010 (2010-05-17)
  7717. */
  7718. protected function _getannotsrefs($n) {
  7719. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  7720. return '';
  7721. }
  7722. $out = ' /Annots [';
  7723. if (isset($this->PageAnnots[$n])) {
  7724. foreach ($this->PageAnnots[$n] as $key => $val) {
  7725. if (!in_array($val['n'], $this->radio_groups)) {
  7726. $out .= ' '.$val['n'].' 0 R';
  7727. }
  7728. }
  7729. // add radiobutton groups
  7730. if (isset($this->radiobutton_groups[$n])) {
  7731. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  7732. if (isset($data['n'])) {
  7733. $out .= ' '.$data['n'].' 0 R';
  7734. }
  7735. }
  7736. }
  7737. }
  7738. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  7739. // set reference for signature object
  7740. $out .= ' '.$this->sig_obj_id.' 0 R';
  7741. }
  7742. if (!empty($this->empty_signature_appearance)) {
  7743. foreach ($this->empty_signature_appearance as $esa) {
  7744. if ($esa['page'] == $n) {
  7745. // set reference for empty signature objects
  7746. $out .= ' '.$esa['objid'].' 0 R';
  7747. }
  7748. }
  7749. }
  7750. $out .= ' ]';
  7751. return $out;
  7752. }
  7753. /**
  7754. * Output annotations objects for all pages.
  7755. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  7756. * See section 12.5 of PDF 32000_2008 reference.
  7757. * @protected
  7758. * @author Nicola Asuni
  7759. * @since 4.0.018 (2008-08-06)
  7760. */
  7761. protected function _putannotsobjs() {
  7762. // reset object counter
  7763. for ($n=1; $n <= $this->numpages; ++$n) {
  7764. if (isset($this->PageAnnots[$n])) {
  7765. // set page annotations
  7766. foreach ($this->PageAnnots[$n] as $key => $pl) {
  7767. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  7768. // create annotation object for grouping radiobuttons
  7769. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  7770. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  7771. $annots = '<<';
  7772. $annots .= ' /Type /Annot';
  7773. $annots .= ' /Subtype /Widget';
  7774. $annots .= ' /Rect [0 0 0 0]';
  7775. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  7776. // read only
  7777. $annots .= ' /F 68';
  7778. $annots .= ' /Ff 49153';
  7779. } else {
  7780. $annots .= ' /F 4'; // default print for PDF/A
  7781. $annots .= ' /Ff 49152';
  7782. }
  7783. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  7784. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  7785. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
  7786. }
  7787. $annots .= ' /FT /Btn';
  7788. $annots .= ' /Kids [';
  7789. $defval = '';
  7790. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  7791. if (isset($data['kid'])) {
  7792. $annots .= ' '.$data['kid'].' 0 R';
  7793. if ($data['def'] !== 'Off') {
  7794. $defval = $data['def'];
  7795. }
  7796. }
  7797. }
  7798. $annots .= ' ]';
  7799. if (!empty($defval)) {
  7800. $annots .= ' /V /'.$defval;
  7801. }
  7802. $annots .= ' >>';
  7803. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  7804. $this->form_obj_id[] = $radio_button_obj_id;
  7805. // store object id to be used on Parent entry of Kids
  7806. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  7807. }
  7808. $formfield = false;
  7809. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  7810. $a = $pl['x'] * $this->k;
  7811. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  7812. $c = $pl['w'] * $this->k;
  7813. $d = $pl['h'] * $this->k;
  7814. $rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
  7815. // create new annotation object
  7816. $annots = '<</Type /Annot';
  7817. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  7818. $annots .= ' /Rect ['.$rect.']';
  7819. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  7820. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  7821. $annots .= ' /FT /'.$pl['opt']['ft'];
  7822. $formfield = true;
  7823. }
  7824. if ($pl['opt']['subtype'] !== 'Link') {
  7825. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  7826. }
  7827. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  7828. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  7829. $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
  7830. if (isset($pl['opt']['f'])) {
  7831. $fval = 0;
  7832. if (is_array($pl['opt']['f'])) {
  7833. foreach ($pl['opt']['f'] as $f) {
  7834. switch (strtolower($f)) {
  7835. case 'invisible': {
  7836. $fval += 1 << 0;
  7837. break;
  7838. }
  7839. case 'hidden': {
  7840. $fval += 1 << 1;
  7841. break;
  7842. }
  7843. case 'print': {
  7844. $fval += 1 << 2;
  7845. break;
  7846. }
  7847. case 'nozoom': {
  7848. $fval += 1 << 3;
  7849. break;
  7850. }
  7851. case 'norotate': {
  7852. $fval += 1 << 4;
  7853. break;
  7854. }
  7855. case 'noview': {
  7856. $fval += 1 << 5;
  7857. break;
  7858. }
  7859. case 'readonly': {
  7860. $fval += 1 << 6;
  7861. break;
  7862. }
  7863. case 'locked': {
  7864. $fval += 1 << 8;
  7865. break;
  7866. }
  7867. case 'togglenoview': {
  7868. $fval += 1 << 9;
  7869. break;
  7870. }
  7871. case 'lockedcontents': {
  7872. $fval += 1 << 10;
  7873. break;
  7874. }
  7875. default: {
  7876. break;
  7877. }
  7878. }
  7879. }
  7880. } else {
  7881. $fval = intval($pl['opt']['f']);
  7882. }
  7883. } else {
  7884. $fval = 4;
  7885. }
  7886. if ($this->pdfa_mode) {
  7887. // force print flag for PDF/A mode
  7888. $fval |= 4;
  7889. }
  7890. $annots .= ' /F '.intval($fval);
  7891. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  7892. $annots .= ' /AS /'.$pl['opt']['as'];
  7893. }
  7894. if (isset($pl['opt']['ap'])) {
  7895. // appearance stream
  7896. $annots .= ' /AP <<';
  7897. if (is_array($pl['opt']['ap'])) {
  7898. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  7899. // $apmode can be: n = normal; r = rollover; d = down;
  7900. $annots .= ' /'.strtoupper($apmode);
  7901. if (is_array($apdef)) {
  7902. $annots .= ' <<';
  7903. foreach ($apdef as $apstate => $stream) {
  7904. // reference to XObject that define the appearance for this mode-state
  7905. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  7906. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  7907. }
  7908. $annots .= ' >>';
  7909. } else {
  7910. // reference to XObject that define the appearance for this mode
  7911. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  7912. $annots .= ' '.$apsobjid.' 0 R';
  7913. }
  7914. }
  7915. } else {
  7916. $annots .= $pl['opt']['ap'];
  7917. }
  7918. $annots .= ' >>';
  7919. }
  7920. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  7921. $annots .= ' /BS <<';
  7922. $annots .= ' /Type /Border';
  7923. if (isset($pl['opt']['bs']['w'])) {
  7924. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  7925. }
  7926. $bstyles = array('S', 'D', 'B', 'I', 'U');
  7927. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  7928. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7929. }
  7930. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  7931. $annots .= ' /D [';
  7932. foreach ($pl['opt']['bs']['d'] as $cord) {
  7933. $annots .= ' '.intval($cord);
  7934. }
  7935. $annots .= ']';
  7936. }
  7937. $annots .= ' >>';
  7938. } else {
  7939. $annots .= ' /Border [';
  7940. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  7941. $annots .= intval($pl['opt']['border'][0]).' ';
  7942. $annots .= intval($pl['opt']['border'][1]).' ';
  7943. $annots .= intval($pl['opt']['border'][2]);
  7944. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  7945. $annots .= ' [';
  7946. foreach ($pl['opt']['border'][3] as $dash) {
  7947. $annots .= intval($dash).' ';
  7948. }
  7949. $annots .= ']';
  7950. }
  7951. } else {
  7952. $annots .= '0 0 0';
  7953. }
  7954. $annots .= ']';
  7955. }
  7956. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  7957. $annots .= ' /BE <<';
  7958. $bstyles = array('S', 'C');
  7959. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
  7960. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7961. } else {
  7962. $annots .= ' /S /S';
  7963. }
  7964. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  7965. $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
  7966. }
  7967. $annots .= '>>';
  7968. }
  7969. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  7970. $annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
  7971. }
  7972. //$annots .= ' /StructParent ';
  7973. //$annots .= ' /OC ';
  7974. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  7975. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  7976. // this is a markup type
  7977. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  7978. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  7979. }
  7980. //$annots .= ' /Popup ';
  7981. if (isset($pl['opt']['ca'])) {
  7982. $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
  7983. }
  7984. if (isset($pl['opt']['rc'])) {
  7985. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  7986. }
  7987. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
  7988. //$annots .= ' /IRT ';
  7989. if (isset($pl['opt']['subj'])) {
  7990. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  7991. }
  7992. //$annots .= ' /RT ';
  7993. //$annots .= ' /IT ';
  7994. //$annots .= ' /ExData ';
  7995. }
  7996. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  7997. // Annotation types
  7998. switch (strtolower($pl['opt']['subtype'])) {
  7999. case 'text': {
  8000. if (isset($pl['opt']['open'])) {
  8001. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  8002. }
  8003. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  8004. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8005. $annots .= ' /Name /'.$pl['opt']['name'];
  8006. } else {
  8007. $annots .= ' /Name /Note';
  8008. }
  8009. $statemodels = array('Marked', 'Review');
  8010. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  8011. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  8012. } else {
  8013. $pl['opt']['statemodel'] = 'Marked';
  8014. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  8015. }
  8016. if ($pl['opt']['statemodel'] == 'Marked') {
  8017. $states = array('Accepted', 'Unmarked');
  8018. } else {
  8019. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  8020. }
  8021. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  8022. $annots .= ' /State /'.$pl['opt']['state'];
  8023. } else {
  8024. if ($pl['opt']['statemodel'] == 'Marked') {
  8025. $annots .= ' /State /Unmarked';
  8026. } else {
  8027. $annots .= ' /State /None';
  8028. }
  8029. }
  8030. break;
  8031. }
  8032. case 'link': {
  8033. if (is_string($pl['txt']) && !empty($pl['txt'])) {
  8034. if ($pl['txt'][0] == '#') {
  8035. // internal destination
  8036. $annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
  8037. } elseif ($pl['txt'][0] == '%') {
  8038. // embedded PDF file
  8039. $filename = basename(substr($pl['txt'], 1));
  8040. $annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  8041. } elseif ($pl['txt'][0] == '*') {
  8042. // embedded generic file
  8043. $filename = basename(substr($pl['txt'], 1));
  8044. $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});';
  8045. $annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
  8046. } else {
  8047. $parsedUrl = parse_url($pl['txt']);
  8048. if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
  8049. // relative link to a PDF file
  8050. $dest = '[0 /Fit]'; // default page 0
  8051. if (!empty($parsedUrl['fragment'])) {
  8052. // check for named destination
  8053. $tmp = explode('=', $parsedUrl['fragment']);
  8054. $dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
  8055. }
  8056. $annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
  8057. } else {
  8058. // external URI link
  8059. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  8060. }
  8061. }
  8062. } elseif (isset($this->links[$pl['txt']])) {
  8063. // internal link ID
  8064. $l = $this->links[$pl['txt']];
  8065. if (isset($this->page_obj_id[($l['p'])])) {
  8066. $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)));
  8067. }
  8068. }
  8069. $hmodes = array('N', 'I', 'O', 'P');
  8070. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  8071. $annots .= ' /H /'.$pl['opt']['h'];
  8072. } else {
  8073. $annots .= ' /H /I';
  8074. }
  8075. //$annots .= ' /PA ';
  8076. //$annots .= ' /Quadpoints ';
  8077. break;
  8078. }
  8079. case 'freetext': {
  8080. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8081. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8082. }
  8083. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8084. $annots .= ' /Q '.intval($pl['opt']['q']);
  8085. }
  8086. if (isset($pl['opt']['rc'])) {
  8087. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8088. }
  8089. if (isset($pl['opt']['ds'])) {
  8090. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  8091. }
  8092. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  8093. $annots .= ' /CL [';
  8094. foreach ($pl['opt']['cl'] as $cl) {
  8095. $annots .= sprintf('%F ', $cl * $this->k);
  8096. }
  8097. $annots .= ']';
  8098. }
  8099. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  8100. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  8101. $annots .= ' /IT /'.$pl['opt']['it'];
  8102. }
  8103. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  8104. $l = $pl['opt']['rd'][0] * $this->k;
  8105. $r = $pl['opt']['rd'][1] * $this->k;
  8106. $t = $pl['opt']['rd'][2] * $this->k;
  8107. $b = $pl['opt']['rd'][3] * $this->k;
  8108. $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
  8109. }
  8110. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  8111. $annots .= ' /LE /'.$pl['opt']['le'];
  8112. }
  8113. break;
  8114. }
  8115. case 'line': {
  8116. break;
  8117. }
  8118. case 'square': {
  8119. break;
  8120. }
  8121. case 'circle': {
  8122. break;
  8123. }
  8124. case 'polygon': {
  8125. break;
  8126. }
  8127. case 'polyline': {
  8128. break;
  8129. }
  8130. case 'highlight': {
  8131. break;
  8132. }
  8133. case 'underline': {
  8134. break;
  8135. }
  8136. case 'squiggly': {
  8137. break;
  8138. }
  8139. case 'strikeout': {
  8140. break;
  8141. }
  8142. case 'stamp': {
  8143. break;
  8144. }
  8145. case 'caret': {
  8146. break;
  8147. }
  8148. case 'ink': {
  8149. break;
  8150. }
  8151. case 'popup': {
  8152. break;
  8153. }
  8154. case 'fileattachment': {
  8155. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  8156. // embedded files are not allowed in PDF/A mode version 1 and 2
  8157. break;
  8158. }
  8159. if (!isset($pl['opt']['fs'])) {
  8160. break;
  8161. }
  8162. $filename = basename($pl['opt']['fs']);
  8163. if (isset($this->embeddedfiles[$filename]['f'])) {
  8164. $annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8165. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  8166. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8167. $annots .= ' /Name /'.$pl['opt']['name'];
  8168. } else {
  8169. $annots .= ' /Name /PushPin';
  8170. }
  8171. // index (zero-based) of the annotation in the Annots array of this page
  8172. $this->embeddedfiles[$filename]['a'] = $key;
  8173. }
  8174. break;
  8175. }
  8176. case 'sound': {
  8177. if (!isset($pl['opt']['fs'])) {
  8178. break;
  8179. }
  8180. $filename = basename($pl['opt']['fs']);
  8181. if (isset($this->embeddedfiles[$filename]['f'])) {
  8182. // ... TO BE COMPLETED ...
  8183. // /R /C /B /E /CO /CP
  8184. $annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8185. $iconsapp = array('Speaker', 'Mic');
  8186. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8187. $annots .= ' /Name /'.$pl['opt']['name'];
  8188. } else {
  8189. $annots .= ' /Name /Speaker';
  8190. }
  8191. }
  8192. break;
  8193. }
  8194. case 'movie': {
  8195. break;
  8196. }
  8197. case 'widget': {
  8198. $hmode = array('N', 'I', 'O', 'P', 'T');
  8199. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  8200. $annots .= ' /H /'.$pl['opt']['h'];
  8201. }
  8202. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  8203. $annots .= ' /MK <<';
  8204. if (isset($pl['opt']['mk']['r'])) {
  8205. $annots .= ' /R '.$pl['opt']['mk']['r'];
  8206. }
  8207. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  8208. $annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
  8209. }
  8210. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  8211. $annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
  8212. }
  8213. if (isset($pl['opt']['mk']['ca'])) {
  8214. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  8215. }
  8216. if (isset($pl['opt']['mk']['rc'])) {
  8217. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  8218. }
  8219. if (isset($pl['opt']['mk']['ac'])) {
  8220. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  8221. }
  8222. if (isset($pl['opt']['mk']['i'])) {
  8223. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  8224. if ($info !== false) {
  8225. $annots .= ' /I '.$info['n'].' 0 R';
  8226. }
  8227. }
  8228. if (isset($pl['opt']['mk']['ri'])) {
  8229. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  8230. if ($info !== false) {
  8231. $annots .= ' /RI '.$info['n'].' 0 R';
  8232. }
  8233. }
  8234. if (isset($pl['opt']['mk']['ix'])) {
  8235. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  8236. if ($info !== false) {
  8237. $annots .= ' /IX '.$info['n'].' 0 R';
  8238. }
  8239. }
  8240. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  8241. $annots .= ' /IF <<';
  8242. $if_sw = array('A', 'B', 'S', 'N');
  8243. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  8244. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  8245. }
  8246. $if_s = array('A', 'P');
  8247. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  8248. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  8249. }
  8250. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  8251. $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  8252. }
  8253. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  8254. $annots .= ' /FB true';
  8255. }
  8256. $annots .= '>>';
  8257. }
  8258. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  8259. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  8260. }
  8261. $annots .= '>>';
  8262. } // end MK
  8263. // --- Entries for field dictionaries ---
  8264. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8265. // set parent
  8266. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  8267. }
  8268. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  8269. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  8270. }
  8271. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  8272. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  8273. }
  8274. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  8275. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  8276. }
  8277. if (isset($pl['opt']['ff'])) {
  8278. if (is_array($pl['opt']['ff'])) {
  8279. // array of bit settings
  8280. $flag = 0;
  8281. foreach($pl['opt']['ff'] as $val) {
  8282. $flag += 1 << ($val - 1);
  8283. }
  8284. } else {
  8285. $flag = intval($pl['opt']['ff']);
  8286. }
  8287. $annots .= ' /Ff '.$flag;
  8288. }
  8289. if (isset($pl['opt']['maxlen'])) {
  8290. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  8291. }
  8292. if (isset($pl['opt']['v'])) {
  8293. $annots .= ' /V';
  8294. if (is_array($pl['opt']['v'])) {
  8295. foreach ($pl['opt']['v'] AS $optval) {
  8296. if (is_float($optval)) {
  8297. $optval = sprintf('%F', $optval);
  8298. }
  8299. $annots .= ' '.$optval;
  8300. }
  8301. } else {
  8302. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  8303. }
  8304. }
  8305. if (isset($pl['opt']['dv'])) {
  8306. $annots .= ' /DV';
  8307. if (is_array($pl['opt']['dv'])) {
  8308. foreach ($pl['opt']['dv'] AS $optval) {
  8309. if (is_float($optval)) {
  8310. $optval = sprintf('%F', $optval);
  8311. }
  8312. $annots .= ' '.$optval;
  8313. }
  8314. } else {
  8315. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  8316. }
  8317. }
  8318. if (isset($pl['opt']['rv'])) {
  8319. $annots .= ' /RV';
  8320. if (is_array($pl['opt']['rv'])) {
  8321. foreach ($pl['opt']['rv'] AS $optval) {
  8322. if (is_float($optval)) {
  8323. $optval = sprintf('%F', $optval);
  8324. }
  8325. $annots .= ' '.$optval;
  8326. }
  8327. } else {
  8328. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  8329. }
  8330. }
  8331. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  8332. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  8333. }
  8334. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  8335. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  8336. }
  8337. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8338. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8339. }
  8340. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8341. $annots .= ' /Q '.intval($pl['opt']['q']);
  8342. }
  8343. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  8344. $annots .= ' /Opt [';
  8345. foreach($pl['opt']['opt'] AS $copt) {
  8346. if (is_array($copt)) {
  8347. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  8348. } else {
  8349. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  8350. }
  8351. }
  8352. $annots .= ']';
  8353. }
  8354. if (isset($pl['opt']['ti'])) {
  8355. $annots .= ' /TI '.intval($pl['opt']['ti']);
  8356. }
  8357. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  8358. $annots .= ' /I [';
  8359. foreach($pl['opt']['i'] AS $copt) {
  8360. $annots .= intval($copt).' ';
  8361. }
  8362. $annots .= ']';
  8363. }
  8364. break;
  8365. }
  8366. case 'screen': {
  8367. break;
  8368. }
  8369. case 'printermark': {
  8370. break;
  8371. }
  8372. case 'trapnet': {
  8373. break;
  8374. }
  8375. case 'watermark': {
  8376. break;
  8377. }
  8378. case '3d': {
  8379. break;
  8380. }
  8381. default: {
  8382. break;
  8383. }
  8384. }
  8385. $annots .= '>>';
  8386. // create new annotation object
  8387. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  8388. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8389. // store reference of form object
  8390. $this->form_obj_id[] = $annot_obj_id;
  8391. }
  8392. }
  8393. }
  8394. } // end for each page
  8395. }
  8396. /**
  8397. * Put appearance streams XObject used to define annotation's appearance states.
  8398. * @param $w (int) annotation width
  8399. * @param $h (int) annotation height
  8400. * @param $stream (string) appearance stream
  8401. * @return int object ID
  8402. * @protected
  8403. * @since 4.8.001 (2009-09-09)
  8404. */
  8405. protected function _putAPXObject($w=0, $h=0, $stream='') {
  8406. $stream = trim($stream);
  8407. $out = $this->_getobj()."\n";
  8408. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  8409. $out .= '<<';
  8410. $out .= ' /Type /XObject';
  8411. $out .= ' /Subtype /Form';
  8412. $out .= ' /FormType 1';
  8413. if ($this->compress) {
  8414. $stream = gzcompress($stream);
  8415. $out .= ' /Filter /FlateDecode';
  8416. }
  8417. $rect = sprintf('%F %F', $w, $h);
  8418. $out .= ' /BBox [0 0 '.$rect.']';
  8419. $out .= ' /Matrix [1 0 0 1 0 0]';
  8420. $out .= ' /Resources 2 0 R';
  8421. $stream = $this->_getrawstream($stream);
  8422. $out .= ' /Length '.strlen($stream);
  8423. $out .= ' >>';
  8424. $out .= ' stream'."\n".$stream."\n".'endstream';
  8425. $out .= "\n".'endobj';
  8426. $this->_out($out);
  8427. return $this->n;
  8428. }
  8429. /**
  8430. * Output fonts.
  8431. * @author Nicola Asuni
  8432. * @protected
  8433. */
  8434. protected function _putfonts() {
  8435. $nf = $this->n;
  8436. foreach ($this->diffs as $diff) {
  8437. //Encodings
  8438. $this->_newobj();
  8439. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  8440. }
  8441. $mqr = TCPDF_STATIC::get_mqr();
  8442. TCPDF_STATIC::set_mqr(false);
  8443. foreach ($this->FontFiles as $file => $info) {
  8444. // search and get font file to embedd
  8445. $fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
  8446. if (!TCPDF_STATIC::empty_string($fontfile)) {
  8447. $font = file_get_contents($fontfile);
  8448. $compressed = (substr($file, -2) == '.z');
  8449. if ((!$compressed) AND (isset($info['length2']))) {
  8450. $header = (ord($font[0]) == 128);
  8451. if ($header) {
  8452. // strip first binary header
  8453. $font = substr($font, 6);
  8454. }
  8455. if ($header AND (ord($font[$info['length1']]) == 128)) {
  8456. // strip second binary header
  8457. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  8458. }
  8459. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  8460. if ($compressed) {
  8461. // uncompress font
  8462. $font = gzuncompress($font);
  8463. }
  8464. // merge subset characters
  8465. $subsetchars = array(); // used chars
  8466. foreach ($info['fontkeys'] as $fontkey) {
  8467. $fontinfo = $this->getFontBuffer($fontkey);
  8468. $subsetchars += $fontinfo['subsetchars'];
  8469. }
  8470. // rebuild a font subset
  8471. $font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
  8472. // calculate new font length
  8473. $info['length1'] = strlen($font);
  8474. if ($compressed) {
  8475. // recompress font
  8476. $font = gzcompress($font);
  8477. }
  8478. }
  8479. $this->_newobj();
  8480. $this->FontFiles[$file]['n'] = $this->n;
  8481. $stream = $this->_getrawstream($font);
  8482. $out = '<< /Length '.strlen($stream);
  8483. if ($compressed) {
  8484. $out .= ' /Filter /FlateDecode';
  8485. }
  8486. $out .= ' /Length1 '.$info['length1'];
  8487. if (isset($info['length2'])) {
  8488. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  8489. }
  8490. $out .= ' >>';
  8491. $out .= ' stream'."\n".$stream."\n".'endstream';
  8492. $out .= "\n".'endobj';
  8493. $this->_out($out);
  8494. }
  8495. }
  8496. TCPDF_STATIC::set_mqr($mqr);
  8497. foreach ($this->fontkeys as $k) {
  8498. //Font objects
  8499. $font = $this->getFontBuffer($k);
  8500. $type = $font['type'];
  8501. $name = $font['name'];
  8502. if ($type == 'core') {
  8503. // standard core font
  8504. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8505. $out .= '<</Type /Font';
  8506. $out .= ' /Subtype /Type1';
  8507. $out .= ' /BaseFont /'.$name;
  8508. $out .= ' /Name /F'.$font['i'];
  8509. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  8510. $out .= ' /Encoding /WinAnsiEncoding';
  8511. }
  8512. if ($k == 'helvetica') {
  8513. // add default font for annotations
  8514. $this->annotation_fonts[$k] = $font['i'];
  8515. }
  8516. $out .= ' >>';
  8517. $out .= "\n".'endobj';
  8518. $this->_out($out);
  8519. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  8520. // additional Type1 or TrueType font
  8521. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8522. $out .= '<</Type /Font';
  8523. $out .= ' /Subtype /'.$type;
  8524. $out .= ' /BaseFont /'.$name;
  8525. $out .= ' /Name /F'.$font['i'];
  8526. $out .= ' /FirstChar 32 /LastChar 255';
  8527. $out .= ' /Widths '.($this->n + 1).' 0 R';
  8528. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  8529. if ($font['enc']) {
  8530. if (isset($font['diff'])) {
  8531. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  8532. } else {
  8533. $out .= ' /Encoding /WinAnsiEncoding';
  8534. }
  8535. }
  8536. $out .= ' >>';
  8537. $out .= "\n".'endobj';
  8538. $this->_out($out);
  8539. // Widths
  8540. $this->_newobj();
  8541. $s = '[';
  8542. for ($i = 32; $i < 256; ++$i) {
  8543. if (isset($font['cw'][$i])) {
  8544. $s .= $font['cw'][$i].' ';
  8545. } else {
  8546. $s .= $font['dw'].' ';
  8547. }
  8548. }
  8549. $s .= ']';
  8550. $s .= "\n".'endobj';
  8551. $this->_out($s);
  8552. //Descriptor
  8553. $this->_newobj();
  8554. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8555. foreach ($font['desc'] as $fdk => $fdv) {
  8556. if (is_float($fdv)) {
  8557. $fdv = sprintf('%F', $fdv);
  8558. }
  8559. $s .= ' /'.$fdk.' '.$fdv.'';
  8560. }
  8561. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8562. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8563. }
  8564. $s .= '>>';
  8565. $s .= "\n".'endobj';
  8566. $this->_out($s);
  8567. } else {
  8568. // additional types
  8569. $mtd = '_put'.strtolower($type);
  8570. if (!method_exists($this, $mtd)) {
  8571. $this->Error('Unsupported font type: '.$type);
  8572. }
  8573. $this->$mtd($font);
  8574. }
  8575. }
  8576. }
  8577. /**
  8578. * Adds unicode fonts.<br>
  8579. * Based on PDF Reference 1.3 (section 5)
  8580. * @param $font (array) font data
  8581. * @protected
  8582. * @author Nicola Asuni
  8583. * @since 1.52.0.TC005 (2005-01-05)
  8584. */
  8585. protected function _puttruetypeunicode($font) {
  8586. $fontname = '';
  8587. if ($font['subset']) {
  8588. // change name for font subsetting
  8589. $subtag = sprintf('%06u', $font['i']);
  8590. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  8591. $fontname .= $subtag.'+';
  8592. }
  8593. $fontname .= $font['name'];
  8594. // Type0 Font
  8595. // A composite font composed of other fonts, organized hierarchically
  8596. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8597. $out .= '<< /Type /Font';
  8598. $out .= ' /Subtype /Type0';
  8599. $out .= ' /BaseFont /'.$fontname;
  8600. $out .= ' /Name /F'.$font['i'];
  8601. $out .= ' /Encoding /'.$font['enc'];
  8602. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  8603. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  8604. $out .= ' >>';
  8605. $out .= "\n".'endobj';
  8606. $this->_out($out);
  8607. // ToUnicode map for Identity-H
  8608. $stream = TCPDF_FONT_DATA::$uni_identity_h;
  8609. // ToUnicode Object
  8610. $this->_newobj();
  8611. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  8612. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8613. $stream = $this->_getrawstream($stream);
  8614. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  8615. // CIDFontType2
  8616. // A CIDFont whose glyph descriptions are based on TrueType font technology
  8617. $oid = $this->_newobj();
  8618. $out = '<< /Type /Font';
  8619. $out .= ' /Subtype /CIDFontType2';
  8620. $out .= ' /BaseFont /'.$fontname;
  8621. // A dictionary containing entries that define the character collection of the CIDFont.
  8622. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8623. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8624. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8625. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  8626. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8627. $out .= ' /DW '.$font['dw']; // default width
  8628. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
  8629. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8630. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  8631. }
  8632. $out .= ' >>';
  8633. $out .= "\n".'endobj';
  8634. $this->_out($out);
  8635. // Font descriptor
  8636. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  8637. $this->_newobj();
  8638. $out = '<< /Type /FontDescriptor';
  8639. $out .= ' /FontName /'.$fontname;
  8640. foreach ($font['desc'] as $key => $value) {
  8641. if (is_float($value)) {
  8642. $value = sprintf('%F', $value);
  8643. }
  8644. $out .= ' /'.$key.' '.$value;
  8645. }
  8646. $fontdir = false;
  8647. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8648. // A stream containing a TrueType font
  8649. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8650. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  8651. }
  8652. $out .= ' >>';
  8653. $out .= "\n".'endobj';
  8654. $this->_out($out);
  8655. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8656. $this->_newobj();
  8657. // Embed CIDToGIDMap
  8658. // A specification of the mapping from CIDs to glyph indices
  8659. // search and get CTG font file to embedd
  8660. $ctgfile = strtolower($font['ctg']);
  8661. // search and get ctg font file to embedd
  8662. $fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
  8663. if (TCPDF_STATIC::empty_string($fontfile)) {
  8664. $this->Error('Font file not found: '.$ctgfile);
  8665. }
  8666. $stream = $this->_getrawstream(file_get_contents($fontfile));
  8667. $out = '<< /Length '.strlen($stream).'';
  8668. if (substr($fontfile, -2) == '.z') { // check file extension
  8669. // Decompresses data encoded using the public-domain
  8670. // zlib/deflate compression method, reproducing the
  8671. // original text or binary data
  8672. $out .= ' /Filter /FlateDecode';
  8673. }
  8674. $out .= ' >>';
  8675. $out .= ' stream'."\n".$stream."\n".'endstream';
  8676. $out .= "\n".'endobj';
  8677. $this->_out($out);
  8678. }
  8679. }
  8680. /**
  8681. * Output CID-0 fonts.
  8682. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  8683. * @param $font (array) font data
  8684. * @protected
  8685. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  8686. * @since 3.2.000 (2008-06-23)
  8687. */
  8688. protected function _putcidfont0($font) {
  8689. $cidoffset = 0;
  8690. if (!isset($font['cw'][1])) {
  8691. $cidoffset = 31;
  8692. }
  8693. if (isset($font['cidinfo']['uni2cid'])) {
  8694. // convert unicode to cid.
  8695. $uni2cid = $font['cidinfo']['uni2cid'];
  8696. $cw = array();
  8697. foreach ($font['cw'] as $uni => $width) {
  8698. if (isset($uni2cid[$uni])) {
  8699. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  8700. } elseif ($uni < 256) {
  8701. $cw[$uni] = $width;
  8702. } // else unknown character
  8703. }
  8704. $font = array_merge($font, array('cw' => $cw));
  8705. }
  8706. $name = $font['name'];
  8707. $enc = $font['enc'];
  8708. if ($enc) {
  8709. $longname = $name.'-'.$enc;
  8710. } else {
  8711. $longname = $name;
  8712. }
  8713. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8714. $out .= '<</Type /Font';
  8715. $out .= ' /Subtype /Type0';
  8716. $out .= ' /BaseFont /'.$longname;
  8717. $out .= ' /Name /F'.$font['i'];
  8718. if ($enc) {
  8719. $out .= ' /Encoding /'.$enc;
  8720. }
  8721. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  8722. $out .= ' >>';
  8723. $out .= "\n".'endobj';
  8724. $this->_out($out);
  8725. $oid = $this->_newobj();
  8726. $out = '<</Type /Font';
  8727. $out .= ' /Subtype /CIDFontType0';
  8728. $out .= ' /BaseFont /'.$name;
  8729. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8730. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8731. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8732. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  8733. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8734. $out .= ' /DW '.$font['dw'];
  8735. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
  8736. $out .= ' >>';
  8737. $out .= "\n".'endobj';
  8738. $this->_out($out);
  8739. $this->_newobj();
  8740. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8741. foreach ($font['desc'] as $k => $v) {
  8742. if ($k != 'Style') {
  8743. if (is_float($v)) {
  8744. $v = sprintf('%F', $v);
  8745. }
  8746. $s .= ' /'.$k.' '.$v.'';
  8747. }
  8748. }
  8749. $s .= '>>';
  8750. $s .= "\n".'endobj';
  8751. $this->_out($s);
  8752. }
  8753. /**
  8754. * Output images.
  8755. * @protected
  8756. */
  8757. protected function _putimages() {
  8758. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8759. foreach ($this->imagekeys as $file) {
  8760. $info = $this->getImageBuffer($file);
  8761. // set object for alternate images array
  8762. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  8763. $altoid = $this->_newobj();
  8764. $out = '[';
  8765. foreach ($info['altimgs'] as $altimage) {
  8766. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  8767. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  8768. $out .= ' /DefaultForPrinting';
  8769. if ($altimage[1] === true) {
  8770. $out .= ' true';
  8771. } else {
  8772. $out .= ' false';
  8773. }
  8774. $out .= ' >>';
  8775. }
  8776. }
  8777. $out .= ' ]';
  8778. $out .= "\n".'endobj';
  8779. $this->_out($out);
  8780. }
  8781. // set image object
  8782. $oid = $this->_newobj();
  8783. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  8784. $this->setImageSubBuffer($file, 'n', $this->n);
  8785. $out = '<</Type /XObject';
  8786. $out .= ' /Subtype /Image';
  8787. $out .= ' /Width '.$info['w'];
  8788. $out .= ' /Height '.$info['h'];
  8789. if (array_key_exists('masked', $info)) {
  8790. $out .= ' /SMask '.($this->n - 1).' 0 R';
  8791. }
  8792. // set color space
  8793. $icc = false;
  8794. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  8795. // ICC Colour Space
  8796. $icc = true;
  8797. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  8798. } elseif ($info['cs'] == 'Indexed') {
  8799. // Indexed Colour Space
  8800. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  8801. } else {
  8802. // Device Colour Space
  8803. $out .= ' /ColorSpace /'.$info['cs'];
  8804. }
  8805. if ($info['cs'] == 'DeviceCMYK') {
  8806. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  8807. }
  8808. $out .= ' /BitsPerComponent '.$info['bpc'];
  8809. if (isset($altoid) AND ($altoid > 0)) {
  8810. // reference to alternate images dictionary
  8811. $out .= ' /Alternates '.$altoid.' 0 R';
  8812. }
  8813. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  8814. // external stream
  8815. $out .= ' /Length 0';
  8816. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  8817. if (isset($info['f'])) {
  8818. $out .= ' /FFilter /'.$info['f'];
  8819. }
  8820. $out .= ' >>';
  8821. $out .= ' stream'."\n".'endstream';
  8822. } else {
  8823. if (isset($info['f'])) {
  8824. $out .= ' /Filter /'.$info['f'];
  8825. }
  8826. if (isset($info['parms'])) {
  8827. $out .= ' '.$info['parms'];
  8828. }
  8829. if (isset($info['trns']) AND is_array($info['trns'])) {
  8830. $trns = '';
  8831. $count_info = count($info['trns']);
  8832. if ($info['cs'] == 'Indexed') {
  8833. $maxval =(pow(2, $info['bpc']) - 1);
  8834. for ($i = 0; $i < $count_info; ++$i) {
  8835. if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
  8836. // this is not a binary type mask @TODO: create a SMask
  8837. $trns = '';
  8838. break;
  8839. } elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
  8840. // store the first fully transparent value
  8841. $trns .= $i.' '.$i.' ';
  8842. }
  8843. }
  8844. } else {
  8845. // grayscale or RGB
  8846. for ($i = 0; $i < $count_info; ++$i) {
  8847. if ($info['trns'][$i] == 0) {
  8848. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  8849. }
  8850. }
  8851. }
  8852. // Colour Key Masking
  8853. if (!empty($trns)) {
  8854. $out .= ' /Mask ['.$trns.']';
  8855. }
  8856. }
  8857. $stream = $this->_getrawstream($info['data']);
  8858. $out .= ' /Length '.strlen($stream).' >>';
  8859. $out .= ' stream'."\n".$stream."\n".'endstream';
  8860. }
  8861. $out .= "\n".'endobj';
  8862. $this->_out($out);
  8863. if ($icc) {
  8864. // ICC colour profile
  8865. $this->_newobj();
  8866. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  8867. $icc = $this->_getrawstream($icc);
  8868. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  8869. } elseif ($info['cs'] == 'Indexed') {
  8870. // colour palette
  8871. $this->_newobj();
  8872. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  8873. $pal = $this->_getrawstream($pal);
  8874. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  8875. }
  8876. }
  8877. }
  8878. /**
  8879. * Output Form XObjects Templates.
  8880. * @author Nicola Asuni
  8881. * @since 5.8.017 (2010-08-24)
  8882. * @protected
  8883. * @see startTemplate(), endTemplate(), printTemplate()
  8884. */
  8885. protected function _putxobjects() {
  8886. foreach ($this->xobjects as $key => $data) {
  8887. if (isset($data['outdata'])) {
  8888. $stream = str_replace($this->epsmarker, '', trim($data['outdata']));
  8889. $out = $this->_getobj($data['n'])."\n";
  8890. $out .= '<<';
  8891. $out .= ' /Type /XObject';
  8892. $out .= ' /Subtype /Form';
  8893. $out .= ' /FormType 1';
  8894. if ($this->compress) {
  8895. $stream = gzcompress($stream);
  8896. $out .= ' /Filter /FlateDecode';
  8897. }
  8898. $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));
  8899. $out .= ' /Matrix [1 0 0 1 0 0]';
  8900. $out .= ' /Resources <<';
  8901. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8902. if (!$this->pdfa_mode) {
  8903. // transparency
  8904. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  8905. $out .= ' /ExtGState <<';
  8906. foreach ($data['extgstates'] as $k => $extgstate) {
  8907. if (isset($this->extgstates[$k]['name'])) {
  8908. $out .= ' /'.$this->extgstates[$k]['name'];
  8909. } else {
  8910. $out .= ' /GS'.$k;
  8911. }
  8912. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  8913. }
  8914. $out .= ' >>';
  8915. }
  8916. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  8917. $gp = '';
  8918. $gs = '';
  8919. foreach ($data['gradients'] as $id => $grad) {
  8920. // gradient patterns
  8921. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  8922. // gradient shadings
  8923. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  8924. }
  8925. $out .= ' /Pattern <<'.$gp.' >>';
  8926. $out .= ' /Shading <<'.$gs.' >>';
  8927. }
  8928. }
  8929. // spot colors
  8930. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  8931. $out .= ' /ColorSpace <<';
  8932. foreach ($data['spot_colors'] as $name => $color) {
  8933. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  8934. }
  8935. $out .= ' >>';
  8936. }
  8937. // fonts
  8938. if (!empty($data['fonts'])) {
  8939. $out .= ' /Font <<';
  8940. foreach ($data['fonts'] as $fontkey => $fontid) {
  8941. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  8942. }
  8943. $out .= ' >>';
  8944. }
  8945. // images or nested xobjects
  8946. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  8947. $out .= ' /XObject <<';
  8948. foreach ($data['images'] as $imgid) {
  8949. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  8950. }
  8951. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  8952. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  8953. }
  8954. $out .= ' >>';
  8955. }
  8956. $out .= ' >>'; //end resources
  8957. if (isset($data['group']) AND ($data['group'] !== false)) {
  8958. // set transparency group
  8959. $out .= ' /Group << /Type /Group /S /Transparency';
  8960. if (is_array($data['group'])) {
  8961. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  8962. $out .= ' /CS /'.$data['group']['CS'];
  8963. }
  8964. if (isset($data['group']['I'])) {
  8965. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  8966. }
  8967. if (isset($data['group']['K'])) {
  8968. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  8969. }
  8970. }
  8971. $out .= ' >>';
  8972. }
  8973. $stream = $this->_getrawstream($stream, $data['n']);
  8974. $out .= ' /Length '.strlen($stream);
  8975. $out .= ' >>';
  8976. $out .= ' stream'."\n".$stream."\n".'endstream';
  8977. $out .= "\n".'endobj';
  8978. $this->_out($out);
  8979. }
  8980. }
  8981. }
  8982. /**
  8983. * Output Spot Colors Resources.
  8984. * @protected
  8985. * @since 4.0.024 (2008-09-12)
  8986. */
  8987. protected function _putspotcolors() {
  8988. foreach ($this->spot_colors as $name => $color) {
  8989. $this->_newobj();
  8990. $this->spot_colors[$name]['n'] = $this->n;
  8991. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  8992. $out .= ' /DeviceCMYK <<';
  8993. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  8994. $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  8995. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  8996. $out .= "\n".'endobj';
  8997. $this->_out($out);
  8998. }
  8999. }
  9000. /**
  9001. * Return XObjects Dictionary.
  9002. * @return string XObjects dictionary
  9003. * @protected
  9004. * @since 5.8.014 (2010-08-23)
  9005. */
  9006. protected function _getxobjectdict() {
  9007. $out = '';
  9008. foreach ($this->xobjects as $id => $objid) {
  9009. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  9010. }
  9011. return $out;
  9012. }
  9013. /**
  9014. * Output Resources Dictionary.
  9015. * @protected
  9016. */
  9017. protected function _putresourcedict() {
  9018. $out = $this->_getobj(2)."\n";
  9019. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  9020. $out .= ' /Font <<';
  9021. foreach ($this->fontkeys as $fontkey) {
  9022. $font = $this->getFontBuffer($fontkey);
  9023. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  9024. }
  9025. $out .= ' >>';
  9026. $out .= ' /XObject <<';
  9027. $out .= $this->_getxobjectdict();
  9028. $out .= ' >>';
  9029. // layers
  9030. if (!empty($this->pdflayers)) {
  9031. $out .= ' /Properties <<';
  9032. foreach ($this->pdflayers as $layer) {
  9033. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  9034. }
  9035. $out .= ' >>';
  9036. }
  9037. if (!$this->pdfa_mode) {
  9038. // transparency
  9039. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  9040. $out .= ' /ExtGState <<';
  9041. foreach ($this->extgstates as $k => $extgstate) {
  9042. if (isset($extgstate['name'])) {
  9043. $out .= ' /'.$extgstate['name'];
  9044. } else {
  9045. $out .= ' /GS'.$k;
  9046. }
  9047. $out .= ' '.$extgstate['n'].' 0 R';
  9048. }
  9049. $out .= ' >>';
  9050. }
  9051. if (isset($this->gradients) AND !empty($this->gradients)) {
  9052. $gp = '';
  9053. $gs = '';
  9054. foreach ($this->gradients as $id => $grad) {
  9055. // gradient patterns
  9056. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  9057. // gradient shadings
  9058. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  9059. }
  9060. $out .= ' /Pattern <<'.$gp.' >>';
  9061. $out .= ' /Shading <<'.$gs.' >>';
  9062. }
  9063. }
  9064. // spot colors
  9065. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  9066. $out .= ' /ColorSpace <<';
  9067. foreach ($this->spot_colors as $color) {
  9068. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  9069. }
  9070. $out .= ' >>';
  9071. }
  9072. $out .= ' >>';
  9073. $out .= "\n".'endobj';
  9074. $this->_out($out);
  9075. }
  9076. /**
  9077. * Output Resources.
  9078. * @protected
  9079. */
  9080. protected function _putresources() {
  9081. $this->_putextgstates();
  9082. $this->_putocg();
  9083. $this->_putfonts();
  9084. $this->_putimages();
  9085. $this->_putspotcolors();
  9086. $this->_putshaders();
  9087. $this->_putxobjects();
  9088. $this->_putresourcedict();
  9089. $this->_putdests();
  9090. $this->_putEmbeddedFiles();
  9091. $this->_putannotsobjs();
  9092. $this->_putjavascript();
  9093. $this->_putbookmarks();
  9094. $this->_putencryption();
  9095. }
  9096. /**
  9097. * Adds some Metadata information (Document Information Dictionary)
  9098. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  9099. * @return int object id
  9100. * @protected
  9101. */
  9102. protected function _putinfo() {
  9103. $oid = $this->_newobj();
  9104. $out = '<<';
  9105. // store current isunicode value
  9106. $prev_isunicode = $this->isunicode;
  9107. if ($this->docinfounicode) {
  9108. $this->isunicode = true;
  9109. }
  9110. if (!TCPDF_STATIC::empty_string($this->title)) {
  9111. // The document's title.
  9112. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  9113. }
  9114. if (!TCPDF_STATIC::empty_string($this->author)) {
  9115. // The name of the person who created the document.
  9116. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  9117. }
  9118. if (!TCPDF_STATIC::empty_string($this->subject)) {
  9119. // The subject of the document.
  9120. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  9121. }
  9122. if (!TCPDF_STATIC::empty_string($this->keywords)) {
  9123. // Keywords associated with the document.
  9124. $out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
  9125. }
  9126. if (!TCPDF_STATIC::empty_string($this->creator)) {
  9127. // 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.
  9128. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  9129. }
  9130. // restore previous isunicode value
  9131. $this->isunicode = $prev_isunicode;
  9132. // default producer
  9133. $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
  9134. // The date and time the document was created, in human-readable form
  9135. $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
  9136. // The date and time the document was most recently modified, in human-readable form
  9137. $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
  9138. // A name object indicating whether the document has been modified to include trapping information
  9139. $out .= ' /Trapped /False';
  9140. $out .= ' >>';
  9141. $out .= "\n".'endobj';
  9142. $this->_out($out);
  9143. return $oid;
  9144. }
  9145. /**
  9146. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  9147. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9148. * @param $xmp (string) Custom XMP data.
  9149. * @since 5.9.128 (2011-10-06)
  9150. * @public
  9151. */
  9152. public function setExtraXMP($xmp) {
  9153. $this->custom_xmp = $xmp;
  9154. }
  9155. /**
  9156. * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
  9157. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9158. * @param $xmp (string) Custom XMP RDF data.
  9159. * @since 6.3.0 (2019-09-19)
  9160. * @public
  9161. */
  9162. public function setExtraXMPRDF($xmp) {
  9163. $this->custom_xmp_rdf = $xmp;
  9164. }
  9165. /**
  9166. * Put XMP data object and return ID.
  9167. * @return (int) The object ID.
  9168. * @since 5.9.121 (2011-09-28)
  9169. * @protected
  9170. */
  9171. protected function _putXMP() {
  9172. $oid = $this->_newobj();
  9173. // store current isunicode value
  9174. $prev_isunicode = $this->isunicode;
  9175. $this->isunicode = true;
  9176. $prev_encrypted = $this->encrypted;
  9177. $this->encrypted = false;
  9178. // set XMP data
  9179. $xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  9180. $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";
  9181. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  9182. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  9183. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  9184. $xmp .= "\t\t\t".'<dc:title>'."\n";
  9185. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9186. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
  9187. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9188. $xmp .= "\t\t\t".'</dc:title>'."\n";
  9189. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  9190. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  9191. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
  9192. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  9193. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  9194. $xmp .= "\t\t\t".'<dc:description>'."\n";
  9195. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9196. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
  9197. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9198. $xmp .= "\t\t\t".'</dc:description>'."\n";
  9199. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  9200. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9201. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
  9202. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9203. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  9204. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9205. // convert doc creation date format
  9206. $dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
  9207. $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
  9208. $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
  9209. $doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
  9210. $doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
  9211. // convert doc modification date format
  9212. $dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
  9213. $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
  9214. $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
  9215. $docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
  9216. $docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
  9217. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  9218. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
  9219. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  9220. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
  9221. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
  9222. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9223. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  9224. $xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
  9225. $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
  9226. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9227. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  9228. $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);
  9229. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  9230. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  9231. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9232. if ($this->pdfa_mode) {
  9233. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  9234. $xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
  9235. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  9236. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9237. }
  9238. // XMP extension schemas
  9239. $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";
  9240. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  9241. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9242. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9243. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  9244. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  9245. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  9246. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9247. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9248. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9249. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9250. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Adobe PDF Schema</pdfaProperty:description>'."\n";
  9251. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9252. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9253. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9254. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9255. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9256. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9257. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9258. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  9259. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  9260. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  9261. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9262. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9263. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9264. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9265. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  9266. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9267. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9268. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9269. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9270. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9271. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9272. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9273. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  9274. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  9275. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  9276. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9277. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9278. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9279. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9280. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  9281. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  9282. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  9283. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9284. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9285. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9286. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  9287. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  9288. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9289. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9290. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9291. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9292. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  9293. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  9294. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9295. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9296. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9297. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9298. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9299. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9300. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  9301. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9302. $xmp .= $this->custom_xmp_rdf;
  9303. $xmp .= "\t".'</rdf:RDF>'."\n";
  9304. $xmp .= $this->custom_xmp;
  9305. $xmp .= '</x:xmpmeta>'."\n";
  9306. $xmp .= '<?xpacket end="w"?>';
  9307. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  9308. // restore previous isunicode value
  9309. $this->isunicode = $prev_isunicode;
  9310. $this->encrypted = $prev_encrypted;
  9311. $this->_out($out);
  9312. return $oid;
  9313. }
  9314. /**
  9315. * Output Catalog.
  9316. * @return int object id
  9317. * @protected
  9318. */
  9319. protected function _putcatalog() {
  9320. // put XMP
  9321. $xmpobj = $this->_putXMP();
  9322. // if required, add standard sRGB ICC colour profile
  9323. if ($this->pdfa_mode OR $this->force_srgb) {
  9324. $iccobj = $this->_newobj();
  9325. $icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
  9326. $filter = '';
  9327. if ($this->compress) {
  9328. $filter = ' /Filter /FlateDecode';
  9329. $icc = gzcompress($icc);
  9330. }
  9331. $icc = $this->_getrawstream($icc);
  9332. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  9333. }
  9334. // start catalog
  9335. $oid = $this->_newobj();
  9336. $out = '<< /Type /Catalog';
  9337. $out .= ' /Version /'.$this->PDFVersion;
  9338. //$out .= ' /Extensions <<>>';
  9339. $out .= ' /Pages 1 0 R';
  9340. //$out .= ' /PageLabels ' //...;
  9341. $out .= ' /Names <<';
  9342. if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
  9343. $out .= ' /JavaScript '.$this->n_js;
  9344. }
  9345. if (!empty($this->efnames)) {
  9346. $out .= ' /EmbeddedFiles <</Names [';
  9347. foreach ($this->efnames AS $fn => $fref) {
  9348. $out .= ' '.$this->_datastring($fn).' '.$fref;
  9349. }
  9350. $out .= ' ]>>';
  9351. }
  9352. $out .= ' >>';
  9353. if (!empty($this->dests)) {
  9354. $out .= ' /Dests '.($this->n_dests).' 0 R';
  9355. }
  9356. $out .= $this->_putviewerpreferences();
  9357. if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
  9358. $out .= ' /PageLayout /'.$this->LayoutMode;
  9359. }
  9360. if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
  9361. $out .= ' /PageMode /'.$this->PageMode;
  9362. }
  9363. if (count($this->outlines) > 0) {
  9364. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  9365. $out .= ' /PageMode /UseOutlines';
  9366. }
  9367. //$out .= ' /Threads []';
  9368. if ($this->ZoomMode == 'fullpage') {
  9369. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  9370. } elseif ($this->ZoomMode == 'fullwidth') {
  9371. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  9372. } elseif ($this->ZoomMode == 'real') {
  9373. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  9374. } elseif (!is_string($this->ZoomMode)) {
  9375. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
  9376. }
  9377. //$out .= ' /AA <<>>';
  9378. //$out .= ' /URI <<>>';
  9379. $out .= ' /Metadata '.$xmpobj.' 0 R';
  9380. //$out .= ' /StructTreeRoot <<>>';
  9381. //$out .= ' /MarkInfo <<>>';
  9382. if (isset($this->l['a_meta_language'])) {
  9383. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  9384. }
  9385. //$out .= ' /SpiderInfo <<>>';
  9386. // set OutputIntent to sRGB IEC61966-2.1 if required
  9387. if ($this->pdfa_mode OR $this->force_srgb) {
  9388. $out .= ' /OutputIntents [<<';
  9389. $out .= ' /Type /OutputIntent';
  9390. $out .= ' /S /GTS_PDFA1';
  9391. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9392. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9393. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  9394. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9395. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  9396. $out .= ' >>]';
  9397. }
  9398. //$out .= ' /PieceInfo <<>>';
  9399. if (!empty($this->pdflayers)) {
  9400. $lyrobjs = '';
  9401. $lyrobjs_off = '';
  9402. $lyrobjs_lock = '';
  9403. foreach ($this->pdflayers as $layer) {
  9404. $layer_obj_ref = ' '.$layer['objid'].' 0 R';
  9405. $lyrobjs .= $layer_obj_ref;
  9406. if ($layer['view'] === false) {
  9407. $lyrobjs_off .= $layer_obj_ref;
  9408. }
  9409. if ($layer['lock']) {
  9410. $lyrobjs_lock .= $layer_obj_ref;
  9411. }
  9412. }
  9413. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  9414. $out .= ' /D <<';
  9415. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  9416. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  9417. $out .= ' /BaseState /ON';
  9418. $out .= ' /OFF ['.$lyrobjs_off.']';
  9419. $out .= ' /Locked ['.$lyrobjs_lock.']';
  9420. $out .= ' /Intent /View';
  9421. $out .= ' /AS [';
  9422. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  9423. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  9424. $out .= ' ]';
  9425. $out .= ' /Order ['.$lyrobjs.']';
  9426. $out .= ' /ListMode /AllPages';
  9427. //$out .= ' /RBGroups ['..']';
  9428. //$out .= ' /Locked ['..']';
  9429. $out .= ' >>';
  9430. $out .= ' >>';
  9431. }
  9432. // AcroForm
  9433. if (!empty($this->form_obj_id)
  9434. OR ($this->sign AND isset($this->signature_data['cert_type']))
  9435. OR !empty($this->empty_signature_appearance)) {
  9436. $out .= ' /AcroForm <<';
  9437. $objrefs = '';
  9438. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9439. // set reference for signature object
  9440. $objrefs .= $this->sig_obj_id.' 0 R';
  9441. }
  9442. if (!empty($this->empty_signature_appearance)) {
  9443. foreach ($this->empty_signature_appearance as $esa) {
  9444. // set reference for empty signature objects
  9445. $objrefs .= ' '.$esa['objid'].' 0 R';
  9446. }
  9447. }
  9448. if (!empty($this->form_obj_id)) {
  9449. foreach($this->form_obj_id as $objid) {
  9450. $objrefs .= ' '.$objid.' 0 R';
  9451. }
  9452. }
  9453. $out .= ' /Fields ['.$objrefs.']';
  9454. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  9455. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  9456. $out .= ' /NeedAppearances false';
  9457. }
  9458. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9459. if ($this->signature_data['cert_type'] > 0) {
  9460. $out .= ' /SigFlags 3';
  9461. } else {
  9462. $out .= ' /SigFlags 1';
  9463. }
  9464. }
  9465. //$out .= ' /CO ';
  9466. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  9467. $out .= ' /DR <<';
  9468. $out .= ' /Font <<';
  9469. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  9470. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  9471. }
  9472. $out .= ' >> >>';
  9473. }
  9474. $font = $this->getFontBuffer('helvetica');
  9475. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  9476. $out .= ' /Q '.(($this->rtl)?'2':'0');
  9477. //$out .= ' /XFA ';
  9478. $out .= ' >>';
  9479. // signatures
  9480. if ($this->sign AND isset($this->signature_data['cert_type'])
  9481. AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
  9482. if ($this->signature_data['cert_type'] > 0) {
  9483. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  9484. } else {
  9485. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  9486. }
  9487. }
  9488. }
  9489. //$out .= ' /Legal <<>>';
  9490. //$out .= ' /Requirements []';
  9491. //$out .= ' /Collection <<>>';
  9492. //$out .= ' /NeedsRendering true';
  9493. $out .= ' >>';
  9494. $out .= "\n".'endobj';
  9495. $this->_out($out);
  9496. return $oid;
  9497. }
  9498. /**
  9499. * Output viewer preferences.
  9500. * @return string for viewer preferences
  9501. * @author Nicola asuni
  9502. * @since 3.1.000 (2008-06-09)
  9503. * @protected
  9504. */
  9505. protected function _putviewerpreferences() {
  9506. $vp = $this->viewer_preferences;
  9507. $out = ' /ViewerPreferences <<';
  9508. if ($this->rtl) {
  9509. $out .= ' /Direction /R2L';
  9510. } else {
  9511. $out .= ' /Direction /L2R';
  9512. }
  9513. if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
  9514. $out .= ' /HideToolbar true';
  9515. }
  9516. if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
  9517. $out .= ' /HideMenubar true';
  9518. }
  9519. if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
  9520. $out .= ' /HideWindowUI true';
  9521. }
  9522. if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
  9523. $out .= ' /FitWindow true';
  9524. }
  9525. if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
  9526. $out .= ' /CenterWindow true';
  9527. }
  9528. if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
  9529. $out .= ' /DisplayDocTitle true';
  9530. }
  9531. if (isset($vp['NonFullScreenPageMode'])) {
  9532. $out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
  9533. }
  9534. if (isset($vp['ViewArea'])) {
  9535. $out .= ' /ViewArea /'.$vp['ViewArea'];
  9536. }
  9537. if (isset($vp['ViewClip'])) {
  9538. $out .= ' /ViewClip /'.$vp['ViewClip'];
  9539. }
  9540. if (isset($vp['PrintArea'])) {
  9541. $out .= ' /PrintArea /'.$vp['PrintArea'];
  9542. }
  9543. if (isset($vp['PrintClip'])) {
  9544. $out .= ' /PrintClip /'.$vp['PrintClip'];
  9545. }
  9546. if (isset($vp['PrintScaling'])) {
  9547. $out .= ' /PrintScaling /'.$vp['PrintScaling'];
  9548. }
  9549. if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
  9550. $out .= ' /Duplex /'.$vp['Duplex'];
  9551. }
  9552. if (isset($vp['PickTrayByPDFSize'])) {
  9553. if ($vp['PickTrayByPDFSize']) {
  9554. $out .= ' /PickTrayByPDFSize true';
  9555. } else {
  9556. $out .= ' /PickTrayByPDFSize false';
  9557. }
  9558. }
  9559. if (isset($vp['PrintPageRange'])) {
  9560. $PrintPageRangeNum = '';
  9561. foreach ($vp['PrintPageRange'] as $k => $v) {
  9562. $PrintPageRangeNum .= ' '.($v - 1).'';
  9563. }
  9564. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  9565. }
  9566. if (isset($vp['NumCopies'])) {
  9567. $out .= ' /NumCopies '.intval($vp['NumCopies']);
  9568. }
  9569. $out .= ' >>';
  9570. return $out;
  9571. }
  9572. /**
  9573. * Output PDF File Header (7.5.2).
  9574. * @protected
  9575. */
  9576. protected function _putheader() {
  9577. $this->_out('%PDF-'.$this->PDFVersion);
  9578. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  9579. }
  9580. /**
  9581. * Output end of document (EOF).
  9582. * @protected
  9583. */
  9584. protected function _enddoc() {
  9585. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  9586. // save subset chars of the previous font
  9587. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  9588. }
  9589. $this->state = 1;
  9590. $this->_putheader();
  9591. $this->_putpages();
  9592. $this->_putresources();
  9593. // empty signature fields
  9594. if (!empty($this->empty_signature_appearance)) {
  9595. foreach ($this->empty_signature_appearance as $key => $esa) {
  9596. // widget annotation for empty signature
  9597. $out = $this->_getobj($esa['objid'])."\n";
  9598. $out .= '<< /Type /Annot';
  9599. $out .= ' /Subtype /Widget';
  9600. $out .= ' /Rect ['.$esa['rect'].']';
  9601. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  9602. $out .= ' /F 4';
  9603. $out .= ' /FT /Sig';
  9604. $signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
  9605. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  9606. $out .= ' /Ff 0';
  9607. $out .= ' >>';
  9608. $out .= "\n".'endobj';
  9609. $this->_out($out);
  9610. }
  9611. }
  9612. // Signature
  9613. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9614. // widget annotation for signature
  9615. $out = $this->_getobj($this->sig_obj_id)."\n";
  9616. $out .= '<< /Type /Annot';
  9617. $out .= ' /Subtype /Widget';
  9618. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  9619. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  9620. $out .= ' /F 4';
  9621. $out .= ' /FT /Sig';
  9622. $out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
  9623. $out .= ' /Ff 0';
  9624. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  9625. $out .= ' >>';
  9626. $out .= "\n".'endobj';
  9627. $this->_out($out);
  9628. // signature
  9629. $this->_putsignature();
  9630. }
  9631. // Info
  9632. $objid_info = $this->_putinfo();
  9633. // Catalog
  9634. $objid_catalog = $this->_putcatalog();
  9635. // Cross-ref
  9636. $o = $this->bufferlen;
  9637. // XREF section
  9638. $this->_out('xref');
  9639. $this->_out('0 '.($this->n + 1));
  9640. $this->_out('0000000000 65535 f ');
  9641. $freegen = ($this->n + 2);
  9642. for ($i=1; $i <= $this->n; ++$i) {
  9643. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  9644. $this->_out(sprintf('0000000000 %05d f ', $freegen));
  9645. ++$freegen;
  9646. } else {
  9647. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  9648. }
  9649. }
  9650. // TRAILER
  9651. $out = 'trailer'."\n";
  9652. $out .= '<<';
  9653. $out .= ' /Size '.($this->n + 1);
  9654. $out .= ' /Root '.$objid_catalog.' 0 R';
  9655. $out .= ' /Info '.$objid_info.' 0 R';
  9656. if ($this->encrypted) {
  9657. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  9658. }
  9659. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  9660. $out .= ' >>';
  9661. $this->_out($out);
  9662. $this->_out('startxref');
  9663. $this->_out($o);
  9664. $this->_out('%%EOF');
  9665. $this->state = 3; // end-of-doc
  9666. }
  9667. /**
  9668. * Initialize a new page.
  9669. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  9670. * @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().
  9671. * @protected
  9672. * @see getPageSizeFromFormat(), setPageFormat()
  9673. */
  9674. protected function _beginpage($orientation='', $format='') {
  9675. ++$this->page;
  9676. $this->pageobjects[$this->page] = array();
  9677. $this->setPageBuffer($this->page, '');
  9678. // initialize array for graphics tranformation positions inside a page buffer
  9679. $this->transfmrk[$this->page] = array();
  9680. $this->state = 2;
  9681. if (TCPDF_STATIC::empty_string($orientation)) {
  9682. if (isset($this->CurOrientation)) {
  9683. $orientation = $this->CurOrientation;
  9684. } elseif ($this->fwPt > $this->fhPt) {
  9685. // landscape
  9686. $orientation = 'L';
  9687. } else {
  9688. // portrait
  9689. $orientation = 'P';
  9690. }
  9691. }
  9692. if (TCPDF_STATIC::empty_string($format)) {
  9693. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  9694. $this->setPageOrientation($orientation);
  9695. } else {
  9696. $this->setPageFormat($format, $orientation);
  9697. }
  9698. if ($this->rtl) {
  9699. $this->x = $this->w - $this->rMargin;
  9700. } else {
  9701. $this->x = $this->lMargin;
  9702. }
  9703. $this->y = $this->tMargin;
  9704. if (isset($this->newpagegroup[$this->page])) {
  9705. // start a new group
  9706. $this->currpagegroup = $this->newpagegroup[$this->page];
  9707. $this->pagegroups[$this->currpagegroup] = 1;
  9708. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  9709. ++$this->pagegroups[$this->currpagegroup];
  9710. }
  9711. }
  9712. /**
  9713. * Mark end of page.
  9714. * @protected
  9715. */
  9716. protected function _endpage() {
  9717. $this->setVisibility('all');
  9718. $this->state = 1;
  9719. }
  9720. /**
  9721. * Begin a new object and return the object number.
  9722. * @return int object number
  9723. * @protected
  9724. */
  9725. protected function _newobj() {
  9726. $this->_out($this->_getobj());
  9727. return $this->n;
  9728. }
  9729. /**
  9730. * Return the starting object string for the selected object ID.
  9731. * @param $objid (int) Object ID (leave empty to get a new ID).
  9732. * @return string the starting object string
  9733. * @protected
  9734. * @since 5.8.009 (2010-08-20)
  9735. */
  9736. protected function _getobj($objid='') {
  9737. if ($objid === '') {
  9738. ++$this->n;
  9739. $objid = $this->n;
  9740. }
  9741. $this->offsets[$objid] = $this->bufferlen;
  9742. $this->pageobjects[$this->page][] = $objid;
  9743. return $objid.' 0 obj';
  9744. }
  9745. /**
  9746. * Underline text.
  9747. * @param $x (int) X coordinate
  9748. * @param $y (int) Y coordinate
  9749. * @param $txt (string) text to underline
  9750. * @protected
  9751. */
  9752. protected function _dounderline($x, $y, $txt) {
  9753. $w = $this->GetStringWidth($txt);
  9754. return $this->_dounderlinew($x, $y, $w);
  9755. }
  9756. /**
  9757. * Underline for rectangular text area.
  9758. * @param $x (int) X coordinate
  9759. * @param $y (int) Y coordinate
  9760. * @param $w (int) width to underline
  9761. * @protected
  9762. * @since 4.8.008 (2009-09-29)
  9763. */
  9764. protected function _dounderlinew($x, $y, $w) {
  9765. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9766. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  9767. }
  9768. /**
  9769. * Line through text.
  9770. * @param $x (int) X coordinate
  9771. * @param $y (int) Y coordinate
  9772. * @param $txt (string) text to linethrough
  9773. * @protected
  9774. */
  9775. protected function _dolinethrough($x, $y, $txt) {
  9776. $w = $this->GetStringWidth($txt);
  9777. return $this->_dolinethroughw($x, $y, $w);
  9778. }
  9779. /**
  9780. * Line through for rectangular text area.
  9781. * @param $x (int) X coordinate
  9782. * @param $y (int) Y coordinate
  9783. * @param $w (int) line length (width)
  9784. * @protected
  9785. * @since 4.9.008 (2009-09-29)
  9786. */
  9787. protected function _dolinethroughw($x, $y, $w) {
  9788. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9789. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  9790. }
  9791. /**
  9792. * Overline text.
  9793. * @param $x (int) X coordinate
  9794. * @param $y (int) Y coordinate
  9795. * @param $txt (string) text to overline
  9796. * @protected
  9797. * @since 4.9.015 (2010-04-19)
  9798. */
  9799. protected function _dooverline($x, $y, $txt) {
  9800. $w = $this->GetStringWidth($txt);
  9801. return $this->_dooverlinew($x, $y, $w);
  9802. }
  9803. /**
  9804. * Overline for rectangular text area.
  9805. * @param $x (int) X coordinate
  9806. * @param $y (int) Y coordinate
  9807. * @param $w (int) width to overline
  9808. * @protected
  9809. * @since 4.9.015 (2010-04-19)
  9810. */
  9811. protected function _dooverlinew($x, $y, $w) {
  9812. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9813. return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  9814. }
  9815. /**
  9816. * Format a data string for meta information
  9817. * @param $s (string) data string to escape.
  9818. * @param $n (int) object ID
  9819. * @return string escaped string.
  9820. * @protected
  9821. */
  9822. protected function _datastring($s, $n=0) {
  9823. if ($n == 0) {
  9824. $n = $this->n;
  9825. }
  9826. $s = $this->_encrypt_data($n, $s);
  9827. return '('. TCPDF_STATIC::_escape($s).')';
  9828. }
  9829. /**
  9830. * Set the document creation timestamp
  9831. * @param $time (mixed) Document creation timestamp in seconds or date-time string.
  9832. * @public
  9833. * @since 5.9.152 (2012-03-23)
  9834. */
  9835. public function setDocCreationTimestamp($time) {
  9836. if (is_string($time)) {
  9837. $time = TCPDF_STATIC::getTimestamp($time);
  9838. }
  9839. $this->doc_creation_timestamp = intval($time);
  9840. }
  9841. /**
  9842. * Set the document modification timestamp
  9843. * @param $time (mixed) Document modification timestamp in seconds or date-time string.
  9844. * @public
  9845. * @since 5.9.152 (2012-03-23)
  9846. */
  9847. public function setDocModificationTimestamp($time) {
  9848. if (is_string($time)) {
  9849. $time = TCPDF_STATIC::getTimestamp($time);
  9850. }
  9851. $this->doc_modification_timestamp = intval($time);
  9852. }
  9853. /**
  9854. * Returns document creation timestamp in seconds.
  9855. * @return (int) Creation timestamp in seconds.
  9856. * @public
  9857. * @since 5.9.152 (2012-03-23)
  9858. */
  9859. public function getDocCreationTimestamp() {
  9860. return $this->doc_creation_timestamp;
  9861. }
  9862. /**
  9863. * Returns document modification timestamp in seconds.
  9864. * @return (int) Modfication timestamp in seconds.
  9865. * @public
  9866. * @since 5.9.152 (2012-03-23)
  9867. */
  9868. public function getDocModificationTimestamp() {
  9869. return $this->doc_modification_timestamp;
  9870. }
  9871. /**
  9872. * Returns a formatted date for meta information
  9873. * @param $n (int) Object ID.
  9874. * @param $timestamp (int) Timestamp to convert.
  9875. * @return string escaped date string.
  9876. * @protected
  9877. * @since 4.6.028 (2009-08-25)
  9878. */
  9879. protected function _datestring($n=0, $timestamp=0) {
  9880. if ((empty($timestamp)) OR ($timestamp < 0)) {
  9881. $timestamp = $this->doc_creation_timestamp;
  9882. }
  9883. return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
  9884. }
  9885. /**
  9886. * Format a text string for meta information
  9887. * @param $s (string) string to escape.
  9888. * @param $n (int) object ID
  9889. * @return string escaped string.
  9890. * @protected
  9891. */
  9892. protected function _textstring($s, $n=0) {
  9893. if ($this->isunicode) {
  9894. //Convert string to UTF-16BE
  9895. $s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
  9896. }
  9897. return $this->_datastring($s, $n);
  9898. }
  9899. /**
  9900. * get raw output stream.
  9901. * @param $s (string) string to output.
  9902. * @param $n (int) object reference for encryption mode
  9903. * @protected
  9904. * @author Nicola Asuni
  9905. * @since 5.5.000 (2010-06-22)
  9906. */
  9907. protected function _getrawstream($s, $n=0) {
  9908. if ($n <= 0) {
  9909. // default to current object
  9910. $n = $this->n;
  9911. }
  9912. return $this->_encrypt_data($n, $s);
  9913. }
  9914. /**
  9915. * Output a string to the document.
  9916. * @param $s (string) string to output.
  9917. * @protected
  9918. */
  9919. protected function _out($s) {
  9920. if ($this->state == 2) {
  9921. if ($this->inxobj) {
  9922. // we are inside an XObject template
  9923. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  9924. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  9925. // puts data before page footer
  9926. $pagebuff = $this->getPageBuffer($this->page);
  9927. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  9928. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  9929. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  9930. // update footer position
  9931. $this->footerpos[$this->page] += strlen($s."\n");
  9932. } else {
  9933. // set page data
  9934. $this->setPageBuffer($this->page, $s."\n", true);
  9935. }
  9936. } elseif ($this->state > 0) {
  9937. // set general data
  9938. $this->setBuffer($s."\n");
  9939. }
  9940. }
  9941. /**
  9942. * Set header font.
  9943. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9944. * @public
  9945. * @since 1.1
  9946. */
  9947. public function setHeaderFont($font) {
  9948. $this->header_font = $font;
  9949. }
  9950. /**
  9951. * Get header font.
  9952. * @return array() Array describing the basic font parameters: (family, style, size).
  9953. * @public
  9954. * @since 4.0.012 (2008-07-24)
  9955. */
  9956. public function getHeaderFont() {
  9957. return $this->header_font;
  9958. }
  9959. /**
  9960. * Set footer font.
  9961. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9962. * @public
  9963. * @since 1.1
  9964. */
  9965. public function setFooterFont($font) {
  9966. $this->footer_font = $font;
  9967. }
  9968. /**
  9969. * Get Footer font.
  9970. * @return array() Array describing the basic font parameters: (family, style, size).
  9971. * @public
  9972. * @since 4.0.012 (2008-07-24)
  9973. */
  9974. public function getFooterFont() {
  9975. return $this->footer_font;
  9976. }
  9977. /**
  9978. * Set language array.
  9979. * @param $language (array)
  9980. * @public
  9981. * @since 1.1
  9982. */
  9983. public function setLanguageArray($language) {
  9984. $this->l = $language;
  9985. if (isset($this->l['a_meta_dir'])) {
  9986. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  9987. } else {
  9988. $this->rtl = false;
  9989. }
  9990. }
  9991. /**
  9992. * Returns the PDF data.
  9993. * @public
  9994. */
  9995. public function getPDFData() {
  9996. if ($this->state < 3) {
  9997. $this->Close();
  9998. }
  9999. return $this->buffer;
  10000. }
  10001. /**
  10002. * Output anchor link.
  10003. * @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;)
  10004. * @param $name (string) link name
  10005. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  10006. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  10007. * @param $color (array) array of RGB text color
  10008. * @param $style (string) font style (U, D, B, I)
  10009. * @param $firstblock (boolean) if true the string is the starting of a line.
  10010. * @return the number of cells used or the remaining text if $firstline = true;
  10011. * @public
  10012. */
  10013. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  10014. if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
  10015. // convert url to internal link
  10016. $lnkdata = explode(',', $url);
  10017. if (isset($lnkdata[0]) ) {
  10018. $page = substr($lnkdata[0], 1);
  10019. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  10020. $lnky = floatval($lnkdata[1]);
  10021. } else {
  10022. $lnky = 0;
  10023. }
  10024. $url = $this->AddLink();
  10025. $this->SetLink($url, $lnky, $page);
  10026. }
  10027. }
  10028. // store current settings
  10029. $prevcolor = $this->fgcolor;
  10030. $prevstyle = $this->FontStyle;
  10031. if (empty($color)) {
  10032. $this->SetTextColorArray($this->htmlLinkColorArray);
  10033. } else {
  10034. $this->SetTextColorArray($color);
  10035. }
  10036. if ($style == -1) {
  10037. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  10038. } else {
  10039. $this->SetFont('', $this->FontStyle.$style);
  10040. }
  10041. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  10042. // restore settings
  10043. $this->SetFont('', $prevstyle);
  10044. $this->SetTextColorArray($prevcolor);
  10045. return $ret;
  10046. }
  10047. /**
  10048. * Converts pixels to User's Units.
  10049. * @param $px (int) pixels
  10050. * @return float value in user's unit
  10051. * @public
  10052. * @see setImageScale(), getImageScale()
  10053. */
  10054. public function pixelsToUnits($px) {
  10055. return ($px / ($this->imgscale * $this->k));
  10056. }
  10057. /**
  10058. * Reverse function for htmlentities.
  10059. * Convert entities in UTF-8.
  10060. * @param $text_to_convert (string) Text to convert.
  10061. * @return string converted text string
  10062. * @public
  10063. */
  10064. public function unhtmlentities($text_to_convert) {
  10065. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  10066. }
  10067. // ENCRYPTION METHODS ----------------------------------
  10068. /**
  10069. * Compute encryption key depending on object number where the encrypted data is stored.
  10070. * This is used for all strings and streams without crypt filter specifier.
  10071. * @param $n (int) object number
  10072. * @return int object key
  10073. * @protected
  10074. * @author Nicola Asuni
  10075. * @since 2.0.000 (2008-01-02)
  10076. */
  10077. protected function _objectkey($n) {
  10078. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  10079. if ($this->encryptdata['mode'] == 2) { // AES-128
  10080. // AES padding
  10081. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  10082. }
  10083. $objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  10084. $objkey = substr($objkey, 0, 16);
  10085. return $objkey;
  10086. }
  10087. /**
  10088. * Encrypt the input string.
  10089. * @param $n (int) object number
  10090. * @param $s (string) data string to encrypt
  10091. * @return encrypted string
  10092. * @protected
  10093. * @author Nicola Asuni
  10094. * @since 5.0.005 (2010-05-11)
  10095. */
  10096. protected function _encrypt_data($n, $s) {
  10097. if (!$this->encrypted) {
  10098. return $s;
  10099. }
  10100. switch ($this->encryptdata['mode']) {
  10101. case 0: // RC4-40
  10102. case 1: { // RC4-128
  10103. $s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
  10104. break;
  10105. }
  10106. case 2: { // AES-128
  10107. $s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
  10108. break;
  10109. }
  10110. case 3: { // AES-256
  10111. $s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
  10112. break;
  10113. }
  10114. }
  10115. return $s;
  10116. }
  10117. /**
  10118. * Put encryption on PDF document.
  10119. * @protected
  10120. * @author Nicola Asuni
  10121. * @since 2.0.000 (2008-01-02)
  10122. */
  10123. protected function _putencryption() {
  10124. if (!$this->encrypted) {
  10125. return;
  10126. }
  10127. $this->encryptdata['objid'] = $this->_newobj();
  10128. $out = '<<';
  10129. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  10130. $this->encryptdata['Filter'] = 'Standard';
  10131. }
  10132. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  10133. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  10134. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  10135. }
  10136. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  10137. $this->encryptdata['V'] = 1;
  10138. }
  10139. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  10140. $out .= ' /V '.$this->encryptdata['V'];
  10141. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  10142. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  10143. $out .= ' /Length '.$this->encryptdata['Length'];
  10144. } else {
  10145. $out .= ' /Length 40';
  10146. }
  10147. if ($this->encryptdata['V'] >= 4) {
  10148. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  10149. $this->encryptdata['StmF'] = 'Identity';
  10150. }
  10151. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  10152. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10153. $this->encryptdata['StrF'] = 'Identity';
  10154. }
  10155. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  10156. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  10157. $out .= ' /CF <<';
  10158. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  10159. $out .= ' /Type /CryptFilter';
  10160. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  10161. // The method used
  10162. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  10163. if ($this->encryptdata['pubkey']) {
  10164. $out .= ' /Recipients [';
  10165. foreach ($this->encryptdata['Recipients'] as $rec) {
  10166. $out .= ' <'.$rec.'>';
  10167. }
  10168. $out .= ' ]';
  10169. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  10170. $out .= ' /EncryptMetadata false';
  10171. } else {
  10172. $out .= ' /EncryptMetadata true';
  10173. }
  10174. }
  10175. } else {
  10176. $out .= ' /CFM /None';
  10177. }
  10178. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  10179. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  10180. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  10181. } else {
  10182. $out .= ' /AuthEvent /DocOpen';
  10183. }
  10184. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  10185. // The bit length of the encryption key.
  10186. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  10187. }
  10188. $out .= ' >> >>';
  10189. }
  10190. // The name of the crypt filter that shall be used by default when decrypting streams.
  10191. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  10192. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10193. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  10194. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  10195. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  10196. $out .= ' /EFF /'.$this->encryptdata[''];
  10197. }
  10198. }
  10199. // Additional encryption dictionary entries for the standard security handler
  10200. if ($this->encryptdata['pubkey']) {
  10201. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  10202. $out .= ' /Recipients [';
  10203. foreach ($this->encryptdata['Recipients'] as $rec) {
  10204. $out .= ' <'.$rec.'>';
  10205. }
  10206. $out .= ' ]';
  10207. }
  10208. } else {
  10209. $out .= ' /R';
  10210. if ($this->encryptdata['V'] == 5) { // AES-256
  10211. $out .= ' 5';
  10212. $out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
  10213. $out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
  10214. $out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
  10215. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  10216. $out .= ' 4';
  10217. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  10218. $out .= ' 2';
  10219. } else { // RC-128
  10220. $out .= ' 3';
  10221. }
  10222. $out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
  10223. $out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
  10224. $out .= ' /P '.$this->encryptdata['P'];
  10225. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  10226. $out .= ' /EncryptMetadata false';
  10227. } else {
  10228. $out .= ' /EncryptMetadata true';
  10229. }
  10230. }
  10231. $out .= ' >>';
  10232. $out .= "\n".'endobj';
  10233. $this->_out($out);
  10234. }
  10235. /**
  10236. * Compute U value (used for encryption)
  10237. * @return string U value
  10238. * @protected
  10239. * @since 2.0.000 (2008-01-02)
  10240. * @author Nicola Asuni
  10241. */
  10242. protected function _Uvalue() {
  10243. if ($this->encryptdata['mode'] == 0) { // RC4-40
  10244. return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
  10245. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  10246. $tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
  10247. $enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
  10248. $len = strlen($tmp);
  10249. for ($i = 1; $i <= 19; ++$i) {
  10250. $ek = '';
  10251. for ($j = 0; $j < $len; ++$j) {
  10252. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  10253. }
  10254. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10255. }
  10256. $enc .= str_repeat("\x00", 16);
  10257. return substr($enc, 0, 32);
  10258. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10259. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10260. // User Validation Salt
  10261. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  10262. // User Key Salt
  10263. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  10264. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  10265. }
  10266. }
  10267. /**
  10268. * Compute UE value (used for encryption)
  10269. * @return string UE value
  10270. * @protected
  10271. * @since 5.9.006 (2010-10-19)
  10272. * @author Nicola Asuni
  10273. */
  10274. protected function _UEvalue() {
  10275. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  10276. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10277. }
  10278. /**
  10279. * Compute O value (used for encryption)
  10280. * @return string O value
  10281. * @protected
  10282. * @since 2.0.000 (2008-01-02)
  10283. * @author Nicola Asuni
  10284. */
  10285. protected function _Ovalue() {
  10286. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  10287. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
  10288. if ($this->encryptdata['mode'] > 0) {
  10289. for ($i = 0; $i < 50; ++$i) {
  10290. $tmp = TCPDF_STATIC::_md5_16($tmp);
  10291. }
  10292. }
  10293. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  10294. $enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
  10295. if ($this->encryptdata['mode'] > 0) {
  10296. $len = strlen($owner_key);
  10297. for ($i = 1; $i <= 19; ++$i) {
  10298. $ek = '';
  10299. for ($j = 0; $j < $len; ++$j) {
  10300. $ek .= chr(ord($owner_key[$j]) ^ $i);
  10301. }
  10302. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10303. }
  10304. }
  10305. return $enc;
  10306. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10307. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10308. // Owner Validation Salt
  10309. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  10310. // Owner Key Salt
  10311. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  10312. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  10313. }
  10314. }
  10315. /**
  10316. * Compute OE value (used for encryption)
  10317. * @return string OE value
  10318. * @protected
  10319. * @since 5.9.006 (2010-10-19)
  10320. * @author Nicola Asuni
  10321. */
  10322. protected function _OEvalue() {
  10323. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  10324. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10325. }
  10326. /**
  10327. * Convert password for AES-256 encryption mode
  10328. * @param $password (string) password
  10329. * @return string password
  10330. * @protected
  10331. * @since 5.9.006 (2010-10-19)
  10332. * @author Nicola Asuni
  10333. */
  10334. protected function _fixAES256Password($password) {
  10335. $psw = ''; // password to be returned
  10336. $psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
  10337. foreach ($psw_array as $c) {
  10338. $psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
  10339. }
  10340. return substr($psw, 0, 127);
  10341. }
  10342. /**
  10343. * Compute encryption key
  10344. * @protected
  10345. * @since 2.0.000 (2008-01-02)
  10346. * @author Nicola Asuni
  10347. */
  10348. protected function _generateencryptionkey() {
  10349. $keybytelen = ($this->encryptdata['Length'] / 8);
  10350. if (!$this->encryptdata['pubkey']) { // standard mode
  10351. if ($this->encryptdata['mode'] == 3) { // AES-256
  10352. // generate 256 bit random key
  10353. $this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
  10354. // truncate passwords
  10355. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  10356. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  10357. // Compute U value
  10358. $this->encryptdata['U'] = $this->_Uvalue();
  10359. // Compute UE value
  10360. $this->encryptdata['UE'] = $this->_UEvalue();
  10361. // Compute O value
  10362. $this->encryptdata['O'] = $this->_Ovalue();
  10363. // Compute OE value
  10364. $this->encryptdata['OE'] = $this->_OEvalue();
  10365. // Compute P value
  10366. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10367. // Computing the encryption dictionary's Perms (permissions) value
  10368. $perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  10369. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  10370. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  10371. $perms .= 'F';
  10372. } else {
  10373. $perms .= 'T';
  10374. }
  10375. $perms .= 'adb'; // bytes 9-11
  10376. $perms .= 'nick'; // bytes 12-15
  10377. $this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
  10378. } else { // RC4-40, RC4-128, AES-128
  10379. // Pad passwords
  10380. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10381. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10382. // Compute O value
  10383. $this->encryptdata['O'] = $this->_Ovalue();
  10384. // get default permissions (reverse byte order)
  10385. $permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
  10386. // Compute encryption key
  10387. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  10388. if ($this->encryptdata['mode'] > 0) {
  10389. for ($i = 0; $i < 50; ++$i) {
  10390. $tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
  10391. }
  10392. }
  10393. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  10394. // Compute U value
  10395. $this->encryptdata['U'] = $this->_Uvalue();
  10396. // Compute P value
  10397. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10398. }
  10399. } else { // Public-Key mode
  10400. // random 20-byte seed
  10401. $seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
  10402. $recipient_bytes = '';
  10403. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  10404. // for each public certificate
  10405. if (isset($pubkey['p'])) {
  10406. $pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  10407. } else {
  10408. $pkprotection = $this->encryptdata['protection'];
  10409. }
  10410. // get default permissions (reverse byte order)
  10411. $pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
  10412. // envelope data
  10413. $envelope = $seed.$pkpermissions;
  10414. // write the envelope data to a temporary file
  10415. $tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
  10416. $f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
  10417. if (!$f) {
  10418. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  10419. }
  10420. $envelope_length = strlen($envelope);
  10421. fwrite($f, $envelope, $envelope_length);
  10422. fclose($f);
  10423. $tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
  10424. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  10425. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  10426. }
  10427. // read encryption signature
  10428. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  10429. // extract signature
  10430. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  10431. $tmparr = explode("\n\n", $signature);
  10432. $signature = trim($tmparr[1]);
  10433. unset($tmparr);
  10434. // decode signature
  10435. $signature = base64_decode($signature);
  10436. // convert signature to hex
  10437. $hexsignature = current(unpack('H*', $signature));
  10438. // store signature on recipients array
  10439. $this->encryptdata['Recipients'][] = $hexsignature;
  10440. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  10441. $recipient_bytes .= $signature;
  10442. }
  10443. // calculate encryption key
  10444. if ($this->encryptdata['mode'] == 3) { // AES-256
  10445. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  10446. } else { // RC4-40, RC4-128, AES-128
  10447. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  10448. }
  10449. }
  10450. }
  10451. /**
  10452. * Set document protection
  10453. * Remark: the protection against modification is for people who have the full Acrobat product.
  10454. * 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.
  10455. * 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.
  10456. * @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>
  10457. * @param $user_pass (String) user password. Empty by default.
  10458. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  10459. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  10460. * @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')))
  10461. * @public
  10462. * @since 2.0.000 (2008-01-02)
  10463. * @author Nicola Asuni
  10464. */
  10465. 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) {
  10466. if ($this->pdfa_mode) {
  10467. // encryption is not allowed in PDF/A mode
  10468. return;
  10469. }
  10470. $this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
  10471. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  10472. // public-key mode
  10473. $this->encryptdata['pubkeys'] = $pubkeys;
  10474. if ($mode == 0) {
  10475. // public-Key Security requires at least 128 bit
  10476. $mode = 1;
  10477. }
  10478. if (!function_exists('openssl_pkcs7_encrypt')) {
  10479. $this->Error('Public-Key Security requires openssl library.');
  10480. }
  10481. // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  10482. $this->encryptdata['pubkey'] = true;
  10483. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  10484. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  10485. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  10486. } else {
  10487. // standard mode (password mode)
  10488. $this->encryptdata['pubkey'] = false;
  10489. $this->encryptdata['Filter'] = 'Standard';
  10490. $this->encryptdata['StmF'] = 'StdCF';
  10491. $this->encryptdata['StrF'] = 'StdCF';
  10492. }
  10493. if ($mode > 1) { // AES
  10494. if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
  10495. $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
  10496. }
  10497. if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
  10498. $this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
  10499. }
  10500. if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  10501. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  10502. }
  10503. if (($mode == 3) AND !function_exists('hash')) {
  10504. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  10505. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  10506. }
  10507. }
  10508. if ($owner_pass === null) {
  10509. $owner_pass = md5(TCPDF_STATIC::getRandomSeed());
  10510. }
  10511. $this->encryptdata['user_password'] = $user_pass;
  10512. $this->encryptdata['owner_password'] = $owner_pass;
  10513. $this->encryptdata['mode'] = $mode;
  10514. switch ($mode) {
  10515. case 0: { // RC4 40 bit
  10516. $this->encryptdata['V'] = 1;
  10517. $this->encryptdata['Length'] = 40;
  10518. $this->encryptdata['CF']['CFM'] = 'V2';
  10519. break;
  10520. }
  10521. case 1: { // RC4 128 bit
  10522. $this->encryptdata['V'] = 2;
  10523. $this->encryptdata['Length'] = 128;
  10524. $this->encryptdata['CF']['CFM'] = 'V2';
  10525. if ($this->encryptdata['pubkey']) {
  10526. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  10527. $this->encryptdata['Recipients'] = array();
  10528. }
  10529. break;
  10530. }
  10531. case 2: { // AES 128 bit
  10532. $this->encryptdata['V'] = 4;
  10533. $this->encryptdata['Length'] = 128;
  10534. $this->encryptdata['CF']['CFM'] = 'AESV2';
  10535. $this->encryptdata['CF']['Length'] = 128;
  10536. if ($this->encryptdata['pubkey']) {
  10537. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10538. $this->encryptdata['Recipients'] = array();
  10539. }
  10540. break;
  10541. }
  10542. case 3: { // AES 256 bit
  10543. $this->encryptdata['V'] = 5;
  10544. $this->encryptdata['Length'] = 256;
  10545. $this->encryptdata['CF']['CFM'] = 'AESV3';
  10546. $this->encryptdata['CF']['Length'] = 256;
  10547. if ($this->encryptdata['pubkey']) {
  10548. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10549. $this->encryptdata['Recipients'] = array();
  10550. }
  10551. break;
  10552. }
  10553. }
  10554. $this->encrypted = true;
  10555. $this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
  10556. $this->_generateencryptionkey();
  10557. }
  10558. // END OF ENCRYPTION FUNCTIONS -------------------------
  10559. // START TRANSFORMATIONS SECTION -----------------------
  10560. /**
  10561. * Starts a 2D tranformation saving current graphic state.
  10562. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  10563. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10564. * @public
  10565. * @since 2.1.000 (2008-01-07)
  10566. * @see StartTransform(), StopTransform()
  10567. */
  10568. public function StartTransform() {
  10569. if ($this->state != 2) {
  10570. return;
  10571. }
  10572. $this->_outSaveGraphicsState();
  10573. if ($this->inxobj) {
  10574. // we are inside an XObject template
  10575. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10576. } else {
  10577. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  10578. }
  10579. ++$this->transfmatrix_key;
  10580. $this->transfmatrix[$this->transfmatrix_key] = array();
  10581. }
  10582. /**
  10583. * Stops a 2D tranformation restoring previous graphic state.
  10584. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  10585. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10586. * @public
  10587. * @since 2.1.000 (2008-01-07)
  10588. * @see StartTransform(), StopTransform()
  10589. */
  10590. public function StopTransform() {
  10591. if ($this->state != 2) {
  10592. return;
  10593. }
  10594. $this->_outRestoreGraphicsState();
  10595. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  10596. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  10597. --$this->transfmatrix_key;
  10598. }
  10599. if ($this->inxobj) {
  10600. // we are inside an XObject template
  10601. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  10602. } else {
  10603. array_pop($this->transfmrk[$this->page]);
  10604. }
  10605. }
  10606. /**
  10607. * Horizontal Scaling.
  10608. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10609. * @param $x (int) abscissa of the scaling center. Default is current x position
  10610. * @param $y (int) ordinate of the scaling center. Default is current y position
  10611. * @public
  10612. * @since 2.1.000 (2008-01-07)
  10613. * @see StartTransform(), StopTransform()
  10614. */
  10615. public function ScaleX($s_x, $x='', $y='') {
  10616. $this->Scale($s_x, 100, $x, $y);
  10617. }
  10618. /**
  10619. * Vertical Scaling.
  10620. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10621. * @param $x (int) abscissa of the scaling center. Default is current x position
  10622. * @param $y (int) ordinate of the scaling center. Default is current y position
  10623. * @public
  10624. * @since 2.1.000 (2008-01-07)
  10625. * @see StartTransform(), StopTransform()
  10626. */
  10627. public function ScaleY($s_y, $x='', $y='') {
  10628. $this->Scale(100, $s_y, $x, $y);
  10629. }
  10630. /**
  10631. * Vertical and horizontal proportional Scaling.
  10632. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  10633. * @param $x (int) abscissa of the scaling center. Default is current x position
  10634. * @param $y (int) ordinate of the scaling center. Default is current y position
  10635. * @public
  10636. * @since 2.1.000 (2008-01-07)
  10637. * @see StartTransform(), StopTransform()
  10638. */
  10639. public function ScaleXY($s, $x='', $y='') {
  10640. $this->Scale($s, $s, $x, $y);
  10641. }
  10642. /**
  10643. * Vertical and horizontal non-proportional Scaling.
  10644. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10645. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10646. * @param $x (int) abscissa of the scaling center. Default is current x position
  10647. * @param $y (int) ordinate of the scaling center. Default is current y position
  10648. * @public
  10649. * @since 2.1.000 (2008-01-07)
  10650. * @see StartTransform(), StopTransform()
  10651. */
  10652. public function Scale($s_x, $s_y, $x='', $y='') {
  10653. if ($x === '') {
  10654. $x = $this->x;
  10655. }
  10656. if ($y === '') {
  10657. $y = $this->y;
  10658. }
  10659. if (($s_x == 0) OR ($s_y == 0)) {
  10660. $this->Error('Please do not use values equal to zero for scaling');
  10661. }
  10662. $y = ($this->h - $y) * $this->k;
  10663. $x *= $this->k;
  10664. //calculate elements of transformation matrix
  10665. $s_x /= 100;
  10666. $s_y /= 100;
  10667. $tm = array();
  10668. $tm[0] = $s_x;
  10669. $tm[1] = 0;
  10670. $tm[2] = 0;
  10671. $tm[3] = $s_y;
  10672. $tm[4] = $x * (1 - $s_x);
  10673. $tm[5] = $y * (1 - $s_y);
  10674. //scale the coordinate system
  10675. $this->Transform($tm);
  10676. }
  10677. /**
  10678. * Horizontal Mirroring.
  10679. * @param $x (int) abscissa of the point. Default is current x position
  10680. * @public
  10681. * @since 2.1.000 (2008-01-07)
  10682. * @see StartTransform(), StopTransform()
  10683. */
  10684. public function MirrorH($x='') {
  10685. $this->Scale(-100, 100, $x);
  10686. }
  10687. /**
  10688. * Verical Mirroring.
  10689. * @param $y (int) ordinate of the point. Default is current y position
  10690. * @public
  10691. * @since 2.1.000 (2008-01-07)
  10692. * @see StartTransform(), StopTransform()
  10693. */
  10694. public function MirrorV($y='') {
  10695. $this->Scale(100, -100, '', $y);
  10696. }
  10697. /**
  10698. * Point reflection mirroring.
  10699. * @param $x (int) abscissa of the point. Default is current x position
  10700. * @param $y (int) ordinate of the point. Default is current y position
  10701. * @public
  10702. * @since 2.1.000 (2008-01-07)
  10703. * @see StartTransform(), StopTransform()
  10704. */
  10705. public function MirrorP($x='',$y='') {
  10706. $this->Scale(-100, -100, $x, $y);
  10707. }
  10708. /**
  10709. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  10710. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  10711. * @param $x (int) abscissa of the point. Default is current x position
  10712. * @param $y (int) ordinate of the point. Default is current y position
  10713. * @public
  10714. * @since 2.1.000 (2008-01-07)
  10715. * @see StartTransform(), StopTransform()
  10716. */
  10717. public function MirrorL($angle=0, $x='',$y='') {
  10718. $this->Scale(-100, 100, $x, $y);
  10719. $this->Rotate(-2*($angle-90), $x, $y);
  10720. }
  10721. /**
  10722. * Translate graphic object horizontally.
  10723. * @param $t_x (int) movement to the right (or left for RTL)
  10724. * @public
  10725. * @since 2.1.000 (2008-01-07)
  10726. * @see StartTransform(), StopTransform()
  10727. */
  10728. public function TranslateX($t_x) {
  10729. $this->Translate($t_x, 0);
  10730. }
  10731. /**
  10732. * Translate graphic object vertically.
  10733. * @param $t_y (int) movement to the bottom
  10734. * @public
  10735. * @since 2.1.000 (2008-01-07)
  10736. * @see StartTransform(), StopTransform()
  10737. */
  10738. public function TranslateY($t_y) {
  10739. $this->Translate(0, $t_y);
  10740. }
  10741. /**
  10742. * Translate graphic object horizontally and vertically.
  10743. * @param $t_x (int) movement to the right
  10744. * @param $t_y (int) movement to the bottom
  10745. * @public
  10746. * @since 2.1.000 (2008-01-07)
  10747. * @see StartTransform(), StopTransform()
  10748. */
  10749. public function Translate($t_x, $t_y) {
  10750. //calculate elements of transformation matrix
  10751. $tm = array();
  10752. $tm[0] = 1;
  10753. $tm[1] = 0;
  10754. $tm[2] = 0;
  10755. $tm[3] = 1;
  10756. $tm[4] = $t_x * $this->k;
  10757. $tm[5] = -$t_y * $this->k;
  10758. //translate the coordinate system
  10759. $this->Transform($tm);
  10760. }
  10761. /**
  10762. * Rotate object.
  10763. * @param $angle (float) angle in degrees for counter-clockwise rotation
  10764. * @param $x (int) abscissa of the rotation center. Default is current x position
  10765. * @param $y (int) ordinate of the rotation center. Default is current y position
  10766. * @public
  10767. * @since 2.1.000 (2008-01-07)
  10768. * @see StartTransform(), StopTransform()
  10769. */
  10770. public function Rotate($angle, $x='', $y='') {
  10771. if ($x === '') {
  10772. $x = $this->x;
  10773. }
  10774. if ($y === '') {
  10775. $y = $this->y;
  10776. }
  10777. $y = ($this->h - $y) * $this->k;
  10778. $x *= $this->k;
  10779. //calculate elements of transformation matrix
  10780. $tm = array();
  10781. $tm[0] = cos(deg2rad($angle));
  10782. $tm[1] = sin(deg2rad($angle));
  10783. $tm[2] = -$tm[1];
  10784. $tm[3] = $tm[0];
  10785. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  10786. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  10787. //rotate the coordinate system around ($x,$y)
  10788. $this->Transform($tm);
  10789. }
  10790. /**
  10791. * Skew horizontally.
  10792. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10793. * @param $x (int) abscissa of the skewing center. default is current x position
  10794. * @param $y (int) ordinate of the skewing center. default is current y position
  10795. * @public
  10796. * @since 2.1.000 (2008-01-07)
  10797. * @see StartTransform(), StopTransform()
  10798. */
  10799. public function SkewX($angle_x, $x='', $y='') {
  10800. $this->Skew($angle_x, 0, $x, $y);
  10801. }
  10802. /**
  10803. * Skew vertically.
  10804. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10805. * @param $x (int) abscissa of the skewing center. default is current x position
  10806. * @param $y (int) ordinate of the skewing center. default is current y position
  10807. * @public
  10808. * @since 2.1.000 (2008-01-07)
  10809. * @see StartTransform(), StopTransform()
  10810. */
  10811. public function SkewY($angle_y, $x='', $y='') {
  10812. $this->Skew(0, $angle_y, $x, $y);
  10813. }
  10814. /**
  10815. * Skew.
  10816. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10817. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10818. * @param $x (int) abscissa of the skewing center. default is current x position
  10819. * @param $y (int) ordinate of the skewing center. default is current y position
  10820. * @public
  10821. * @since 2.1.000 (2008-01-07)
  10822. * @see StartTransform(), StopTransform()
  10823. */
  10824. public function Skew($angle_x, $angle_y, $x='', $y='') {
  10825. if ($x === '') {
  10826. $x = $this->x;
  10827. }
  10828. if ($y === '') {
  10829. $y = $this->y;
  10830. }
  10831. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  10832. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  10833. }
  10834. $x *= $this->k;
  10835. $y = ($this->h - $y) * $this->k;
  10836. //calculate elements of transformation matrix
  10837. $tm = array();
  10838. $tm[0] = 1;
  10839. $tm[1] = tan(deg2rad($angle_y));
  10840. $tm[2] = tan(deg2rad($angle_x));
  10841. $tm[3] = 1;
  10842. $tm[4] = -$tm[2] * $y;
  10843. $tm[5] = -$tm[1] * $x;
  10844. //skew the coordinate system
  10845. $this->Transform($tm);
  10846. }
  10847. /**
  10848. * Apply graphic transformations.
  10849. * @param $tm (array) transformation matrix
  10850. * @protected
  10851. * @since 2.1.000 (2008-01-07)
  10852. * @see StartTransform(), StopTransform()
  10853. */
  10854. protected function Transform($tm) {
  10855. if ($this->state != 2) {
  10856. return;
  10857. }
  10858. $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  10859. // add tranformation matrix
  10860. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  10861. // update transformation mark
  10862. if ($this->inxobj) {
  10863. // we are inside an XObject template
  10864. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  10865. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  10866. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10867. }
  10868. } elseif (end($this->transfmrk[$this->page]) !== false) {
  10869. $key = key($this->transfmrk[$this->page]);
  10870. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  10871. }
  10872. }
  10873. // END TRANSFORMATIONS SECTION -------------------------
  10874. // START GRAPHIC FUNCTIONS SECTION ---------------------
  10875. // The following section is based on the code provided by David Hernandez Sanz
  10876. /**
  10877. * 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.
  10878. * @param $width (float) The width.
  10879. * @public
  10880. * @since 1.0
  10881. * @see Line(), Rect(), Cell(), MultiCell()
  10882. */
  10883. public function SetLineWidth($width) {
  10884. //Set line width
  10885. $this->LineWidth = $width;
  10886. $this->linestyleWidth = sprintf('%F w', ($width * $this->k));
  10887. if ($this->state == 2) {
  10888. $this->_out($this->linestyleWidth);
  10889. }
  10890. }
  10891. /**
  10892. * Returns the current the line width.
  10893. * @return int Line width
  10894. * @public
  10895. * @since 2.1.000 (2008-01-07)
  10896. * @see Line(), SetLineWidth()
  10897. */
  10898. public function GetLineWidth() {
  10899. return $this->LineWidth;
  10900. }
  10901. /**
  10902. * Set line style.
  10903. * @param $style (array) Line style. Array with keys among the following:
  10904. * <ul>
  10905. * <li>width (float): Width of the line in user units.</li>
  10906. * <li>cap (string): Type of cap to put on the line. Possible values are:
  10907. * butt, round, square. The difference between "square" and "butt" is that
  10908. * "square" projects a flat end past the end of the line.</li>
  10909. * <li>join (string): Type of join. Possible values are: miter, round,
  10910. * bevel.</li>
  10911. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  10912. * series of length values, which are the lengths of the on and off dashes.
  10913. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  10914. * 1 off, 2 on, 1 off, ...</li>
  10915. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  10916. * the point at which the pattern starts.</li>
  10917. * <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>
  10918. * </ul>
  10919. * @param $ret (boolean) if true do not send the command.
  10920. * @return string the PDF command
  10921. * @public
  10922. * @since 2.1.000 (2008-01-08)
  10923. */
  10924. public function SetLineStyle($style, $ret=false) {
  10925. $s = ''; // string to be returned
  10926. if (!is_array($style)) {
  10927. return;
  10928. }
  10929. if (isset($style['width'])) {
  10930. $this->LineWidth = $style['width'];
  10931. $this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
  10932. $s .= $this->linestyleWidth.' ';
  10933. }
  10934. if (isset($style['cap'])) {
  10935. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  10936. if (isset($ca[$style['cap']])) {
  10937. $this->linestyleCap = $ca[$style['cap']].' J';
  10938. $s .= $this->linestyleCap.' ';
  10939. }
  10940. }
  10941. if (isset($style['join'])) {
  10942. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  10943. if (isset($ja[$style['join']])) {
  10944. $this->linestyleJoin = $ja[$style['join']].' j';
  10945. $s .= $this->linestyleJoin.' ';
  10946. }
  10947. }
  10948. if (isset($style['dash'])) {
  10949. $dash_string = '';
  10950. if ($style['dash']) {
  10951. if (preg_match('/^.+,/', $style['dash']) > 0) {
  10952. $tab = explode(',', $style['dash']);
  10953. } else {
  10954. $tab = array($style['dash']);
  10955. }
  10956. $dash_string = '';
  10957. foreach ($tab as $i => $v) {
  10958. if ($i) {
  10959. $dash_string .= ' ';
  10960. }
  10961. $dash_string .= sprintf('%F', $v);
  10962. }
  10963. }
  10964. if (!isset($style['phase']) OR !$style['dash']) {
  10965. $style['phase'] = 0;
  10966. }
  10967. $this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
  10968. $s .= $this->linestyleDash.' ';
  10969. }
  10970. if (isset($style['color'])) {
  10971. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  10972. }
  10973. if (!$ret AND ($this->state == 2)) {
  10974. $this->_out($s);
  10975. }
  10976. return $s;
  10977. }
  10978. /**
  10979. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  10980. * @param $x (float) Abscissa of point.
  10981. * @param $y (float) Ordinate of point.
  10982. * @protected
  10983. * @since 2.1.000 (2008-01-08)
  10984. */
  10985. protected function _outPoint($x, $y) {
  10986. if ($this->state == 2) {
  10987. $this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
  10988. }
  10989. }
  10990. /**
  10991. * Append a straight line segment from the current point to the point (x, y).
  10992. * The new current point shall be (x, y).
  10993. * @param $x (float) Abscissa of end point.
  10994. * @param $y (float) Ordinate of end point.
  10995. * @protected
  10996. * @since 2.1.000 (2008-01-08)
  10997. */
  10998. protected function _outLine($x, $y) {
  10999. if ($this->state == 2) {
  11000. $this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
  11001. }
  11002. }
  11003. /**
  11004. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  11005. * @param $x (float) Abscissa of upper-left corner.
  11006. * @param $y (float) Ordinate of upper-left corner.
  11007. * @param $w (float) Width.
  11008. * @param $h (float) Height.
  11009. * @param $op (string) options
  11010. * @protected
  11011. * @since 2.1.000 (2008-01-08)
  11012. */
  11013. protected function _outRect($x, $y, $w, $h, $op) {
  11014. if ($this->state == 2) {
  11015. $this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
  11016. }
  11017. }
  11018. /**
  11019. * 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.
  11020. * The new current point shall be (x3, y3).
  11021. * @param $x1 (float) Abscissa of control point 1.
  11022. * @param $y1 (float) Ordinate of control point 1.
  11023. * @param $x2 (float) Abscissa of control point 2.
  11024. * @param $y2 (float) Ordinate of control point 2.
  11025. * @param $x3 (float) Abscissa of end point.
  11026. * @param $y3 (float) Ordinate of end point.
  11027. * @protected
  11028. * @since 2.1.000 (2008-01-08)
  11029. */
  11030. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  11031. if ($this->state == 2) {
  11032. $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)));
  11033. }
  11034. }
  11035. /**
  11036. * 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.
  11037. * The new current point shall be (x3, y3).
  11038. * @param $x2 (float) Abscissa of control point 2.
  11039. * @param $y2 (float) Ordinate of control point 2.
  11040. * @param $x3 (float) Abscissa of end point.
  11041. * @param $y3 (float) Ordinate of end point.
  11042. * @protected
  11043. * @since 4.9.019 (2010-04-26)
  11044. */
  11045. protected function _outCurveV($x2, $y2, $x3, $y3) {
  11046. if ($this->state == 2) {
  11047. $this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11048. }
  11049. }
  11050. /**
  11051. * 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.
  11052. * The new current point shall be (x3, y3).
  11053. * @param $x1 (float) Abscissa of control point 1.
  11054. * @param $y1 (float) Ordinate of control point 1.
  11055. * @param $x3 (float) Abscissa of end point.
  11056. * @param $y3 (float) Ordinate of end point.
  11057. * @protected
  11058. * @since 2.1.000 (2008-01-08)
  11059. */
  11060. protected function _outCurveY($x1, $y1, $x3, $y3) {
  11061. if ($this->state == 2) {
  11062. $this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11063. }
  11064. }
  11065. /**
  11066. * Draws a line between two points.
  11067. * @param $x1 (float) Abscissa of first point.
  11068. * @param $y1 (float) Ordinate of first point.
  11069. * @param $x2 (float) Abscissa of second point.
  11070. * @param $y2 (float) Ordinate of second point.
  11071. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  11072. * @public
  11073. * @since 1.0
  11074. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  11075. */
  11076. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  11077. if ($this->state != 2) {
  11078. return;
  11079. }
  11080. if (is_array($style)) {
  11081. $this->SetLineStyle($style);
  11082. }
  11083. $this->_outPoint($x1, $y1);
  11084. $this->_outLine($x2, $y2);
  11085. $this->_out('S');
  11086. }
  11087. /**
  11088. * Draws a rectangle.
  11089. * @param $x (float) Abscissa of upper-left corner.
  11090. * @param $y (float) Ordinate of upper-left corner.
  11091. * @param $w (float) Width.
  11092. * @param $h (float) Height.
  11093. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11094. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  11095. * <ul>
  11096. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  11097. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  11098. * </ul>
  11099. * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
  11100. * @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).
  11101. * @public
  11102. * @since 1.0
  11103. * @see SetLineStyle()
  11104. */
  11105. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  11106. if ($this->state != 2) {
  11107. return;
  11108. }
  11109. if (empty($style)) {
  11110. $style = 'S';
  11111. }
  11112. if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
  11113. // set background color
  11114. $this->SetFillColorArray($fill_color);
  11115. }
  11116. if (!empty($border_style)) {
  11117. if (isset($border_style['all']) AND !empty($border_style['all'])) {
  11118. //set global style for border
  11119. $this->SetLineStyle($border_style['all']);
  11120. $border_style = array();
  11121. } else {
  11122. // remove stroke operator from style
  11123. $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*' );
  11124. if (isset($opnostroke[$style])) {
  11125. $style = $opnostroke[$style];
  11126. }
  11127. }
  11128. }
  11129. if (!empty($style)) {
  11130. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11131. $this->_outRect($x, $y, $w, $h, $op);
  11132. }
  11133. if (!empty($border_style)) {
  11134. $border_style2 = array();
  11135. foreach ($border_style as $line => $value) {
  11136. $length = strlen($line);
  11137. for ($i = 0; $i < $length; ++$i) {
  11138. $border_style2[$line[$i]] = $value;
  11139. }
  11140. }
  11141. $border_style = $border_style2;
  11142. if (isset($border_style['L']) AND $border_style['L']) {
  11143. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  11144. }
  11145. if (isset($border_style['T']) AND $border_style['T']) {
  11146. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  11147. }
  11148. if (isset($border_style['R']) AND $border_style['R']) {
  11149. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  11150. }
  11151. if (isset($border_style['B']) AND $border_style['B']) {
  11152. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  11153. }
  11154. }
  11155. }
  11156. /**
  11157. * Draws a Bezier curve.
  11158. * The Bezier curve is a tangent to the line between the control points at
  11159. * either end of the curve.
  11160. * @param $x0 (float) Abscissa of start point.
  11161. * @param $y0 (float) Ordinate of start point.
  11162. * @param $x1 (float) Abscissa of control point 1.
  11163. * @param $y1 (float) Ordinate of control point 1.
  11164. * @param $x2 (float) Abscissa of control point 2.
  11165. * @param $y2 (float) Ordinate of control point 2.
  11166. * @param $x3 (float) Abscissa of end point.
  11167. * @param $y3 (float) Ordinate of end point.
  11168. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11169. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11170. * @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).
  11171. * @public
  11172. * @see SetLineStyle()
  11173. * @since 2.1.000 (2008-01-08)
  11174. */
  11175. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  11176. if ($this->state != 2) {
  11177. return;
  11178. }
  11179. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11180. $this->SetFillColorArray($fill_color);
  11181. }
  11182. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11183. if ($line_style) {
  11184. $this->SetLineStyle($line_style);
  11185. }
  11186. $this->_outPoint($x0, $y0);
  11187. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11188. $this->_out($op);
  11189. }
  11190. /**
  11191. * Draws a poly-Bezier curve.
  11192. * Each Bezier curve segment is a tangent to the line between the control points at
  11193. * either end of the curve.
  11194. * @param $x0 (float) Abscissa of start point.
  11195. * @param $y0 (float) Ordinate of start point.
  11196. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  11197. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11198. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11199. * @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).
  11200. * @public
  11201. * @see SetLineStyle()
  11202. * @since 3.0008 (2008-05-12)
  11203. */
  11204. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  11205. if ($this->state != 2) {
  11206. return;
  11207. }
  11208. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11209. $this->SetFillColorArray($fill_color);
  11210. }
  11211. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11212. if ($op == 'f') {
  11213. $line_style = array();
  11214. }
  11215. if ($line_style) {
  11216. $this->SetLineStyle($line_style);
  11217. }
  11218. $this->_outPoint($x0, $y0);
  11219. foreach ($segments as $segment) {
  11220. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  11221. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11222. }
  11223. $this->_out($op);
  11224. }
  11225. /**
  11226. * Draws an ellipse.
  11227. * An ellipse is formed from n Bezier curves.
  11228. * @param $x0 (float) Abscissa of center point.
  11229. * @param $y0 (float) Ordinate of center point.
  11230. * @param $rx (float) Horizontal radius.
  11231. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11232. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11233. * @param $astart: (float) Angle start of draw line. Default value: 0.
  11234. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  11235. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11236. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  11237. * @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).
  11238. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11239. * @author Nicola Asuni
  11240. * @public
  11241. * @since 2.1.000 (2008-01-08)
  11242. */
  11243. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11244. if ($this->state != 2) {
  11245. return;
  11246. }
  11247. if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
  11248. $ry = $rx;
  11249. }
  11250. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11251. $this->SetFillColorArray($fill_color);
  11252. }
  11253. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11254. if ($op == 'f') {
  11255. $line_style = array();
  11256. }
  11257. if ($line_style) {
  11258. $this->SetLineStyle($line_style);
  11259. }
  11260. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  11261. $this->_out($op);
  11262. }
  11263. /**
  11264. * Append an elliptical arc to the current path.
  11265. * An ellipse is formed from n Bezier curves.
  11266. * @param $xc (float) Abscissa of center point.
  11267. * @param $yc (float) Ordinate of center point.
  11268. * @param $rx (float) Horizontal radius.
  11269. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11270. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  11271. * @param $angs: (float) Angle start of draw line. Default value: 0.
  11272. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  11273. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  11274. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11275. * @param $startpoint (boolean) if true output a starting point.
  11276. * @param $ccw (boolean) if true draws in counter-clockwise.
  11277. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  11278. * @return array bounding box coordinates (x min, y min, x max, y max)
  11279. * @author Nicola Asuni
  11280. * @protected
  11281. * @since 4.9.019 (2010-04-26)
  11282. */
  11283. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  11284. if (($rx <= 0) OR ($ry < 0)) {
  11285. return;
  11286. }
  11287. $k = $this->k;
  11288. if ($nc < 2) {
  11289. $nc = 2;
  11290. }
  11291. $xmin = 2147483647;
  11292. $ymin = 2147483647;
  11293. $xmax = 0;
  11294. $ymax = 0;
  11295. if ($pie) {
  11296. // center of the arc
  11297. $this->_outPoint($xc, $yc);
  11298. }
  11299. $xang = deg2rad((float) $xang);
  11300. $angs = deg2rad((float) $angs);
  11301. $angf = deg2rad((float) $angf);
  11302. if ($svg) {
  11303. $as = $angs;
  11304. $af = $angf;
  11305. } else {
  11306. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  11307. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  11308. }
  11309. if ($as < 0) {
  11310. $as += (2 * M_PI);
  11311. }
  11312. if ($af < 0) {
  11313. $af += (2 * M_PI);
  11314. }
  11315. if ($ccw AND ($as > $af)) {
  11316. // reverse rotation
  11317. $as -= (2 * M_PI);
  11318. } elseif (!$ccw AND ($as < $af)) {
  11319. // reverse rotation
  11320. $af -= (2 * M_PI);
  11321. }
  11322. $total_angle = ($af - $as);
  11323. if ($nc < 2) {
  11324. $nc = 2;
  11325. }
  11326. // total arcs to draw
  11327. $nc *= (2 * abs($total_angle) / M_PI);
  11328. $nc = round($nc) + 1;
  11329. // angle of each arc
  11330. $arcang = ($total_angle / $nc);
  11331. // center point in PDF coordinates
  11332. $x0 = $xc;
  11333. $y0 = ($this->h - $yc);
  11334. // starting angle
  11335. $ang = $as;
  11336. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  11337. $cos_xang = cos($xang);
  11338. $sin_xang = sin($xang);
  11339. $cos_ang = cos($ang);
  11340. $sin_ang = sin($ang);
  11341. // first arc point
  11342. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11343. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11344. // first Bezier control point
  11345. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11346. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11347. if ($pie) {
  11348. // line from center to arc starting point
  11349. $this->_outLine($px1, $this->h - $py1);
  11350. } elseif ($startpoint) {
  11351. // arc starting point
  11352. $this->_outPoint($px1, $this->h - $py1);
  11353. }
  11354. // draw arcs
  11355. for ($i = 1; $i <= $nc; ++$i) {
  11356. // starting angle
  11357. $ang = $as + ($i * $arcang);
  11358. if ($i == $nc) {
  11359. $ang = $af;
  11360. }
  11361. $cos_ang = cos($ang);
  11362. $sin_ang = sin($ang);
  11363. // second arc point
  11364. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11365. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11366. // second Bezier control point
  11367. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11368. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11369. // draw arc
  11370. $cx1 = ($px1 + $qx1);
  11371. $cy1 = ($this->h - ($py1 + $qy1));
  11372. $cx2 = ($px2 - $qx2);
  11373. $cy2 = ($this->h - ($py2 - $qy2));
  11374. $cx3 = $px2;
  11375. $cy3 = ($this->h - $py2);
  11376. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  11377. // get bounding box coordinates
  11378. $xmin = min($xmin, $cx1, $cx2, $cx3);
  11379. $ymin = min($ymin, $cy1, $cy2, $cy3);
  11380. $xmax = max($xmax, $cx1, $cx2, $cx3);
  11381. $ymax = max($ymax, $cy1, $cy2, $cy3);
  11382. // move to next point
  11383. $px1 = $px2;
  11384. $py1 = $py2;
  11385. $qx1 = $qx2;
  11386. $qy1 = $qy2;
  11387. }
  11388. if ($pie) {
  11389. $this->_outLine($xc, $yc);
  11390. // get bounding box coordinates
  11391. $xmin = min($xmin, $xc);
  11392. $ymin = min($ymin, $yc);
  11393. $xmax = max($xmax, $xc);
  11394. $ymax = max($ymax, $yc);
  11395. }
  11396. return array($xmin, $ymin, $xmax, $ymax);
  11397. }
  11398. /**
  11399. * Draws a circle.
  11400. * A circle is formed from n Bezier curves.
  11401. * @param $x0 (float) Abscissa of center point.
  11402. * @param $y0 (float) Ordinate of center point.
  11403. * @param $r (float) Radius.
  11404. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  11405. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  11406. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11407. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11408. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11409. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  11410. * @public
  11411. * @since 2.1.000 (2008-01-08)
  11412. */
  11413. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11414. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  11415. }
  11416. /**
  11417. * Draws a polygonal line
  11418. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11419. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11420. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11421. * <ul>
  11422. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11423. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11424. * </ul>
  11425. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11426. * @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).
  11427. * @since 4.8.003 (2009-09-15)
  11428. * @public
  11429. */
  11430. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  11431. $this->Polygon($p, $style, $line_style, $fill_color, false);
  11432. }
  11433. /**
  11434. * Draws a polygon.
  11435. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11436. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11437. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11438. * <ul>
  11439. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11440. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11441. * </ul>
  11442. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11443. * @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).
  11444. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  11445. * @public
  11446. * @since 2.1.000 (2008-01-08)
  11447. */
  11448. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  11449. if ($this->state != 2) {
  11450. return;
  11451. }
  11452. $nc = count($p); // number of coordinates
  11453. $np = $nc / 2; // number of points
  11454. if ($closed) {
  11455. // close polygon by adding the first 2 points at the end (one line)
  11456. for ($i = 0; $i < 4; ++$i) {
  11457. $p[$nc + $i] = $p[$i];
  11458. }
  11459. // copy style for the last added line
  11460. if (isset($line_style[0])) {
  11461. $line_style[$np] = $line_style[0];
  11462. }
  11463. $nc += 4;
  11464. }
  11465. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11466. $this->SetFillColorArray($fill_color);
  11467. }
  11468. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11469. if ($op == 'f') {
  11470. $line_style = array();
  11471. }
  11472. $draw = true;
  11473. if ($line_style) {
  11474. if (isset($line_style['all'])) {
  11475. $this->SetLineStyle($line_style['all']);
  11476. } else {
  11477. $draw = false;
  11478. if ($op == 'B') {
  11479. // draw fill
  11480. $op = 'f';
  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. // draw outline
  11488. $this->_outPoint($p[0], $p[1]);
  11489. for ($i = 2; $i < $nc; $i = $i + 2) {
  11490. $line_num = ($i / 2) - 1;
  11491. if (isset($line_style[$line_num])) {
  11492. if ($line_style[$line_num] != 0) {
  11493. if (is_array($line_style[$line_num])) {
  11494. $this->_out('S');
  11495. $this->SetLineStyle($line_style[$line_num]);
  11496. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  11497. $this->_outLine($p[$i], $p[$i + 1]);
  11498. $this->_out('S');
  11499. $this->_outPoint($p[$i], $p[$i + 1]);
  11500. } else {
  11501. $this->_outLine($p[$i], $p[$i + 1]);
  11502. }
  11503. }
  11504. } else {
  11505. $this->_outLine($p[$i], $p[$i + 1]);
  11506. }
  11507. }
  11508. $this->_out($op);
  11509. }
  11510. }
  11511. if ($draw) {
  11512. $this->_outPoint($p[0], $p[1]);
  11513. for ($i = 2; $i < $nc; $i = $i + 2) {
  11514. $this->_outLine($p[$i], $p[$i + 1]);
  11515. }
  11516. $this->_out($op);
  11517. }
  11518. }
  11519. /**
  11520. * Draws a regular polygon.
  11521. * @param $x0 (float) Abscissa of center point.
  11522. * @param $y0 (float) Ordinate of center point.
  11523. * @param $r: (float) Radius of inscribed circle.
  11524. * @param $ns (integer) Number of sides.
  11525. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  11526. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  11527. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11528. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11529. * <ul>
  11530. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  11531. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  11532. * </ul>
  11533. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11534. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11535. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11536. * <ul>
  11537. * <li>D or empty string: Draw (default).</li>
  11538. * <li>F: Fill.</li>
  11539. * <li>DF or FD: Draw and fill.</li>
  11540. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11541. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11542. * </ul>
  11543. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11544. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11545. * @public
  11546. * @since 2.1.000 (2008-01-08)
  11547. */
  11548. 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()) {
  11549. if (3 > $ns) {
  11550. $ns = 3;
  11551. }
  11552. if ($draw_circle) {
  11553. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11554. }
  11555. $p = array();
  11556. for ($i = 0; $i < $ns; ++$i) {
  11557. $a = $angle + ($i * 360 / $ns);
  11558. $a_rad = deg2rad((float) $a);
  11559. $p[] = $x0 + ($r * sin($a_rad));
  11560. $p[] = $y0 + ($r * cos($a_rad));
  11561. }
  11562. $this->Polygon($p, $style, $line_style, $fill_color);
  11563. }
  11564. /**
  11565. * Draws a star polygon
  11566. * @param $x0 (float) Abscissa of center point.
  11567. * @param $y0 (float) Ordinate of center point.
  11568. * @param $r (float) Radius of inscribed circle.
  11569. * @param $nv (integer) Number of vertices.
  11570. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  11571. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11572. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  11573. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11574. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11575. * <ul>
  11576. * <li>all: Line style of all sides. Array like for
  11577. * SetLineStyle().</li>
  11578. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  11579. * </ul>
  11580. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11581. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11582. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11583. * <ul>
  11584. * <li>D or empty string: Draw (default).</li>
  11585. * <li>F: Fill.</li>
  11586. * <li>DF or FD: Draw and fill.</li>
  11587. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11588. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11589. * </ul>
  11590. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11591. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11592. * @public
  11593. * @since 2.1.000 (2008-01-08)
  11594. */
  11595. 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()) {
  11596. if ($nv < 2) {
  11597. $nv = 2;
  11598. }
  11599. if ($draw_circle) {
  11600. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11601. }
  11602. $p2 = array();
  11603. $visited = array();
  11604. for ($i = 0; $i < $nv; ++$i) {
  11605. $a = $angle + ($i * 360 / $nv);
  11606. $a_rad = deg2rad((float) $a);
  11607. $p2[] = $x0 + ($r * sin($a_rad));
  11608. $p2[] = $y0 + ($r * cos($a_rad));
  11609. $visited[] = false;
  11610. }
  11611. $p = array();
  11612. $i = 0;
  11613. do {
  11614. $p[] = $p2[$i * 2];
  11615. $p[] = $p2[($i * 2) + 1];
  11616. $visited[$i] = true;
  11617. $i += $ng;
  11618. $i %= $nv;
  11619. } while (!$visited[$i]);
  11620. $this->Polygon($p, $style, $line_style, $fill_color);
  11621. }
  11622. /**
  11623. * Draws a rounded rectangle.
  11624. * @param $x (float) Abscissa of upper-left corner.
  11625. * @param $y (float) Ordinate of upper-left corner.
  11626. * @param $w (float) Width.
  11627. * @param $h (float) Height.
  11628. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  11629. * @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").
  11630. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11631. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11632. * @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).
  11633. * @public
  11634. * @since 2.1.000 (2008-01-08)
  11635. */
  11636. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11637. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  11638. }
  11639. /**
  11640. * Draws a rounded rectangle.
  11641. * @param $x (float) Abscissa of upper-left corner.
  11642. * @param $y (float) Ordinate of upper-left corner.
  11643. * @param $w (float) Width.
  11644. * @param $h (float) Height.
  11645. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  11646. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  11647. * @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").
  11648. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11649. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11650. * @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).
  11651. * @public
  11652. * @since 4.9.019 (2010-04-22)
  11653. */
  11654. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11655. if ($this->state != 2) {
  11656. return;
  11657. }
  11658. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  11659. // Not rounded
  11660. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  11661. return;
  11662. }
  11663. // Rounded
  11664. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11665. $this->SetFillColorArray($fill_color);
  11666. }
  11667. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11668. if ($op == 'f') {
  11669. $border_style = array();
  11670. }
  11671. if ($border_style) {
  11672. $this->SetLineStyle($border_style);
  11673. }
  11674. $MyArc = 4 / 3 * (sqrt(2) - 1);
  11675. $this->_outPoint($x + $rx, $y);
  11676. $xc = $x + $w - $rx;
  11677. $yc = $y + $ry;
  11678. $this->_outLine($xc, $y);
  11679. if ($round_corner[0]) {
  11680. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  11681. } else {
  11682. $this->_outLine($x + $w, $y);
  11683. }
  11684. $xc = $x + $w - $rx;
  11685. $yc = $y + $h - $ry;
  11686. $this->_outLine($x + $w, $yc);
  11687. if ($round_corner[1]) {
  11688. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  11689. } else {
  11690. $this->_outLine($x + $w, $y + $h);
  11691. }
  11692. $xc = $x + $rx;
  11693. $yc = $y + $h - $ry;
  11694. $this->_outLine($xc, $y + $h);
  11695. if ($round_corner[2]) {
  11696. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  11697. } else {
  11698. $this->_outLine($x, $y + $h);
  11699. }
  11700. $xc = $x + $rx;
  11701. $yc = $y + $ry;
  11702. $this->_outLine($x, $yc);
  11703. if ($round_corner[3]) {
  11704. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  11705. } else {
  11706. $this->_outLine($x, $y);
  11707. $this->_outLine($x + $rx, $y);
  11708. }
  11709. $this->_out($op);
  11710. }
  11711. /**
  11712. * Draws a grahic arrow.
  11713. * @param $x0 (float) Abscissa of first point.
  11714. * @param $y0 (float) Ordinate of first point.
  11715. * @param $x1 (float) Abscissa of second point.
  11716. * @param $y1 (float) Ordinate of second point.
  11717. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  11718. * @param $arm_size (float) length of arrowhead arms
  11719. * @param $arm_angle (int) angle between an arm and the shaft
  11720. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  11721. * @since 4.6.018 (2009-07-10)
  11722. */
  11723. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  11724. // getting arrow direction angle
  11725. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  11726. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  11727. if ($dir_angle < 0) {
  11728. $dir_angle += (2 * M_PI);
  11729. }
  11730. $arm_angle = deg2rad($arm_angle);
  11731. $sx1 = $x1;
  11732. $sy1 = $y1;
  11733. if ($head_style > 0) {
  11734. // calculate the stopping point for the arrow shaft
  11735. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  11736. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  11737. }
  11738. // main arrow line / shaft
  11739. $this->Line($x0, $y0, $sx1, $sy1);
  11740. // left arrowhead arm tip
  11741. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  11742. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  11743. // right arrowhead arm tip
  11744. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  11745. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  11746. $mode = 'D';
  11747. $style = array();
  11748. switch ($head_style) {
  11749. case 0: {
  11750. // draw only arrowhead arms
  11751. $mode = 'D';
  11752. $style = array(1, 1, 0);
  11753. break;
  11754. }
  11755. case 1: {
  11756. // draw closed arrowhead, but no fill
  11757. $mode = 'D';
  11758. break;
  11759. }
  11760. case 2: {
  11761. // closed and filled arrowhead
  11762. $mode = 'DF';
  11763. break;
  11764. }
  11765. case 3: {
  11766. // filled arrowhead
  11767. $mode = 'F';
  11768. break;
  11769. }
  11770. }
  11771. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  11772. }
  11773. // END GRAPHIC FUNCTIONS SECTION -----------------------
  11774. /**
  11775. * Add a Named Destination.
  11776. * NOTE: destination names are unique, so only last entry will be saved.
  11777. * @param $name (string) Destination name.
  11778. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  11779. * @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.
  11780. * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
  11781. * @return (string) Stripped named destination identifier or false in case of error.
  11782. * @public
  11783. * @author Christian Deligant, Nicola Asuni
  11784. * @since 5.9.097 (2011-06-23)
  11785. */
  11786. public function setDestination($name, $y=-1, $page='', $x=-1) {
  11787. // remove unsupported characters
  11788. $name = TCPDF_STATIC::encodeNameObject($name);
  11789. if (TCPDF_STATIC::empty_string($name)) {
  11790. return false;
  11791. }
  11792. if ($y == -1) {
  11793. $y = $this->GetY();
  11794. } elseif ($y < 0) {
  11795. $y = 0;
  11796. } elseif ($y > $this->h) {
  11797. $y = $this->h;
  11798. }
  11799. if ($x == -1) {
  11800. $x = $this->GetX();
  11801. } elseif ($x < 0) {
  11802. $x = 0;
  11803. } elseif ($x > $this->w) {
  11804. $x = $this->w;
  11805. }
  11806. $fixed = false;
  11807. if (!empty($page) AND (substr($page, 0, 1) == '*')) {
  11808. $page = intval(substr($page, 1));
  11809. // this page number will not be changed when moving/add/deleting pages
  11810. $fixed = true;
  11811. }
  11812. if (empty($page)) {
  11813. $page = $this->PageNo();
  11814. if (empty($page)) {
  11815. return;
  11816. }
  11817. }
  11818. $this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
  11819. return $name;
  11820. }
  11821. /**
  11822. * Return the Named Destination array.
  11823. * @return (array) Named Destination array.
  11824. * @public
  11825. * @author Nicola Asuni
  11826. * @since 5.9.097 (2011-06-23)
  11827. */
  11828. public function getDestination() {
  11829. return $this->dests;
  11830. }
  11831. /**
  11832. * Insert Named Destinations.
  11833. * @protected
  11834. * @author Johannes G\FCntert, Nicola Asuni
  11835. * @since 5.9.098 (2011-06-23)
  11836. */
  11837. protected function _putdests() {
  11838. if (empty($this->dests)) {
  11839. return;
  11840. }
  11841. $this->n_dests = $this->_newobj();
  11842. $out = ' <<';
  11843. foreach($this->dests as $name => $o) {
  11844. $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)));
  11845. }
  11846. $out .= ' >>';
  11847. $out .= "\n".'endobj';
  11848. $this->_out($out);
  11849. }
  11850. /**
  11851. * Adds a bookmark - alias for Bookmark().
  11852. * @param $txt (string) Bookmark description.
  11853. * @param $level (int) Bookmark level (minimum value is 0).
  11854. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11855. * @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.
  11856. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11857. * @param $color (array) RGB color array (values from 0 to 255).
  11858. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11859. * @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).
  11860. * @public
  11861. */
  11862. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11863. $this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
  11864. }
  11865. /**
  11866. * Adds a bookmark.
  11867. * @param $txt (string) Bookmark description.
  11868. * @param $level (int) Bookmark level (minimum value is 0).
  11869. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11870. * @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.
  11871. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11872. * @param $color (array) RGB color array (values from 0 to 255).
  11873. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11874. * @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).
  11875. * @public
  11876. * @since 2.1.002 (2008-02-12)
  11877. */
  11878. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11879. if ($level < 0) {
  11880. $level = 0;
  11881. }
  11882. if (isset($this->outlines[0])) {
  11883. $lastoutline = end($this->outlines);
  11884. $maxlevel = $lastoutline['l'] + 1;
  11885. } else {
  11886. $maxlevel = 0;
  11887. }
  11888. if ($level > $maxlevel) {
  11889. $level = $maxlevel;
  11890. }
  11891. if ($y == -1) {
  11892. $y = $this->GetY();
  11893. } elseif ($y < 0) {
  11894. $y = 0;
  11895. } elseif ($y > $this->h) {
  11896. $y = $this->h;
  11897. }
  11898. if ($x == -1) {
  11899. $x = $this->GetX();
  11900. } elseif ($x < 0) {
  11901. $x = 0;
  11902. } elseif ($x > $this->w) {
  11903. $x = $this->w;
  11904. }
  11905. $fixed = false;
  11906. $pageAsString = (string) $page;
  11907. if ($pageAsString && $pageAsString[0] == '*') {
  11908. $page = intval(substr($page, 1));
  11909. // this page number will not be changed when moving/add/deleting pages
  11910. $fixed = true;
  11911. }
  11912. if (empty($page)) {
  11913. $page = $this->PageNo();
  11914. if (empty($page)) {
  11915. return;
  11916. }
  11917. }
  11918. $this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
  11919. }
  11920. /**
  11921. * Sort bookmarks for page and key.
  11922. * @protected
  11923. * @since 5.9.119 (2011-09-19)
  11924. */
  11925. protected function sortBookmarks() {
  11926. // get sorting columns
  11927. $outline_p = array();
  11928. $outline_y = array();
  11929. foreach ($this->outlines as $key => $row) {
  11930. $outline_p[$key] = $row['p'];
  11931. $outline_k[$key] = $key;
  11932. }
  11933. // sort outlines by page and original position
  11934. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  11935. }
  11936. /**
  11937. * Create a bookmark PDF string.
  11938. * @protected
  11939. * @author Olivier Plathey, Nicola Asuni
  11940. * @since 2.1.002 (2008-02-12)
  11941. */
  11942. protected function _putbookmarks() {
  11943. $nb = count($this->outlines);
  11944. if ($nb == 0) {
  11945. return;
  11946. }
  11947. // sort bookmarks
  11948. $this->sortBookmarks();
  11949. $lru = array();
  11950. $level = 0;
  11951. foreach ($this->outlines as $i => $o) {
  11952. if ($o['l'] > 0) {
  11953. $parent = $lru[($o['l'] - 1)];
  11954. //Set parent and last pointers
  11955. $this->outlines[$i]['parent'] = $parent;
  11956. $this->outlines[$parent]['last'] = $i;
  11957. if ($o['l'] > $level) {
  11958. //Level increasing: set first pointer
  11959. $this->outlines[$parent]['first'] = $i;
  11960. }
  11961. } else {
  11962. $this->outlines[$i]['parent'] = $nb;
  11963. }
  11964. if (($o['l'] <= $level) AND ($i > 0)) {
  11965. //Set prev and next pointers
  11966. $prev = $lru[$o['l']];
  11967. $this->outlines[$prev]['next'] = $i;
  11968. $this->outlines[$i]['prev'] = $prev;
  11969. }
  11970. $lru[$o['l']] = $i;
  11971. $level = $o['l'];
  11972. }
  11973. //Outline items
  11974. $n = $this->n + 1;
  11975. $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';
  11976. foreach ($this->outlines as $i => $o) {
  11977. $oid = $this->_newobj();
  11978. // covert HTML title to string
  11979. $title = preg_replace($nltags, "\n", $o['t']);
  11980. $title = preg_replace("/[\r]+/si", '', $title);
  11981. $title = preg_replace("/[\n]+/si", "\n", $title);
  11982. $title = strip_tags($title);
  11983. $title = $this->stringTrim($title);
  11984. $out = '<</Title '.$this->_textstring($title, $oid);
  11985. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  11986. if (isset($o['prev'])) {
  11987. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  11988. }
  11989. if (isset($o['next'])) {
  11990. $out .= ' /Next '.($n + $o['next']).' 0 R';
  11991. }
  11992. if (isset($o['first'])) {
  11993. $out .= ' /First '.($n + $o['first']).' 0 R';
  11994. }
  11995. if (isset($o['last'])) {
  11996. $out .= ' /Last '.($n + $o['last']).' 0 R';
  11997. }
  11998. if (isset($o['u']) AND !empty($o['u'])) {
  11999. // link
  12000. if (is_string($o['u'])) {
  12001. if ($o['u'][0] == '#') {
  12002. // internal destination
  12003. $out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
  12004. } elseif ($o['u'][0] == '%') {
  12005. // embedded PDF file
  12006. $filename = basename(substr($o['u'], 1));
  12007. $out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  12008. } elseif ($o['u'][0] == '*') {
  12009. // embedded generic file
  12010. $filename = basename(substr($o['u'], 1));
  12011. $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});';
  12012. $out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
  12013. } else {
  12014. // external URI link
  12015. $out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
  12016. }
  12017. } elseif (isset($this->links[$o['u']])) {
  12018. // internal link ID
  12019. $l = $this->links[$o['u']];
  12020. if (isset($this->page_obj_id[($l['p'])])) {
  12021. $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)));
  12022. }
  12023. }
  12024. } elseif (isset($this->page_obj_id[($o['p'])])) {
  12025. // link to a page
  12026. $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)));
  12027. }
  12028. // set font style
  12029. $style = 0;
  12030. if (!empty($o['s'])) {
  12031. // bold
  12032. if (strpos($o['s'], 'B') !== false) {
  12033. $style |= 2;
  12034. }
  12035. // oblique
  12036. if (strpos($o['s'], 'I') !== false) {
  12037. $style |= 1;
  12038. }
  12039. }
  12040. $out .= sprintf(' /F %d', $style);
  12041. // set bookmark color
  12042. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  12043. $color = array_values($o['c']);
  12044. $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  12045. } else {
  12046. // black
  12047. $out .= ' /C [0.0 0.0 0.0]';
  12048. }
  12049. $out .= ' /Count 0'; // normally closed item
  12050. $out .= ' >>';
  12051. $out .= "\n".'endobj';
  12052. $this->_out($out);
  12053. }
  12054. //Outline root
  12055. $this->OutlineRoot = $this->_newobj();
  12056. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  12057. }
  12058. // --- JAVASCRIPT ------------------------------------------------------
  12059. /**
  12060. * Adds a javascript
  12061. * @param $script (string) Javascript code
  12062. * @public
  12063. * @author Johannes G\FCntert, Nicola Asuni
  12064. * @since 2.1.002 (2008-02-12)
  12065. */
  12066. public function IncludeJS($script) {
  12067. $this->javascript .= $script;
  12068. }
  12069. /**
  12070. * Adds a javascript object and return object ID
  12071. * @param $script (string) Javascript code
  12072. * @param $onload (boolean) if true executes this object when opening the document
  12073. * @return int internal object ID
  12074. * @public
  12075. * @author Nicola Asuni
  12076. * @since 4.8.000 (2009-09-07)
  12077. */
  12078. public function addJavascriptObject($script, $onload=false) {
  12079. if ($this->pdfa_mode) {
  12080. // javascript is not allowed in PDF/A mode
  12081. return false;
  12082. }
  12083. ++$this->n;
  12084. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  12085. return $this->n;
  12086. }
  12087. /**
  12088. * Create a javascript PDF string.
  12089. * @protected
  12090. * @author Johannes G\FCntert, Nicola Asuni
  12091. * @since 2.1.002 (2008-02-12)
  12092. */
  12093. protected function _putjavascript() {
  12094. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  12095. return;
  12096. }
  12097. if (strpos($this->javascript, 'this.addField') > 0) {
  12098. if (!$this->ur['enabled']) {
  12099. //$this->setUserRights();
  12100. }
  12101. // the following two lines are used to avoid form fields duplication after saving
  12102. // The addField method only works when releasing user rights (UR3)
  12103. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  12104. $jsb = "getField('tcpdfdocsaved').value='saved';";
  12105. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  12106. }
  12107. // name tree for javascript
  12108. $this->n_js = '<< /Names [';
  12109. if (!empty($this->javascript)) {
  12110. $this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  12111. }
  12112. if (!empty($this->js_objects)) {
  12113. foreach ($this->js_objects as $key => $val) {
  12114. if ($val['onload']) {
  12115. $this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
  12116. }
  12117. }
  12118. }
  12119. $this->n_js .= ' ] >>';
  12120. // default Javascript object
  12121. if (!empty($this->javascript)) {
  12122. $obj_id = $this->_newobj();
  12123. $out = '<< /S /JavaScript';
  12124. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  12125. $out .= ' >>';
  12126. $out .= "\n".'endobj';
  12127. $this->_out($out);
  12128. }
  12129. // additional Javascript objects
  12130. if (!empty($this->js_objects)) {
  12131. foreach ($this->js_objects as $key => $val) {
  12132. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  12133. $this->_out($out);
  12134. }
  12135. }
  12136. }
  12137. /**
  12138. * Adds a javascript form field.
  12139. * @param $type (string) field type
  12140. * @param $name (string) field name
  12141. * @param $x (int) horizontal position
  12142. * @param $y (int) vertical position
  12143. * @param $w (int) width
  12144. * @param $h (int) height
  12145. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12146. * @protected
  12147. * @author Denis Van Nuffelen, Nicola Asuni
  12148. * @since 2.1.002 (2008-02-12)
  12149. */
  12150. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  12151. if ($this->rtl) {
  12152. $x = $x - $w;
  12153. }
  12154. // the followind avoid fields duplication after saving the document
  12155. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  12156. $k = $this->k;
  12157. $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";
  12158. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  12159. foreach($prop as $key => $val) {
  12160. if (strcmp(substr($key, -5), 'Color') == 0) {
  12161. $val = TCPDF_COLORS::_JScolor($val);
  12162. } else {
  12163. $val = "'".$val."'";
  12164. }
  12165. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  12166. }
  12167. if ($this->rtl) {
  12168. $this->x -= $w;
  12169. } else {
  12170. $this->x += $w;
  12171. }
  12172. $this->javascript .= '}';
  12173. }
  12174. // --- FORM FIELDS -----------------------------------------------------
  12175. /**
  12176. * Set default properties for form fields.
  12177. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12178. * @public
  12179. * @author Nicola Asuni
  12180. * @since 4.8.000 (2009-09-06)
  12181. */
  12182. public function setFormDefaultProp($prop=array()) {
  12183. $this->default_form_prop = $prop;
  12184. }
  12185. /**
  12186. * Return the default properties for form fields.
  12187. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12188. * @public
  12189. * @author Nicola Asuni
  12190. * @since 4.8.000 (2009-09-06)
  12191. */
  12192. public function getFormDefaultProp() {
  12193. return $this->default_form_prop;
  12194. }
  12195. /**
  12196. * Creates a text field
  12197. * @param $name (string) field name
  12198. * @param $w (float) Width of the rectangle
  12199. * @param $h (float) Height of the rectangle
  12200. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12201. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12202. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12203. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12204. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12205. * @public
  12206. * @author Nicola Asuni
  12207. * @since 4.8.000 (2009-09-07)
  12208. */
  12209. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12210. if ($x === '') {
  12211. $x = $this->x;
  12212. }
  12213. if ($y === '') {
  12214. $y = $this->y;
  12215. }
  12216. // check page for no-write regions and adapt page margins if necessary
  12217. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12218. if ($js) {
  12219. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  12220. return;
  12221. }
  12222. // get default style
  12223. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12224. // get annotation data
  12225. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12226. // set default appearance stream
  12227. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12228. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12229. $popt['da'] = $fontstyle;
  12230. // build appearance stream
  12231. $popt['ap'] = array();
  12232. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12233. $text = '';
  12234. if (isset($prop['value']) AND !empty($prop['value'])) {
  12235. $text = $prop['value'];
  12236. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  12237. $text = $opt['v'];
  12238. }
  12239. $tmpid = $this->startTemplate($w, $h, false);
  12240. $align = '';
  12241. if (isset($popt['q'])) {
  12242. switch ($popt['q']) {
  12243. case 0: {
  12244. $align = 'L';
  12245. break;
  12246. }
  12247. case 1: {
  12248. $align = 'C';
  12249. break;
  12250. }
  12251. case 2: {
  12252. $align = 'R';
  12253. break;
  12254. }
  12255. default: {
  12256. $align = '';
  12257. break;
  12258. }
  12259. }
  12260. }
  12261. $this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12262. $this->endTemplate();
  12263. --$this->n;
  12264. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12265. unset($this->xobjects[$tmpid]);
  12266. $popt['ap']['n'] .= 'Q EMC';
  12267. // merge options
  12268. $opt = array_merge($popt, $opt);
  12269. // remove some conflicting options
  12270. unset($opt['bs']);
  12271. // set remaining annotation data
  12272. $opt['Subtype'] = 'Widget';
  12273. $opt['ft'] = 'Tx';
  12274. $opt['t'] = $name;
  12275. // Additional annotation's parameters (check _putannotsobj() method):
  12276. //$opt['f']
  12277. //$opt['as']
  12278. //$opt['bs']
  12279. //$opt['be']
  12280. //$opt['c']
  12281. //$opt['border']
  12282. //$opt['h']
  12283. //$opt['mk'];
  12284. //$opt['mk']['r']
  12285. //$opt['mk']['bc'];
  12286. //$opt['mk']['bg'];
  12287. unset($opt['mk']['ca']);
  12288. unset($opt['mk']['rc']);
  12289. unset($opt['mk']['ac']);
  12290. unset($opt['mk']['i']);
  12291. unset($opt['mk']['ri']);
  12292. unset($opt['mk']['ix']);
  12293. unset($opt['mk']['if']);
  12294. //$opt['mk']['if']['sw'];
  12295. //$opt['mk']['if']['s'];
  12296. //$opt['mk']['if']['a'];
  12297. //$opt['mk']['if']['fb'];
  12298. unset($opt['mk']['tp']);
  12299. //$opt['tu']
  12300. //$opt['tm']
  12301. //$opt['ff']
  12302. //$opt['v']
  12303. //$opt['dv']
  12304. //$opt['a']
  12305. //$opt['aa']
  12306. //$opt['q']
  12307. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12308. if ($this->rtl) {
  12309. $this->x -= $w;
  12310. } else {
  12311. $this->x += $w;
  12312. }
  12313. }
  12314. /**
  12315. * Creates a RadioButton field.
  12316. * @param $name (string) Field name.
  12317. * @param $w (int) Width of the radio button.
  12318. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12319. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12320. * @param $onvalue (string) Value to be returned if selected.
  12321. * @param $checked (boolean) Define the initial state.
  12322. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12323. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12324. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12325. * @public
  12326. * @author Nicola Asuni
  12327. * @since 4.8.000 (2009-09-07)
  12328. */
  12329. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  12330. if ($x === '') {
  12331. $x = $this->x;
  12332. }
  12333. if ($y === '') {
  12334. $y = $this->y;
  12335. }
  12336. // check page for no-write regions and adapt page margins if necessary
  12337. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12338. if ($js) {
  12339. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  12340. return;
  12341. }
  12342. if (TCPDF_STATIC::empty_string($onvalue)) {
  12343. $onvalue = 'On';
  12344. }
  12345. if ($checked) {
  12346. $defval = $onvalue;
  12347. } else {
  12348. $defval = 'Off';
  12349. }
  12350. // set font
  12351. $font = 'zapfdingbats';
  12352. if ($this->pdfa_mode) {
  12353. // all fonts must be embedded
  12354. $font = 'pdfa'.$font;
  12355. }
  12356. $this->AddFont($font);
  12357. $tmpfont = $this->getFontBuffer($font);
  12358. // set data for parent group
  12359. if (!isset($this->radiobutton_groups[$this->page])) {
  12360. $this->radiobutton_groups[$this->page] = array();
  12361. }
  12362. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  12363. $this->radiobutton_groups[$this->page][$name] = array();
  12364. ++$this->n;
  12365. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  12366. $this->radio_groups[] = $this->n;
  12367. }
  12368. $kid = ($this->n + 1);
  12369. // save object ID to be added on Kids entry on parent object
  12370. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  12371. // get default style
  12372. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12373. $prop['NoToggleToOff'] = 'true';
  12374. $prop['Radio'] = 'true';
  12375. $prop['borderStyle'] = 'inset';
  12376. // get annotation data
  12377. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12378. // set additional default options
  12379. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12380. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12381. $popt['da'] = $fontstyle;
  12382. // build appearance stream
  12383. $popt['ap'] = array();
  12384. $popt['ap']['n'] = array();
  12385. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
  12386. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12387. $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);
  12388. $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);
  12389. if (!isset($popt['mk'])) {
  12390. $popt['mk'] = array();
  12391. }
  12392. $popt['mk']['ca'] = '(l)';
  12393. // merge options
  12394. $opt = array_merge($popt, $opt);
  12395. // set remaining annotation data
  12396. $opt['Subtype'] = 'Widget';
  12397. $opt['ft'] = 'Btn';
  12398. if ($checked) {
  12399. $opt['v'] = array('/'.$onvalue);
  12400. $opt['as'] = $onvalue;
  12401. } else {
  12402. $opt['as'] = 'Off';
  12403. }
  12404. // store readonly flag
  12405. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  12406. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  12407. }
  12408. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  12409. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12410. if ($this->rtl) {
  12411. $this->x -= $w;
  12412. } else {
  12413. $this->x += $w;
  12414. }
  12415. }
  12416. /**
  12417. * Creates a List-box field
  12418. * @param $name (string) field name
  12419. * @param $w (int) width
  12420. * @param $h (int) height
  12421. * @param $values (array) array containing the list of values.
  12422. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12423. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12424. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12425. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12426. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12427. * @public
  12428. * @author Nicola Asuni
  12429. * @since 4.8.000 (2009-09-07)
  12430. */
  12431. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12432. if ($x === '') {
  12433. $x = $this->x;
  12434. }
  12435. if ($y === '') {
  12436. $y = $this->y;
  12437. }
  12438. // check page for no-write regions and adapt page margins if necessary
  12439. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12440. if ($js) {
  12441. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  12442. $s = '';
  12443. foreach ($values as $value) {
  12444. if (is_array($value)) {
  12445. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12446. } else {
  12447. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12448. }
  12449. }
  12450. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12451. return;
  12452. }
  12453. // get default style
  12454. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12455. // get annotation data
  12456. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12457. // set additional default values
  12458. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12459. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12460. $popt['da'] = $fontstyle;
  12461. // build appearance stream
  12462. $popt['ap'] = array();
  12463. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12464. $text = '';
  12465. foreach($values as $item) {
  12466. if (is_array($item)) {
  12467. $text .= $item[1]."\n";
  12468. } else {
  12469. $text .= $item."\n";
  12470. }
  12471. }
  12472. $tmpid = $this->startTemplate($w, $h, false);
  12473. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12474. $this->endTemplate();
  12475. --$this->n;
  12476. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12477. unset($this->xobjects[$tmpid]);
  12478. $popt['ap']['n'] .= 'Q EMC';
  12479. // merge options
  12480. $opt = array_merge($popt, $opt);
  12481. // set remaining annotation data
  12482. $opt['Subtype'] = 'Widget';
  12483. $opt['ft'] = 'Ch';
  12484. $opt['t'] = $name;
  12485. $opt['opt'] = $values;
  12486. unset($opt['mk']['ca']);
  12487. unset($opt['mk']['rc']);
  12488. unset($opt['mk']['ac']);
  12489. unset($opt['mk']['i']);
  12490. unset($opt['mk']['ri']);
  12491. unset($opt['mk']['ix']);
  12492. unset($opt['mk']['if']);
  12493. unset($opt['mk']['tp']);
  12494. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12495. if ($this->rtl) {
  12496. $this->x -= $w;
  12497. } else {
  12498. $this->x += $w;
  12499. }
  12500. }
  12501. /**
  12502. * Creates a Combo-box field
  12503. * @param $name (string) field name
  12504. * @param $w (int) width
  12505. * @param $h (int) height
  12506. * @param $values (array) array containing the list of values.
  12507. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12508. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12509. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12510. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12511. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12512. * @public
  12513. * @author Nicola Asuni
  12514. * @since 4.8.000 (2009-09-07)
  12515. */
  12516. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12517. if ($x === '') {
  12518. $x = $this->x;
  12519. }
  12520. if ($y === '') {
  12521. $y = $this->y;
  12522. }
  12523. // check page for no-write regions and adapt page margins if necessary
  12524. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12525. if ($js) {
  12526. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  12527. $s = '';
  12528. foreach ($values as $value) {
  12529. if (is_array($value)) {
  12530. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12531. } else {
  12532. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12533. }
  12534. }
  12535. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12536. return;
  12537. }
  12538. // get default style
  12539. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12540. $prop['Combo'] = true;
  12541. // get annotation data
  12542. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12543. // set additional default options
  12544. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12545. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12546. $popt['da'] = $fontstyle;
  12547. // build appearance stream
  12548. $popt['ap'] = array();
  12549. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12550. $text = '';
  12551. foreach($values as $item) {
  12552. if (is_array($item)) {
  12553. $text .= $item[1]."\n";
  12554. } else {
  12555. $text .= $item."\n";
  12556. }
  12557. }
  12558. $tmpid = $this->startTemplate($w, $h, false);
  12559. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12560. $this->endTemplate();
  12561. --$this->n;
  12562. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12563. unset($this->xobjects[$tmpid]);
  12564. $popt['ap']['n'] .= 'Q EMC';
  12565. // merge options
  12566. $opt = array_merge($popt, $opt);
  12567. // set remaining annotation data
  12568. $opt['Subtype'] = 'Widget';
  12569. $opt['ft'] = 'Ch';
  12570. $opt['t'] = $name;
  12571. $opt['opt'] = $values;
  12572. unset($opt['mk']['ca']);
  12573. unset($opt['mk']['rc']);
  12574. unset($opt['mk']['ac']);
  12575. unset($opt['mk']['i']);
  12576. unset($opt['mk']['ri']);
  12577. unset($opt['mk']['ix']);
  12578. unset($opt['mk']['if']);
  12579. unset($opt['mk']['tp']);
  12580. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12581. if ($this->rtl) {
  12582. $this->x -= $w;
  12583. } else {
  12584. $this->x += $w;
  12585. }
  12586. }
  12587. /**
  12588. * Creates a CheckBox field
  12589. * @param $name (string) field name
  12590. * @param $w (int) width
  12591. * @param $checked (boolean) define the initial state.
  12592. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12593. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12594. * @param $onvalue (string) value to be returned if selected.
  12595. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12596. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12597. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12598. * @public
  12599. * @author Nicola Asuni
  12600. * @since 4.8.000 (2009-09-07)
  12601. */
  12602. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  12603. if ($x === '') {
  12604. $x = $this->x;
  12605. }
  12606. if ($y === '') {
  12607. $y = $this->y;
  12608. }
  12609. // check page for no-write regions and adapt page margins if necessary
  12610. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12611. if ($js) {
  12612. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  12613. return;
  12614. }
  12615. if (!isset($prop['value'])) {
  12616. $prop['value'] = array('Yes');
  12617. }
  12618. // get default style
  12619. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12620. $prop['borderStyle'] = 'inset';
  12621. // get annotation data
  12622. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12623. // set additional default options
  12624. $font = 'zapfdingbats';
  12625. if ($this->pdfa_mode) {
  12626. // all fonts must be embedded
  12627. $font = 'pdfa'.$font;
  12628. }
  12629. $this->AddFont($font);
  12630. $tmpfont = $this->getFontBuffer($font);
  12631. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12632. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12633. $popt['da'] = $fontstyle;
  12634. // build appearance stream
  12635. $popt['ap'] = array();
  12636. $popt['ap']['n'] = array();
  12637. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
  12638. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12639. $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);
  12640. $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);
  12641. // merge options
  12642. $opt = array_merge($popt, $opt);
  12643. // set remaining annotation data
  12644. $opt['Subtype'] = 'Widget';
  12645. $opt['ft'] = 'Btn';
  12646. $opt['t'] = $name;
  12647. if (TCPDF_STATIC::empty_string($onvalue)) {
  12648. $onvalue = 'Yes';
  12649. }
  12650. $opt['opt'] = array($onvalue);
  12651. if ($checked) {
  12652. $opt['v'] = array('/Yes');
  12653. $opt['as'] = 'Yes';
  12654. } else {
  12655. $opt['v'] = array('/Off');
  12656. $opt['as'] = 'Off';
  12657. }
  12658. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12659. if ($this->rtl) {
  12660. $this->x -= $w;
  12661. } else {
  12662. $this->x += $w;
  12663. }
  12664. }
  12665. /**
  12666. * Creates a button field
  12667. * @param $name (string) field name
  12668. * @param $w (int) width
  12669. * @param $h (int) height
  12670. * @param $caption (string) caption.
  12671. * @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.
  12672. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12673. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12674. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12675. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12676. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12677. * @public
  12678. * @author Nicola Asuni
  12679. * @since 4.8.000 (2009-09-07)
  12680. */
  12681. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12682. if ($x === '') {
  12683. $x = $this->x;
  12684. }
  12685. if ($y === '') {
  12686. $y = $this->y;
  12687. }
  12688. // check page for no-write regions and adapt page margins if necessary
  12689. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12690. if ($js) {
  12691. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  12692. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  12693. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  12694. $this->javascript .= 'f'.$name.".highlight='push';\n";
  12695. $this->javascript .= 'f'.$name.".print=false;\n";
  12696. return;
  12697. }
  12698. // get default style
  12699. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12700. $prop['Pushbutton'] = 'true';
  12701. $prop['highlight'] = 'push';
  12702. $prop['display'] = 'display.noPrint';
  12703. // get annotation data
  12704. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12705. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12706. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12707. $popt['da'] = $fontstyle;
  12708. // build appearance stream
  12709. $popt['ap'] = array();
  12710. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12711. $tmpid = $this->startTemplate($w, $h, false);
  12712. $bw = (2 / $this->k); // border width
  12713. $border = array(
  12714. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12715. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  12716. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12717. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  12718. $this->SetFillColor(204);
  12719. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  12720. $this->endTemplate();
  12721. --$this->n;
  12722. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12723. unset($this->xobjects[$tmpid]);
  12724. $popt['ap']['n'] .= 'Q EMC';
  12725. // set additional default options
  12726. if (!isset($popt['mk'])) {
  12727. $popt['mk'] = array();
  12728. }
  12729. $ann_obj_id = ($this->n + 1);
  12730. if (!empty($action) AND !is_array($action)) {
  12731. $ann_obj_id = ($this->n + 2);
  12732. }
  12733. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  12734. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  12735. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  12736. // merge options
  12737. $opt = array_merge($popt, $opt);
  12738. // set remaining annotation data
  12739. $opt['Subtype'] = 'Widget';
  12740. $opt['ft'] = 'Btn';
  12741. $opt['t'] = $caption;
  12742. $opt['v'] = $name;
  12743. if (!empty($action)) {
  12744. if (is_array($action)) {
  12745. // form action options as on section 12.7.5 of PDF32000_2008.
  12746. $opt['aa'] = '/D <<';
  12747. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  12748. foreach ($action AS $key => $val) {
  12749. if (($key == 'S') AND in_array($val, $bmode)) {
  12750. $opt['aa'] .= ' /S /'.$val;
  12751. } elseif (($key == 'F') AND (!empty($val))) {
  12752. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  12753. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  12754. $opt['aa'] .= ' /Fields [';
  12755. foreach ($val AS $field) {
  12756. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  12757. }
  12758. $opt['aa'] .= ']';
  12759. } elseif (($key == 'Flags')) {
  12760. $ff = 0;
  12761. if (is_array($val)) {
  12762. foreach ($val AS $flag) {
  12763. switch ($flag) {
  12764. case 'Include/Exclude': {
  12765. $ff += 1 << 0;
  12766. break;
  12767. }
  12768. case 'IncludeNoValueFields': {
  12769. $ff += 1 << 1;
  12770. break;
  12771. }
  12772. case 'ExportFormat': {
  12773. $ff += 1 << 2;
  12774. break;
  12775. }
  12776. case 'GetMethod': {
  12777. $ff += 1 << 3;
  12778. break;
  12779. }
  12780. case 'SubmitCoordinates': {
  12781. $ff += 1 << 4;
  12782. break;
  12783. }
  12784. case 'XFDF': {
  12785. $ff += 1 << 5;
  12786. break;
  12787. }
  12788. case 'IncludeAppendSaves': {
  12789. $ff += 1 << 6;
  12790. break;
  12791. }
  12792. case 'IncludeAnnotations': {
  12793. $ff += 1 << 7;
  12794. break;
  12795. }
  12796. case 'SubmitPDF': {
  12797. $ff += 1 << 8;
  12798. break;
  12799. }
  12800. case 'CanonicalFormat': {
  12801. $ff += 1 << 9;
  12802. break;
  12803. }
  12804. case 'ExclNonUserAnnots': {
  12805. $ff += 1 << 10;
  12806. break;
  12807. }
  12808. case 'ExclFKey': {
  12809. $ff += 1 << 11;
  12810. break;
  12811. }
  12812. case 'EmbedForm': {
  12813. $ff += 1 << 13;
  12814. break;
  12815. }
  12816. }
  12817. }
  12818. } else {
  12819. $ff = intval($val);
  12820. }
  12821. $opt['aa'] .= ' /Flags '.$ff;
  12822. }
  12823. }
  12824. $opt['aa'] .= ' >>';
  12825. } else {
  12826. // Javascript action or raw action command
  12827. $js_obj_id = $this->addJavascriptObject($action);
  12828. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  12829. }
  12830. }
  12831. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12832. if ($this->rtl) {
  12833. $this->x -= $w;
  12834. } else {
  12835. $this->x += $w;
  12836. }
  12837. }
  12838. // --- END FORMS FIELDS ------------------------------------------------
  12839. /**
  12840. * Add certification signature (DocMDP or UR3)
  12841. * You can set only one signature type
  12842. * @protected
  12843. * @author Nicola Asuni
  12844. * @since 4.6.008 (2009-05-07)
  12845. */
  12846. protected function _putsignature() {
  12847. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  12848. return;
  12849. }
  12850. $sigobjid = ($this->sig_obj_id + 1);
  12851. $out = $this->_getobj($sigobjid)."\n";
  12852. $out .= '<< /Type /Sig';
  12853. $out .= ' /Filter /Adobe.PPKLite';
  12854. $out .= ' /SubFilter /adbe.pkcs7.detached';
  12855. $out .= ' '.TCPDF_STATIC::$byterange_string;
  12856. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  12857. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  12858. $out .= ' /Reference ['; // array of signature reference dictionaries
  12859. $out .= ' << /Type /SigRef';
  12860. if ($this->signature_data['cert_type'] > 0) {
  12861. $out .= ' /TransformMethod /DocMDP';
  12862. $out .= ' /TransformParams <<';
  12863. $out .= ' /Type /TransformParams';
  12864. $out .= ' /P '.$this->signature_data['cert_type'];
  12865. $out .= ' /V /1.2';
  12866. } else {
  12867. $out .= ' /TransformMethod /UR3';
  12868. $out .= ' /TransformParams <<';
  12869. $out .= ' /Type /TransformParams';
  12870. $out .= ' /V /2.2';
  12871. if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
  12872. $out .= ' /Document['.$this->ur['document'].']';
  12873. }
  12874. if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
  12875. $out .= ' /Form['.$this->ur['form'].']';
  12876. }
  12877. if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
  12878. $out .= ' /Signature['.$this->ur['signature'].']';
  12879. }
  12880. if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
  12881. $out .= ' /Annots['.$this->ur['annots'].']';
  12882. }
  12883. if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
  12884. $out .= ' /EF['.$this->ur['ef'].']';
  12885. }
  12886. if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
  12887. $out .= ' /FormEX['.$this->ur['formex'].']';
  12888. }
  12889. }
  12890. $out .= ' >>'; // close TransformParams
  12891. // optional digest data (values must be calculated and replaced later)
  12892. //$out .= ' /Data ********** 0 R';
  12893. //$out .= ' /DigestMethod/MD5';
  12894. //$out .= ' /DigestLocation[********** 34]';
  12895. //$out .= ' /DigestValue<********************************>';
  12896. $out .= ' >>';
  12897. $out .= ' ]'; // end of reference
  12898. }
  12899. if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
  12900. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  12901. }
  12902. if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
  12903. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  12904. }
  12905. if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
  12906. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  12907. }
  12908. if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
  12909. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  12910. }
  12911. $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
  12912. $out .= ' >>';
  12913. $out .= "\n".'endobj';
  12914. $this->_out($out);
  12915. }
  12916. /**
  12917. * Set User's Rights for PDF Reader
  12918. * WARNING: This is experimental and currently do not work.
  12919. * Check the PDF Reference 8.7.1 Transform Methods,
  12920. * Table 8.105 Entries in the UR transform parameters dictionary
  12921. * @param $enable (boolean) if true enable user's rights on PDF reader
  12922. * @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.
  12923. * @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.
  12924. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  12925. * @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.
  12926. * @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
  12927. Names specifying additional embedded-files-related usage rights for the document.
  12928. * @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.
  12929. * @public
  12930. * @author Nicola Asuni
  12931. * @since 2.9.000 (2008-03-26)
  12932. */
  12933. public function setUserRights(
  12934. $enable=true,
  12935. $document='/FullSave',
  12936. $annots='/Create/Delete/Modify/Copy/Import/Export',
  12937. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  12938. $signature='/Modify',
  12939. $ef='/Create/Delete/Modify/Import',
  12940. $formex='') {
  12941. $this->ur['enabled'] = $enable;
  12942. $this->ur['document'] = $document;
  12943. $this->ur['annots'] = $annots;
  12944. $this->ur['form'] = $form;
  12945. $this->ur['signature'] = $signature;
  12946. $this->ur['ef'] = $ef;
  12947. $this->ur['formex'] = $formex;
  12948. if (!$this->sign) {
  12949. $this->setSignature('', '', '', '', 0, array());
  12950. }
  12951. }
  12952. /**
  12953. * Enable document signature (requires the OpenSSL Library).
  12954. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  12955. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12956. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12957. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  12958. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  12959. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  12960. * @param $private_key_password (string) password
  12961. * @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.
  12962. * @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.
  12963. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  12964. * @param $approval (string) Enable approval signature eg. for PDF incremental update
  12965. * @public
  12966. * @author Nicola Asuni
  12967. * @since 4.6.005 (2009-04-24)
  12968. */
  12969. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
  12970. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12971. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12972. // to convert pfx certificate to pem: openssl
  12973. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  12974. $this->sign = true;
  12975. ++$this->n;
  12976. $this->sig_obj_id = $this->n; // signature widget
  12977. ++$this->n; // signature object ($this->sig_obj_id + 1)
  12978. $this->signature_data = array();
  12979. if (strlen($signing_cert) == 0) {
  12980. $this->Error('Please provide a certificate file and password!');
  12981. }
  12982. if (strlen($private_key) == 0) {
  12983. $private_key = $signing_cert;
  12984. }
  12985. $this->signature_data['signcert'] = $signing_cert;
  12986. $this->signature_data['privkey'] = $private_key;
  12987. $this->signature_data['password'] = $private_key_password;
  12988. $this->signature_data['extracerts'] = $extracerts;
  12989. $this->signature_data['cert_type'] = $cert_type;
  12990. $this->signature_data['info'] = $info;
  12991. $this->signature_data['approval'] = $approval;
  12992. }
  12993. /**
  12994. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  12995. * @param $x (float) Abscissa of the upper-left corner.
  12996. * @param $y (float) Ordinate of the upper-left corner.
  12997. * @param $w (float) Width of the signature area.
  12998. * @param $h (float) Height of the signature area.
  12999. * @param $page (int) option page number (if < 0 the current page is used).
  13000. * @param $name (string) Name of the signature.
  13001. * @public
  13002. * @author Nicola Asuni
  13003. * @since 5.3.011 (2010-06-17)
  13004. */
  13005. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13006. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  13007. }
  13008. /**
  13009. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  13010. * @param $x (float) Abscissa of the upper-left corner.
  13011. * @param $y (float) Ordinate of the upper-left corner.
  13012. * @param $w (float) Width of the signature area.
  13013. * @param $h (float) Height of the signature area.
  13014. * @param $page (int) option page number (if < 0 the current page is used).
  13015. * @param $name (string) Name of the signature.
  13016. * @public
  13017. * @author Nicola Asuni
  13018. * @since 5.9.101 (2011-07-06)
  13019. */
  13020. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13021. ++$this->n;
  13022. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  13023. }
  13024. /**
  13025. * Get the array that defines the signature appearance (page and rectangle coordinates).
  13026. * @param $x (float) Abscissa of the upper-left corner.
  13027. * @param $y (float) Ordinate of the upper-left corner.
  13028. * @param $w (float) Width of the signature area.
  13029. * @param $h (float) Height of the signature area.
  13030. * @param $page (int) option page number (if < 0 the current page is used).
  13031. * @param $name (string) Name of the signature.
  13032. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  13033. * @protected
  13034. * @author Nicola Asuni
  13035. * @since 5.9.101 (2011-07-06)
  13036. */
  13037. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13038. $sigapp = array();
  13039. if (($page < 1) OR ($page > $this->numpages)) {
  13040. $sigapp['page'] = $this->page;
  13041. } else {
  13042. $sigapp['page'] = intval($page);
  13043. }
  13044. if (empty($name)) {
  13045. $sigapp['name'] = 'Signature';
  13046. } else {
  13047. $sigapp['name'] = $name;
  13048. }
  13049. $a = $x * $this->k;
  13050. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  13051. $c = $w * $this->k;
  13052. $d = $h * $this->k;
  13053. $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
  13054. return $sigapp;
  13055. }
  13056. /**
  13057. * Enable document timestamping (requires the OpenSSL Library).
  13058. * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
  13059. * Use with digital signature only!
  13060. * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
  13061. * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
  13062. * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
  13063. * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
  13064. * @public
  13065. * @author Richard Stockinger
  13066. * @since 6.0.090 (2014-06-16)
  13067. */
  13068. public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
  13069. $this->tsa_data = array();
  13070. if (!function_exists('curl_init')) {
  13071. $this->Error('Please enable cURL PHP extension!');
  13072. }
  13073. if (strlen($tsa_host) == 0) {
  13074. $this->Error('Please specify the host of Time Stamping Authority (TSA)!');
  13075. }
  13076. $this->tsa_data['tsa_host'] = $tsa_host;
  13077. if (is_file($tsa_username)) {
  13078. $this->tsa_data['tsa_auth'] = $tsa_username;
  13079. } else {
  13080. $this->tsa_data['tsa_username'] = $tsa_username;
  13081. }
  13082. $this->tsa_data['tsa_password'] = $tsa_password;
  13083. $this->tsa_data['tsa_cert'] = $tsa_cert;
  13084. $this->tsa_timestamp = true;
  13085. }
  13086. /**
  13087. * NOT YET IMPLEMENTED
  13088. * Request TSA for a timestamp
  13089. * @param $signature (string) Digital signature as binary string
  13090. * @return (string) Timestamped digital signature
  13091. * @protected
  13092. * @author Richard Stockinger
  13093. * @since 6.0.090 (2014-06-16)
  13094. */
  13095. protected function applyTSA($signature) {
  13096. if (!$this->tsa_timestamp) {
  13097. return $signature;
  13098. }
  13099. //@TODO: implement this feature
  13100. return $signature;
  13101. }
  13102. /**
  13103. * Create a new page group.
  13104. * NOTE: call this function before calling AddPage()
  13105. * @param $page (int) starting group page (leave empty for next page).
  13106. * @public
  13107. * @since 3.0.000 (2008-03-27)
  13108. */
  13109. public function startPageGroup($page='') {
  13110. if (empty($page)) {
  13111. $page = $this->page + 1;
  13112. }
  13113. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  13114. }
  13115. /**
  13116. * Set the starting page number.
  13117. * @param $num (int) Starting page number.
  13118. * @since 5.9.093 (2011-06-16)
  13119. * @public
  13120. */
  13121. public function setStartingPageNumber($num=1) {
  13122. $this->starting_page_number = max(0, intval($num));
  13123. }
  13124. /**
  13125. * Returns the string alias used right align page numbers.
  13126. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  13127. * @return string
  13128. * @since 5.9.099 (2011-06-27)
  13129. * @public
  13130. */
  13131. public function getAliasRightShift() {
  13132. // calculate aproximatively the ratio between widths of aliases and replacements.
  13133. $ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
  13134. $rep = str_repeat(' ', $this->GetNumChars($ref));
  13135. $wrep = $this->GetStringWidth($rep);
  13136. if ($wrep > 0) {
  13137. $wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
  13138. } else {
  13139. $wdiff = 1;
  13140. }
  13141. $sdiff = sprintf('%F', $wdiff);
  13142. $alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
  13143. if ($this->isUnicodeFont()) {
  13144. $alias = '{'.$alias;
  13145. }
  13146. return $alias;
  13147. }
  13148. /**
  13149. * Returns the string alias used for the total number of pages.
  13150. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13151. * This alias will be replaced by the total number of pages in the document.
  13152. * @return string
  13153. * @since 4.0.018 (2008-08-08)
  13154. * @public
  13155. */
  13156. public function getAliasNbPages() {
  13157. if ($this->isUnicodeFont()) {
  13158. return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
  13159. }
  13160. return TCPDF_STATIC::$alias_tot_pages;
  13161. }
  13162. /**
  13163. * Returns the string alias used for the page number.
  13164. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13165. * This alias will be replaced by the page number.
  13166. * @return string
  13167. * @since 4.5.000 (2009-01-02)
  13168. * @public
  13169. */
  13170. public function getAliasNumPage() {
  13171. if ($this->isUnicodeFont()) {
  13172. return '{'.TCPDF_STATIC::$alias_num_page.'}';
  13173. }
  13174. return TCPDF_STATIC::$alias_num_page;
  13175. }
  13176. /**
  13177. * Return the alias for the total number of pages in the current page group.
  13178. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13179. * This alias will be replaced by the total number of pages in this group.
  13180. * @return alias of the current page group
  13181. * @public
  13182. * @since 3.0.000 (2008-03-27)
  13183. */
  13184. public function getPageGroupAlias() {
  13185. if ($this->isUnicodeFont()) {
  13186. return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
  13187. }
  13188. return TCPDF_STATIC::$alias_group_tot_pages;
  13189. }
  13190. /**
  13191. * Return the alias for the page number on the current page group.
  13192. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13193. * This alias will be replaced by the page number (relative to the belonging group).
  13194. * @return alias of the current page group
  13195. * @public
  13196. * @since 4.5.000 (2009-01-02)
  13197. */
  13198. public function getPageNumGroupAlias() {
  13199. if ($this->isUnicodeFont()) {
  13200. return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
  13201. }
  13202. return TCPDF_STATIC::$alias_group_num_page;
  13203. }
  13204. /**
  13205. * Return the current page in the group.
  13206. * @return current page in the group
  13207. * @public
  13208. * @since 3.0.000 (2008-03-27)
  13209. */
  13210. public function getGroupPageNo() {
  13211. return $this->pagegroups[$this->currpagegroup];
  13212. }
  13213. /**
  13214. * Returns the current group page number formatted as a string.
  13215. * @public
  13216. * @since 4.3.003 (2008-11-18)
  13217. * @see PaneNo(), formatPageNumber()
  13218. */
  13219. public function getGroupPageNoFormatted() {
  13220. return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
  13221. }
  13222. /**
  13223. * Returns the current page number formatted as a string.
  13224. * @public
  13225. * @since 4.2.005 (2008-11-06)
  13226. * @see PaneNo(), formatPageNumber()
  13227. */
  13228. public function PageNoFormatted() {
  13229. return TCPDF_STATIC::formatPageNumber($this->PageNo());
  13230. }
  13231. /**
  13232. * Put pdf layers.
  13233. * @protected
  13234. * @since 3.0.000 (2008-03-27)
  13235. */
  13236. protected function _putocg() {
  13237. if (empty($this->pdflayers)) {
  13238. return;
  13239. }
  13240. foreach ($this->pdflayers as $key => $layer) {
  13241. $this->pdflayers[$key]['objid'] = $this->_newobj();
  13242. $out = '<< /Type /OCG';
  13243. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  13244. $out .= ' /Usage <<';
  13245. if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
  13246. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  13247. }
  13248. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  13249. $out .= ' >> >>';
  13250. $out .= "\n".'endobj';
  13251. $this->_out($out);
  13252. }
  13253. }
  13254. /**
  13255. * Start a new pdf layer.
  13256. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  13257. * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
  13258. * @param $view (boolean) Set to true to view this layer.
  13259. * @param $lock (boolean) If true lock the layer
  13260. * @public
  13261. * @since 5.9.102 (2011-07-13)
  13262. */
  13263. public function startLayer($name='', $print=true, $view=true, $lock=true) {
  13264. if ($this->state != 2) {
  13265. return;
  13266. }
  13267. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  13268. if (empty($name)) {
  13269. $name = $layer;
  13270. } else {
  13271. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  13272. }
  13273. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
  13274. $this->openMarkedContent = true;
  13275. $this->_out('/OC /'.$layer.' BDC');
  13276. }
  13277. /**
  13278. * End the current PDF layer.
  13279. * @public
  13280. * @since 5.9.102 (2011-07-13)
  13281. */
  13282. public function endLayer() {
  13283. if ($this->state != 2) {
  13284. return;
  13285. }
  13286. if ($this->openMarkedContent) {
  13287. // close existing open marked-content layer
  13288. $this->_out('EMC');
  13289. $this->openMarkedContent = false;
  13290. }
  13291. }
  13292. /**
  13293. * Set the visibility of the successive elements.
  13294. * This can be useful, for instance, to put a background
  13295. * image or color that will show on screen but won't print.
  13296. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  13297. * @public
  13298. * @since 3.0.000 (2008-03-27)
  13299. */
  13300. public function setVisibility($v) {
  13301. if ($this->state != 2) {
  13302. return;
  13303. }
  13304. $this->endLayer();
  13305. switch($v) {
  13306. case 'print': {
  13307. $this->startLayer('Print', true, false);
  13308. break;
  13309. }
  13310. case 'view':
  13311. case 'screen': {
  13312. $this->startLayer('View', false, true);
  13313. break;
  13314. }
  13315. case 'all': {
  13316. $this->_out('');
  13317. break;
  13318. }
  13319. default: {
  13320. $this->Error('Incorrect visibility: '.$v);
  13321. break;
  13322. }
  13323. }
  13324. }
  13325. /**
  13326. * Add transparency parameters to the current extgstate
  13327. * @param $parms (array) parameters
  13328. * @return the number of extgstates
  13329. * @protected
  13330. * @since 3.0.000 (2008-03-27)
  13331. */
  13332. protected function addExtGState($parms) {
  13333. if ($this->pdfa_mode) {
  13334. // transparencies are not allowed in PDF/A mode
  13335. return;
  13336. }
  13337. // check if this ExtGState already exist
  13338. foreach ($this->extgstates as $i => $ext) {
  13339. if ($ext['parms'] == $parms) {
  13340. if ($this->inxobj) {
  13341. // we are inside an XObject template
  13342. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  13343. }
  13344. // return reference to existing ExtGState
  13345. return $i;
  13346. }
  13347. }
  13348. $n = (count($this->extgstates) + 1);
  13349. $this->extgstates[$n] = array('parms' => $parms);