PageRenderTime 200ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/vendor/dompdf/dompdf/lib/Cpdf.php

https://bitbucket.org/openemr/openemr
PHP | 5122 lines | 3296 code | 772 blank | 1054 comment | 560 complexity | 5b783bb56ccd74d70400cf0c079b683b MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * A PHP class to provide the basic functionality to create a pdf document without
  4. * any requirement for additional modules.
  5. *
  6. * Extended by Orion Richardson to support Unicode / UTF-8 characters using
  7. * TCPDF and others as a guide.
  8. *
  9. * @author Wayne Munro <pdf@ros.co.nz>
  10. * @author Orion Richardson <orionr@yahoo.com>
  11. * @author Helmut Tischer <htischer@weihenstephan.org>
  12. * @author Ryan H. Masten <ryan.masten@gmail.com>
  13. * @author Brian Sweeney <eclecticgeek@gmail.com>
  14. * @author Fabien MĂŠnager <fabien.menager@gmail.com>
  15. * @license Public Domain http://creativecommons.org/licenses/publicdomain/
  16. * @package Cpdf
  17. */
  18. use FontLib\Font;
  19. use FontLib\BinaryStream;
  20. class Cpdf
  21. {
  22. /**
  23. * @var integer The current number of pdf objects in the document
  24. */
  25. public $numObj = 0;
  26. /**
  27. * @var array This array contains all of the pdf objects, ready for final assembly
  28. */
  29. public $objects = array();
  30. /**
  31. * @var integer The objectId (number within the objects array) of the document catalog
  32. */
  33. public $catalogId;
  34. /**
  35. * @var array Array carrying information about the fonts that the system currently knows about
  36. * Used to ensure that a font is not loaded twice, among other things
  37. */
  38. public $fonts = array();
  39. /**
  40. * @var string The default font metrics file to use if no other font has been loaded.
  41. * The path to the directory containing the font metrics should be included
  42. */
  43. public $defaultFont = './fonts/Helvetica.afm';
  44. /**
  45. * @string A record of the current font
  46. */
  47. public $currentFont = '';
  48. /**
  49. * @var string The current base font
  50. */
  51. public $currentBaseFont = '';
  52. /**
  53. * @var integer The number of the current font within the font array
  54. */
  55. public $currentFontNum = 0;
  56. /**
  57. * @var integer
  58. */
  59. public $currentNode;
  60. /**
  61. * @var integer Object number of the current page
  62. */
  63. public $currentPage;
  64. /**
  65. * @var integer Object number of the currently active contents block
  66. */
  67. public $currentContents;
  68. /**
  69. * @var integer Number of fonts within the system
  70. */
  71. public $numFonts = 0;
  72. /**
  73. * @var integer Number of graphic state resources used
  74. */
  75. private $numStates = 0;
  76. /**
  77. * @var array Current color for fill operations, defaults to inactive value,
  78. * all three components should be between 0 and 1 inclusive when active
  79. */
  80. public $currentColor = null;
  81. /**
  82. * @var array Current color for stroke operations (lines etc.)
  83. */
  84. public $currentStrokeColor = null;
  85. /**
  86. * @var string Fill rule (nonzero or evenodd)
  87. */
  88. public $fillRule = "nonzero";
  89. /**
  90. * @var string Current style that lines are drawn in
  91. */
  92. public $currentLineStyle = '';
  93. /**
  94. * @var array Current line transparency (partial graphics state)
  95. */
  96. public $currentLineTransparency = array("mode" => "Normal", "opacity" => 1.0);
  97. /**
  98. * array Current fill transparency (partial graphics state)
  99. */
  100. public $currentFillTransparency = array("mode" => "Normal", "opacity" => 1.0);
  101. /**
  102. * @var array An array which is used to save the state of the document, mainly the colors and styles
  103. * it is used to temporarily change to another state, the change back to what it was before
  104. */
  105. public $stateStack = array();
  106. /**
  107. * @var integer Number of elements within the state stack
  108. */
  109. public $nStateStack = 0;
  110. /**
  111. * @var integer Number of page objects within the document
  112. */
  113. public $numPages = 0;
  114. /**
  115. * @var array Object Id storage stack
  116. */
  117. public $stack = array();
  118. /**
  119. * @var integer Number of elements within the object Id storage stack
  120. */
  121. public $nStack = 0;
  122. /**
  123. * an array which contains information about the objects which are not firmly attached to pages
  124. * these have been added with the addObject function
  125. */
  126. public $looseObjects = array();
  127. /**
  128. * array contains information about how the loose objects are to be added to the document
  129. */
  130. public $addLooseObjects = array();
  131. /**
  132. * @var integer The objectId of the information object for the document
  133. * this contains authorship, title etc.
  134. */
  135. public $infoObject = 0;
  136. /**
  137. * @var integer Number of images being tracked within the document
  138. */
  139. public $numImages = 0;
  140. /**
  141. * @var array An array containing options about the document
  142. * it defaults to turning on the compression of the objects
  143. */
  144. public $options = array('compression' => true);
  145. /**
  146. * @var integer The objectId of the first page of the document
  147. */
  148. public $firstPageId;
  149. /**
  150. * @var integer The object Id of the procset object
  151. */
  152. public $procsetObjectId;
  153. /**
  154. * @var array Store the information about the relationship between font families
  155. * this used so that the code knows which font is the bold version of another font, etc.
  156. * the value of this array is initialised in the constructor function.
  157. */
  158. public $fontFamilies = array();
  159. /**
  160. * @var string Folder for php serialized formats of font metrics files.
  161. * If empty string, use same folder as original metrics files.
  162. * This can be passed in from class creator.
  163. * If this folder does not exist or is not writable, Cpdf will be **much** slower.
  164. * Because of potential trouble with php safe mode, folder cannot be created at runtime.
  165. */
  166. public $fontcache = '';
  167. /**
  168. * @var integer The version of the font metrics cache file.
  169. * This value must be manually incremented whenever the internal font data structure is modified.
  170. */
  171. public $fontcacheVersion = 6;
  172. /**
  173. * @var string Temporary folder.
  174. * If empty string, will attempt system tmp folder.
  175. * This can be passed in from class creator.
  176. */
  177. public $tmp = '';
  178. /**
  179. * @var string Track if the current font is bolded or italicised
  180. */
  181. public $currentTextState = '';
  182. /**
  183. * @var string Messages are stored here during processing, these can be selected afterwards to give some useful debug information
  184. */
  185. public $messages = '';
  186. /**
  187. * @var string The encryption array for the document encryption is stored here
  188. */
  189. public $arc4 = '';
  190. /**
  191. * @var integer The object Id of the encryption information
  192. */
  193. public $arc4_objnum = 0;
  194. /**
  195. * @var string The file identifier, used to uniquely identify a pdf document
  196. */
  197. public $fileIdentifier = '';
  198. /**
  199. * @var boolean A flag to say if a document is to be encrypted or not
  200. */
  201. public $encrypted = false;
  202. /**
  203. * @var string The encryption key for the encryption of all the document content (structure is not encrypted)
  204. */
  205. public $encryptionKey = '';
  206. /**
  207. * @var array Array which forms a stack to keep track of nested callback functions
  208. */
  209. public $callback = array();
  210. /**
  211. * @var integer The number of callback functions in the callback array
  212. */
  213. public $nCallback = 0;
  214. /**
  215. * @var array Store label->id pairs for named destinations, these will be used to replace internal links
  216. * done this way so that destinations can be defined after the location that links to them
  217. */
  218. public $destinations = array();
  219. /**
  220. * @var array Store the stack for the transaction commands, each item in here is a record of the values of all the
  221. * publiciables within the class, so that the user can rollback at will (from each 'start' command)
  222. * note that this includes the objects array, so these can be large.
  223. */
  224. public $checkpoint = '';
  225. /**
  226. * @var array Table of Image origin filenames and image labels which were already added with o_image().
  227. * Allows to merge identical images
  228. */
  229. public $imagelist = array();
  230. /**
  231. * @var boolean Whether the text passed in should be treated as Unicode or just local character set.
  232. */
  233. public $isUnicode = false;
  234. /**
  235. * @var string the JavaScript code of the document
  236. */
  237. public $javascript = '';
  238. /**
  239. * @var boolean whether the compression is possible
  240. */
  241. protected $compressionReady = false;
  242. /**
  243. * @var array Current page size
  244. */
  245. protected $currentPageSize = array("width" => 0, "height" => 0);
  246. /**
  247. * @var array All the chars that will be required in the font subsets
  248. */
  249. protected $stringSubsets = array();
  250. /**
  251. * @var string The target internal encoding
  252. */
  253. static protected $targetEncoding = 'iso-8859-1';
  254. /**
  255. * @var array The list of the core fonts
  256. */
  257. static protected $coreFonts = array(
  258. 'courier',
  259. 'courier-bold',
  260. 'courier-oblique',
  261. 'courier-boldoblique',
  262. 'helvetica',
  263. 'helvetica-bold',
  264. 'helvetica-oblique',
  265. 'helvetica-boldoblique',
  266. 'times-roman',
  267. 'times-bold',
  268. 'times-italic',
  269. 'times-bolditalic',
  270. 'symbol',
  271. 'zapfdingbats'
  272. );
  273. /**
  274. * Class constructor
  275. * This will start a new document
  276. *
  277. * @param array $pageSize Array of 4 numbers, defining the bottom left and upper right corner of the page. first two are normally zero.
  278. * @param boolean $isUnicode Whether text will be treated as Unicode or not.
  279. * @param string $fontcache The font cache folder
  280. * @param string $tmp The temporary folder
  281. */
  282. function __construct($pageSize = array(0, 0, 612, 792), $isUnicode = false, $fontcache = '', $tmp = '')
  283. {
  284. $this->isUnicode = $isUnicode;
  285. $this->fontcache = rtrim($fontcache, DIRECTORY_SEPARATOR."/\\");
  286. $this->tmp = ($tmp !== '' ? $tmp : sys_get_temp_dir());
  287. $this->newDocument($pageSize);
  288. $this->compressionReady = function_exists('gzcompress');
  289. if (in_array('Windows-1252', mb_list_encodings())) {
  290. self::$targetEncoding = 'Windows-1252';
  291. }
  292. // also initialize the font families that are known about already
  293. $this->setFontFamily('init');
  294. // $this->fileIdentifier = md5('xxxxxxxx'.time());
  295. }
  296. /**
  297. * Document object methods (internal use only)
  298. *
  299. * There is about one object method for each type of object in the pdf document
  300. * Each function has the same call list ($id,$action,$options).
  301. * $id = the object ID of the object, or what it is to be if it is being created
  302. * $action = a string specifying the action to be performed, though ALL must support:
  303. * 'new' - create the object with the id $id
  304. * 'out' - produce the output for the pdf object
  305. * $options = optional, a string or array containing the various parameters for the object
  306. *
  307. * These, in conjunction with the output function are the ONLY way for output to be produced
  308. * within the pdf 'file'.
  309. */
  310. /**
  311. * Destination object, used to specify the location for the user to jump to, presently on opening
  312. */
  313. protected function o_destination($id, $action, $options = '')
  314. {
  315. if ($action !== 'new') {
  316. $o = &$this->objects[$id];
  317. }
  318. switch ($action) {
  319. case 'new':
  320. $this->objects[$id] = array('t' => 'destination', 'info' => array());
  321. $tmp = '';
  322. switch ($options['type']) {
  323. case 'XYZ':
  324. case 'FitR':
  325. $tmp = ' ' . $options['p3'] . $tmp;
  326. case 'FitH':
  327. case 'FitV':
  328. case 'FitBH':
  329. case 'FitBV':
  330. $tmp = ' ' . $options['p1'] . ' ' . $options['p2'] . $tmp;
  331. case 'Fit':
  332. case 'FitB':
  333. $tmp = $options['type'] . $tmp;
  334. $this->objects[$id]['info']['string'] = $tmp;
  335. $this->objects[$id]['info']['page'] = $options['page'];
  336. }
  337. break;
  338. case 'out':
  339. $tmp = $o['info'];
  340. $res = "\n$id 0 obj\n" . '[' . $tmp['page'] . ' 0 R /' . $tmp['string'] . "]\nendobj";
  341. return $res;
  342. }
  343. }
  344. /**
  345. * set the viewer preferences
  346. */
  347. protected function o_viewerPreferences($id, $action, $options = '')
  348. {
  349. if ($action !== 'new') {
  350. $o = &$this->objects[$id];
  351. }
  352. switch ($action) {
  353. case 'new':
  354. $this->objects[$id] = array('t' => 'viewerPreferences', 'info' => array());
  355. break;
  356. case 'add':
  357. foreach ($options as $k => $v) {
  358. switch ($k) {
  359. // Boolean keys
  360. case 'HideToolbar':
  361. case 'HideMenubar':
  362. case 'HideWindowUI':
  363. case 'FitWindow':
  364. case 'CenterWindow':
  365. case 'DisplayDocTitle':
  366. case 'PickTrayByPDFSize':
  367. $o['info'][$k] = (bool)$v;
  368. break;
  369. // Integer keys
  370. case 'NumCopies':
  371. $o['info'][$k] = (int)$v;
  372. break;
  373. // Name keys
  374. case 'ViewArea':
  375. case 'ViewClip':
  376. case 'PrintClip':
  377. case 'PrintArea':
  378. $o['info'][$k] = (string)$v;
  379. break;
  380. // Named with limited valid values
  381. case 'NonFullScreenPageMode':
  382. if (!in_array($v, array('UseNone', 'UseOutlines', 'UseThumbs', 'UseOC'))) {
  383. continue;
  384. }
  385. $o['info'][$k] = $v;
  386. break;
  387. case 'Direction':
  388. if (!in_array($v, array('L2R', 'R2L'))) {
  389. continue;
  390. }
  391. $o['info'][$k] = $v;
  392. break;
  393. case 'PrintScaling':
  394. if (!in_array($v, array('None', 'AppDefault'))) {
  395. continue;
  396. }
  397. $o['info'][$k] = $v;
  398. break;
  399. case 'Duplex':
  400. if (!in_array($v, array('None', 'AppDefault'))) {
  401. continue;
  402. }
  403. $o['info'][$k] = $v;
  404. break;
  405. // Integer array
  406. case 'PrintPageRange':
  407. // Cast to integer array
  408. foreach ($v as $vK => $vV) {
  409. $v[$vK] = (int)$vV;
  410. }
  411. $o['info'][$k] = array_values($v);
  412. break;
  413. }
  414. }
  415. break;
  416. case 'out':
  417. $res = "\n$id 0 obj\n<< ";
  418. foreach ($o['info'] as $k => $v) {
  419. if (is_string($v)) {
  420. $v = '/' . $v;
  421. } elseif (is_int($v)) {
  422. $v = (string) $v;
  423. } elseif (is_bool($v)) {
  424. $v = ($v ? 'true' : 'false');
  425. } elseif (is_array($v)) {
  426. $v = '[' . implode(' ', $v) . ']';
  427. }
  428. $res .= "\n/$k $v";
  429. }
  430. $res .= "\n>>\n";
  431. return $res;
  432. }
  433. }
  434. /**
  435. * define the document catalog, the overall controller for the document
  436. */
  437. protected function o_catalog($id, $action, $options = '')
  438. {
  439. if ($action !== 'new') {
  440. $o = &$this->objects[$id];
  441. }
  442. switch ($action) {
  443. case 'new':
  444. $this->objects[$id] = array('t' => 'catalog', 'info' => array());
  445. $this->catalogId = $id;
  446. break;
  447. case 'outlines':
  448. case 'pages':
  449. case 'openHere':
  450. case 'javascript':
  451. $o['info'][$action] = $options;
  452. break;
  453. case 'viewerPreferences':
  454. if (!isset($o['info']['viewerPreferences'])) {
  455. $this->numObj++;
  456. $this->o_viewerPreferences($this->numObj, 'new');
  457. $o['info']['viewerPreferences'] = $this->numObj;
  458. }
  459. $vp = $o['info']['viewerPreferences'];
  460. $this->o_viewerPreferences($vp, 'add', $options);
  461. break;
  462. case 'out':
  463. $res = "\n$id 0 obj\n<< /Type /Catalog";
  464. foreach ($o['info'] as $k => $v) {
  465. switch ($k) {
  466. case 'outlines':
  467. $res .= "\n/Outlines $v 0 R";
  468. break;
  469. case 'pages':
  470. $res .= "\n/Pages $v 0 R";
  471. break;
  472. case 'viewerPreferences':
  473. $res .= "\n/ViewerPreferences $v 0 R";
  474. break;
  475. case 'openHere':
  476. $res .= "\n/OpenAction $v 0 R";
  477. break;
  478. case 'javascript':
  479. $res .= "\n/Names <</JavaScript $v 0 R>>";
  480. break;
  481. }
  482. }
  483. $res .= " >>\nendobj";
  484. return $res;
  485. }
  486. }
  487. /**
  488. * object which is a parent to the pages in the document
  489. */
  490. protected function o_pages($id, $action, $options = '')
  491. {
  492. if ($action !== 'new') {
  493. $o = &$this->objects[$id];
  494. }
  495. switch ($action) {
  496. case 'new':
  497. $this->objects[$id] = array('t' => 'pages', 'info' => array());
  498. $this->o_catalog($this->catalogId, 'pages', $id);
  499. break;
  500. case 'page':
  501. if (!is_array($options)) {
  502. // then it will just be the id of the new page
  503. $o['info']['pages'][] = $options;
  504. } else {
  505. // then it should be an array having 'id','rid','pos', where rid=the page to which this one will be placed relative
  506. // and pos is either 'before' or 'after', saying where this page will fit.
  507. if (isset($options['id']) && isset($options['rid']) && isset($options['pos'])) {
  508. $i = array_search($options['rid'], $o['info']['pages']);
  509. if (isset($o['info']['pages'][$i]) && $o['info']['pages'][$i] == $options['rid']) {
  510. // then there is a match
  511. // make a space
  512. switch ($options['pos']) {
  513. case 'before':
  514. $k = $i;
  515. break;
  516. case 'after':
  517. $k = $i + 1;
  518. break;
  519. default:
  520. $k = -1;
  521. break;
  522. }
  523. if ($k >= 0) {
  524. for ($j = count($o['info']['pages']) - 1; $j >= $k; $j--) {
  525. $o['info']['pages'][$j + 1] = $o['info']['pages'][$j];
  526. }
  527. $o['info']['pages'][$k] = $options['id'];
  528. }
  529. }
  530. }
  531. }
  532. break;
  533. case 'procset':
  534. $o['info']['procset'] = $options;
  535. break;
  536. case 'mediaBox':
  537. $o['info']['mediaBox'] = $options;
  538. // which should be an array of 4 numbers
  539. $this->currentPageSize = array('width' => $options[2], 'height' => $options[3]);
  540. break;
  541. case 'font':
  542. $o['info']['fonts'][] = array('objNum' => $options['objNum'], 'fontNum' => $options['fontNum']);
  543. break;
  544. case 'extGState':
  545. $o['info']['extGStates'][] = array('objNum' => $options['objNum'], 'stateNum' => $options['stateNum']);
  546. break;
  547. case 'xObject':
  548. $o['info']['xObjects'][] = array('objNum' => $options['objNum'], 'label' => $options['label']);
  549. break;
  550. case 'out':
  551. if (count($o['info']['pages'])) {
  552. $res = "\n$id 0 obj\n<< /Type /Pages\n/Kids [";
  553. foreach ($o['info']['pages'] as $v) {
  554. $res .= "$v 0 R\n";
  555. }
  556. $res .= "]\n/Count " . count($this->objects[$id]['info']['pages']);
  557. if ((isset($o['info']['fonts']) && count($o['info']['fonts'])) ||
  558. isset($o['info']['procset']) ||
  559. (isset($o['info']['extGStates']) && count($o['info']['extGStates']))
  560. ) {
  561. $res .= "\n/Resources <<";
  562. if (isset($o['info']['procset'])) {
  563. $res .= "\n/ProcSet " . $o['info']['procset'] . " 0 R";
  564. }
  565. if (isset($o['info']['fonts']) && count($o['info']['fonts'])) {
  566. $res .= "\n/Font << ";
  567. foreach ($o['info']['fonts'] as $finfo) {
  568. $res .= "\n/F" . $finfo['fontNum'] . " " . $finfo['objNum'] . " 0 R";
  569. }
  570. $res .= "\n>>";
  571. }
  572. if (isset($o['info']['xObjects']) && count($o['info']['xObjects'])) {
  573. $res .= "\n/XObject << ";
  574. foreach ($o['info']['xObjects'] as $finfo) {
  575. $res .= "\n/" . $finfo['label'] . " " . $finfo['objNum'] . " 0 R";
  576. }
  577. $res .= "\n>>";
  578. }
  579. if (isset($o['info']['extGStates']) && count($o['info']['extGStates'])) {
  580. $res .= "\n/ExtGState << ";
  581. foreach ($o['info']['extGStates'] as $gstate) {
  582. $res .= "\n/GS" . $gstate['stateNum'] . " " . $gstate['objNum'] . " 0 R";
  583. }
  584. $res .= "\n>>";
  585. }
  586. $res .= "\n>>";
  587. if (isset($o['info']['mediaBox'])) {
  588. $tmp = $o['info']['mediaBox'];
  589. $res .= "\n/MediaBox [" . sprintf(
  590. '%.3F %.3F %.3F %.3F',
  591. $tmp[0],
  592. $tmp[1],
  593. $tmp[2],
  594. $tmp[3]
  595. ) . ']';
  596. }
  597. }
  598. $res .= "\n >>\nendobj";
  599. } else {
  600. $res = "\n$id 0 obj\n<< /Type /Pages\n/Count 0\n>>\nendobj";
  601. }
  602. return $res;
  603. }
  604. }
  605. /**
  606. * define the outlines in the doc, empty for now
  607. */
  608. protected function o_outlines($id, $action, $options = '')
  609. {
  610. if ($action !== 'new') {
  611. $o = &$this->objects[$id];
  612. }
  613. switch ($action) {
  614. case 'new':
  615. $this->objects[$id] = array('t' => 'outlines', 'info' => array('outlines' => array()));
  616. $this->o_catalog($this->catalogId, 'outlines', $id);
  617. break;
  618. case 'outline':
  619. $o['info']['outlines'][] = $options;
  620. break;
  621. case 'out':
  622. if (count($o['info']['outlines'])) {
  623. $res = "\n$id 0 obj\n<< /Type /Outlines /Kids [";
  624. foreach ($o['info']['outlines'] as $v) {
  625. $res .= "$v 0 R ";
  626. }
  627. $res .= "] /Count " . count($o['info']['outlines']) . " >>\nendobj";
  628. } else {
  629. $res = "\n$id 0 obj\n<< /Type /Outlines /Count 0 >>\nendobj";
  630. }
  631. return $res;
  632. }
  633. }
  634. /**
  635. * an object to hold the font description
  636. */
  637. protected function o_font($id, $action, $options = '')
  638. {
  639. if ($action !== 'new') {
  640. $o = &$this->objects[$id];
  641. }
  642. switch ($action) {
  643. case 'new':
  644. $this->objects[$id] = array(
  645. 't' => 'font',
  646. 'info' => array(
  647. 'name' => $options['name'],
  648. 'fontFileName' => $options['fontFileName'],
  649. 'SubType' => 'Type1'
  650. )
  651. );
  652. $fontNum = $this->numFonts;
  653. $this->objects[$id]['info']['fontNum'] = $fontNum;
  654. // deal with the encoding and the differences
  655. if (isset($options['differences'])) {
  656. // then we'll need an encoding dictionary
  657. $this->numObj++;
  658. $this->o_fontEncoding($this->numObj, 'new', $options);
  659. $this->objects[$id]['info']['encodingDictionary'] = $this->numObj;
  660. } else {
  661. if (isset($options['encoding'])) {
  662. // we can specify encoding here
  663. switch ($options['encoding']) {
  664. case 'WinAnsiEncoding':
  665. case 'MacRomanEncoding':
  666. case 'MacExpertEncoding':
  667. $this->objects[$id]['info']['encoding'] = $options['encoding'];
  668. break;
  669. case 'none':
  670. break;
  671. default:
  672. $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
  673. break;
  674. }
  675. } else {
  676. $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
  677. }
  678. }
  679. if ($this->fonts[$options['fontFileName']]['isUnicode']) {
  680. // For Unicode fonts, we need to incorporate font data into
  681. // sub-sections that are linked from the primary font section.
  682. // Look at o_fontGIDtoCID and o_fontDescendentCID functions
  683. // for more information.
  684. //
  685. // All of this code is adapted from the excellent changes made to
  686. // transform FPDF to TCPDF (http://tcpdf.sourceforge.net/)
  687. $toUnicodeId = ++$this->numObj;
  688. $this->o_contents($toUnicodeId, 'new', 'raw');
  689. $this->objects[$id]['info']['toUnicode'] = $toUnicodeId;
  690. $stream = <<<EOT
  691. /CIDInit /ProcSet findresource begin
  692. 12 dict begin
  693. begincmap
  694. /CIDSystemInfo
  695. <</Registry (Adobe)
  696. /Ordering (UCS)
  697. /Supplement 0
  698. >> def
  699. /CMapName /Adobe-Identity-UCS def
  700. /CMapType 2 def
  701. 1 begincodespacerange
  702. <0000> <FFFF>
  703. endcodespacerange
  704. 1 beginbfrange
  705. <0000> <FFFF> <0000>
  706. endbfrange
  707. endcmap
  708. CMapName currentdict /CMap defineresource pop
  709. end
  710. end
  711. EOT;
  712. $res = "<</Length " . mb_strlen($stream, '8bit') . " >>\n";
  713. $res .= "stream\n" . $stream . "\nendstream";
  714. $this->objects[$toUnicodeId]['c'] = $res;
  715. $cidFontId = ++$this->numObj;
  716. $this->o_fontDescendentCID($cidFontId, 'new', $options);
  717. $this->objects[$id]['info']['cidFont'] = $cidFontId;
  718. }
  719. // also tell the pages node about the new font
  720. $this->o_pages($this->currentNode, 'font', array('fontNum' => $fontNum, 'objNum' => $id));
  721. break;
  722. case 'add':
  723. foreach ($options as $k => $v) {
  724. switch ($k) {
  725. case 'BaseFont':
  726. $o['info']['name'] = $v;
  727. break;
  728. case 'FirstChar':
  729. case 'LastChar':
  730. case 'Widths':
  731. case 'FontDescriptor':
  732. case 'SubType':
  733. $this->addMessage('o_font ' . $k . " : " . $v);
  734. $o['info'][$k] = $v;
  735. break;
  736. }
  737. }
  738. // pass values down to descendent font
  739. if (isset($o['info']['cidFont'])) {
  740. $this->o_fontDescendentCID($o['info']['cidFont'], 'add', $options);
  741. }
  742. break;
  743. case 'out':
  744. if ($this->fonts[$this->objects[$id]['info']['fontFileName']]['isUnicode']) {
  745. // For Unicode fonts, we need to incorporate font data into
  746. // sub-sections that are linked from the primary font section.
  747. // Look at o_fontGIDtoCID and o_fontDescendentCID functions
  748. // for more information.
  749. //
  750. // All of this code is adapted from the excellent changes made to
  751. // transform FPDF to TCPDF (http://tcpdf.sourceforge.net/)
  752. $res = "\n$id 0 obj\n<</Type /Font\n/Subtype /Type0\n";
  753. $res .= "/BaseFont /" . $o['info']['name'] . "\n";
  754. // The horizontal identity mapping for 2-byte CIDs; may be used
  755. // with CIDFonts using any Registry, Ordering, and Supplement values.
  756. $res .= "/Encoding /Identity-H\n";
  757. $res .= "/DescendantFonts [" . $o['info']['cidFont'] . " 0 R]\n";
  758. $res .= "/ToUnicode " . $o['info']['toUnicode'] . " 0 R\n";
  759. $res .= ">>\n";
  760. $res .= "endobj";
  761. } else {
  762. $res = "\n$id 0 obj\n<< /Type /Font\n/Subtype /" . $o['info']['SubType'] . "\n";
  763. $res .= "/Name /F" . $o['info']['fontNum'] . "\n";
  764. $res .= "/BaseFont /" . $o['info']['name'] . "\n";
  765. if (isset($o['info']['encodingDictionary'])) {
  766. // then place a reference to the dictionary
  767. $res .= "/Encoding " . $o['info']['encodingDictionary'] . " 0 R\n";
  768. } else {
  769. if (isset($o['info']['encoding'])) {
  770. // use the specified encoding
  771. $res .= "/Encoding /" . $o['info']['encoding'] . "\n";
  772. }
  773. }
  774. if (isset($o['info']['FirstChar'])) {
  775. $res .= "/FirstChar " . $o['info']['FirstChar'] . "\n";
  776. }
  777. if (isset($o['info']['LastChar'])) {
  778. $res .= "/LastChar " . $o['info']['LastChar'] . "\n";
  779. }
  780. if (isset($o['info']['Widths'])) {
  781. $res .= "/Widths " . $o['info']['Widths'] . " 0 R\n";
  782. }
  783. if (isset($o['info']['FontDescriptor'])) {
  784. $res .= "/FontDescriptor " . $o['info']['FontDescriptor'] . " 0 R\n";
  785. }
  786. $res .= ">>\n";
  787. $res .= "endobj";
  788. }
  789. return $res;
  790. }
  791. }
  792. /**
  793. * a font descriptor, needed for including additional fonts
  794. */
  795. protected function o_fontDescriptor($id, $action, $options = '')
  796. {
  797. if ($action !== 'new') {
  798. $o = &$this->objects[$id];
  799. }
  800. switch ($action) {
  801. case 'new':
  802. $this->objects[$id] = array('t' => 'fontDescriptor', 'info' => $options);
  803. break;
  804. case 'out':
  805. $res = "\n$id 0 obj\n<< /Type /FontDescriptor\n";
  806. foreach ($o['info'] as $label => $value) {
  807. switch ($label) {
  808. case 'Ascent':
  809. case 'CapHeight':
  810. case 'Descent':
  811. case 'Flags':
  812. case 'ItalicAngle':
  813. case 'StemV':
  814. case 'AvgWidth':
  815. case 'Leading':
  816. case 'MaxWidth':
  817. case 'MissingWidth':
  818. case 'StemH':
  819. case 'XHeight':
  820. case 'CharSet':
  821. if (mb_strlen($value, '8bit')) {
  822. $res .= "/$label $value\n";
  823. }
  824. break;
  825. case 'FontFile':
  826. case 'FontFile2':
  827. case 'FontFile3':
  828. $res .= "/$label $value 0 R\n";
  829. break;
  830. case 'FontBBox':
  831. $res .= "/$label [$value[0] $value[1] $value[2] $value[3]]\n";
  832. break;
  833. case 'FontName':
  834. $res .= "/$label /$value\n";
  835. break;
  836. }
  837. }
  838. $res .= ">>\nendobj";
  839. return $res;
  840. }
  841. }
  842. /**
  843. * the font encoding
  844. */
  845. protected function o_fontEncoding($id, $action, $options = '')
  846. {
  847. if ($action !== 'new') {
  848. $o = &$this->objects[$id];
  849. }
  850. switch ($action) {
  851. case 'new':
  852. // the options array should contain 'differences' and maybe 'encoding'
  853. $this->objects[$id] = array('t' => 'fontEncoding', 'info' => $options);
  854. break;
  855. case 'out':
  856. $res = "\n$id 0 obj\n<< /Type /Encoding\n";
  857. if (!isset($o['info']['encoding'])) {
  858. $o['info']['encoding'] = 'WinAnsiEncoding';
  859. }
  860. if ($o['info']['encoding'] !== 'none') {
  861. $res .= "/BaseEncoding /" . $o['info']['encoding'] . "\n";
  862. }
  863. $res .= "/Differences \n[";
  864. $onum = -100;
  865. foreach ($o['info']['differences'] as $num => $label) {
  866. if ($num != $onum + 1) {
  867. // we cannot make use of consecutive numbering
  868. $res .= "\n$num /$label";
  869. } else {
  870. $res .= " /$label";
  871. }
  872. $onum = $num;
  873. }
  874. $res .= "\n]\n>>\nendobj";
  875. return $res;
  876. }
  877. }
  878. /**
  879. * a descendent cid font, needed for unicode fonts
  880. */
  881. protected function o_fontDescendentCID($id, $action, $options = '')
  882. {
  883. if ($action !== 'new') {
  884. $o = &$this->objects[$id];
  885. }
  886. switch ($action) {
  887. case 'new':
  888. $this->objects[$id] = array('t' => 'fontDescendentCID', 'info' => $options);
  889. // we need a CID system info section
  890. $cidSystemInfoId = ++$this->numObj;
  891. $this->o_contents($cidSystemInfoId, 'new', 'raw');
  892. $this->objects[$id]['info']['cidSystemInfo'] = $cidSystemInfoId;
  893. $res = "<</Registry (Adobe)\n"; // A string identifying an issuer of character collections
  894. $res .= "/Ordering (UCS)\n"; // A string that uniquely names a character collection issued by a specific registry
  895. $res .= "/Supplement 0\n"; // The supplement number of the character collection.
  896. $res .= ">>";
  897. $this->objects[$cidSystemInfoId]['c'] = $res;
  898. // and a CID to GID map
  899. $cidToGidMapId = ++$this->numObj;
  900. $this->o_fontGIDtoCIDMap($cidToGidMapId, 'new', $options);
  901. $this->objects[$id]['info']['cidToGidMap'] = $cidToGidMapId;
  902. break;
  903. case 'add':
  904. foreach ($options as $k => $v) {
  905. switch ($k) {
  906. case 'BaseFont':
  907. $o['info']['name'] = $v;
  908. break;
  909. case 'FirstChar':
  910. case 'LastChar':
  911. case 'MissingWidth':
  912. case 'FontDescriptor':
  913. case 'SubType':
  914. $this->addMessage("o_fontDescendentCID $k : $v");
  915. $o['info'][$k] = $v;
  916. break;
  917. }
  918. }
  919. // pass values down to cid to gid map
  920. $this->o_fontGIDtoCIDMap($o['info']['cidToGidMap'], 'add', $options);
  921. break;
  922. case 'out':
  923. $res = "\n$id 0 obj\n";
  924. $res .= "<</Type /Font\n";
  925. $res .= "/Subtype /CIDFontType2\n";
  926. $res .= "/BaseFont /" . $o['info']['name'] . "\n";
  927. $res .= "/CIDSystemInfo " . $o['info']['cidSystemInfo'] . " 0 R\n";
  928. // if (isset($o['info']['FirstChar'])) {
  929. // $res.= "/FirstChar ".$o['info']['FirstChar']."\n";
  930. // }
  931. // if (isset($o['info']['LastChar'])) {
  932. // $res.= "/LastChar ".$o['info']['LastChar']."\n";
  933. // }
  934. if (isset($o['info']['FontDescriptor'])) {
  935. $res .= "/FontDescriptor " . $o['info']['FontDescriptor'] . " 0 R\n";
  936. }
  937. if (isset($o['info']['MissingWidth'])) {
  938. $res .= "/DW " . $o['info']['MissingWidth'] . "\n";
  939. }
  940. if (isset($o['info']['fontFileName']) && isset($this->fonts[$o['info']['fontFileName']]['CIDWidths'])) {
  941. $cid_widths = &$this->fonts[$o['info']['fontFileName']]['CIDWidths'];
  942. $w = '';
  943. foreach ($cid_widths as $cid => $width) {
  944. $w .= "$cid [$width] ";
  945. }
  946. $res .= "/W [$w]\n";
  947. }
  948. $res .= "/CIDToGIDMap " . $o['info']['cidToGidMap'] . " 0 R\n";
  949. $res .= ">>\n";
  950. $res .= "endobj";
  951. return $res;
  952. }
  953. }
  954. /**
  955. * a font glyph to character map, needed for unicode fonts
  956. */
  957. protected function o_fontGIDtoCIDMap($id, $action, $options = '')
  958. {
  959. if ($action !== 'new') {
  960. $o = &$this->objects[$id];
  961. }
  962. switch ($action) {
  963. case 'new':
  964. $this->objects[$id] = array('t' => 'fontGIDtoCIDMap', 'info' => $options);
  965. break;
  966. case 'out':
  967. $res = "\n$id 0 obj\n";
  968. $fontFileName = $o['info']['fontFileName'];
  969. $tmp = $this->fonts[$fontFileName]['CIDtoGID'] = base64_decode($this->fonts[$fontFileName]['CIDtoGID']);
  970. $compressed = isset($this->fonts[$fontFileName]['CIDtoGID_Compressed']) &&
  971. $this->fonts[$fontFileName]['CIDtoGID_Compressed'];
  972. if (!$compressed && isset($o['raw'])) {
  973. $res .= $tmp;
  974. } else {
  975. $res .= "<<";
  976. if (!$compressed && $this->compressionReady && $this->options['compression']) {
  977. // then implement ZLIB based compression on this content stream
  978. $compressed = true;
  979. $tmp = gzcompress($tmp, 6);
  980. }
  981. if ($compressed) {
  982. $res .= "\n/Filter /FlateDecode";
  983. }
  984. $res .= "\n/Length " . mb_strlen($tmp, '8bit') . ">>\nstream\n$tmp\nendstream";
  985. }
  986. $res .= "\nendobj";
  987. return $res;
  988. }
  989. }
  990. /**
  991. * the document procset, solves some problems with printing to old PS printers
  992. */
  993. protected function o_procset($id, $action, $options = '')
  994. {
  995. if ($action !== 'new') {
  996. $o = &$this->objects[$id];
  997. }
  998. switch ($action) {
  999. case 'new':
  1000. $this->objects[$id] = array('t' => 'procset', 'info' => array('PDF' => 1, 'Text' => 1));
  1001. $this->o_pages($this->currentNode, 'procset', $id);
  1002. $this->procsetObjectId = $id;
  1003. break;
  1004. case 'add':
  1005. // this is to add new items to the procset list, despite the fact that this is considered
  1006. // obsolete, the items are required for printing to some postscript printers
  1007. switch ($options) {
  1008. case 'ImageB':
  1009. case 'ImageC':
  1010. case 'ImageI':
  1011. $o['info'][$options] = 1;
  1012. break;
  1013. }
  1014. break;
  1015. case 'out':
  1016. $res = "\n$id 0 obj\n[";
  1017. foreach ($o['info'] as $label => $val) {
  1018. $res .= "/$label ";
  1019. }
  1020. $res .= "]\nendobj";
  1021. return $res;
  1022. }
  1023. }
  1024. /**
  1025. * define the document information
  1026. */
  1027. protected function o_info($id, $action, $options = '')
  1028. {
  1029. if ($action !== 'new') {
  1030. $o = &$this->objects[$id];
  1031. }
  1032. switch ($action) {
  1033. case 'new':
  1034. $this->infoObject = $id;
  1035. $date = 'D:' . @date('Ymd');
  1036. $this->objects[$id] = array(
  1037. 't' => 'info',
  1038. 'info' => array(
  1039. 'Producer' => 'CPDF (dompdf)',
  1040. 'CreationDate' => $date
  1041. )
  1042. );
  1043. break;
  1044. case 'Title':
  1045. case 'Author':
  1046. case 'Subject':
  1047. case 'Keywords':
  1048. case 'Creator':
  1049. case 'Producer':
  1050. case 'CreationDate':
  1051. case 'ModDate':
  1052. case 'Trapped':
  1053. $o['info'][$action] = $options;
  1054. break;
  1055. case 'out':
  1056. if ($this->encrypted) {
  1057. $this->encryptInit($id);
  1058. }
  1059. $res = "\n$id 0 obj\n<<\n";
  1060. foreach ($o['info'] as $k => $v) {
  1061. $res .= "/$k (";
  1062. if ($this->encrypted) {
  1063. $v = $this->ARC4($v);
  1064. } // dates must be outputted as-is, without Unicode transformations
  1065. elseif (!in_array($k, array('CreationDate', 'ModDate'))) {
  1066. $v = $this->filterText($v);
  1067. }
  1068. $res .= $v;
  1069. $res .= ")\n";
  1070. }
  1071. $res .= ">>\nendobj";
  1072. return $res;
  1073. }
  1074. }
  1075. /**
  1076. * an action object, used to link to URLS initially
  1077. */
  1078. protected function o_action($id, $action, $options = '')
  1079. {
  1080. if ($action !== 'new') {
  1081. $o = &$this->objects[$id];
  1082. }
  1083. switch ($action) {
  1084. case 'new':
  1085. if (is_array($options)) {
  1086. $this->objects[$id] = array('t' => 'action', 'info' => $options, 'type' => $options['type']);
  1087. } else {
  1088. // then assume a URI action
  1089. $this->objects[$id] = array('t' => 'action', 'info' => $options, 'type' => 'URI');
  1090. }
  1091. break;
  1092. case 'out':
  1093. if ($this->encrypted) {
  1094. $this->encryptInit($id);
  1095. }
  1096. $res = "\n$id 0 obj\n<< /Type /Action";
  1097. switch ($o['type']) {
  1098. case 'ilink':
  1099. if (!isset($this->destinations[(string)$o['info']['label']])) {
  1100. break;
  1101. }
  1102. // there will be an 'label' setting, this is the name of the destination
  1103. $res .= "\n/S /GoTo\n/D " . $this->destinations[(string)$o['info']['label']] . " 0 R";
  1104. break;
  1105. case 'URI':
  1106. $res .= "\n/S /URI\n/URI (";
  1107. if ($this->encrypted) {
  1108. $res .= $this->filterText($this->ARC4($o['info']), true, false);
  1109. } else {
  1110. $res .= $this->filterText($o['info'], true, false);
  1111. }
  1112. $res .= ")";
  1113. break;
  1114. }
  1115. $res .= "\n>>\nendobj";
  1116. return $res;
  1117. }
  1118. }
  1119. /**
  1120. * an annotation object, this will add an annotation to the current page.
  1121. * initially will support just link annotations
  1122. */
  1123. protected function o_annotation($id, $action, $options = '')
  1124. {
  1125. if ($action !== 'new') {
  1126. $o = &$this->objects[$id];
  1127. }
  1128. switch ($action) {
  1129. case 'new':
  1130. // add the annotation to the current page
  1131. $pageId = $this->currentPage;
  1132. $this->o_page($pageId, 'annot', $id);
  1133. // and add the action object which is going to be required
  1134. switch ($options['type']) {
  1135. case 'link':
  1136. $this->objects[$id] = array('t' => 'annotation', 'info' => $options);
  1137. $this->numObj++;
  1138. $this->o_action($this->numObj, 'new', $options['url']);
  1139. $this->objects[$id]['info']['actionId'] = $this->numObj;
  1140. break;
  1141. case 'ilink':
  1142. // this is to a named internal link
  1143. $label = $options['label'];
  1144. $this->objects[$id] = array('t' => 'annotation', 'info' => $options);
  1145. $this->numObj++;
  1146. $this->o_action($this->numObj, 'new', array('type' => 'ilink', 'label' => $label));
  1147. $this->objects[$id]['info']['actionId'] = $this->numObj;
  1148. break;
  1149. }
  1150. break;
  1151. case 'out':
  1152. $res = "\n$id 0 obj\n<< /Type /Annot";
  1153. switch ($o['info']['type']) {
  1154. case 'link':
  1155. case 'ilink':
  1156. $res .= "\n/Subtype /Link";
  1157. break;
  1158. }
  1159. $res .= "\n/A " . $o['info']['actionId'] . " 0 R";
  1160. $res .= "\n/Border [0 0 0]";
  1161. $res .= "\n/H /I";
  1162. $res .= "\n/Rect [ ";
  1163. foreach ($o['info']['rect'] as $v) {
  1164. $res .= sprintf("%.4F ", $v);
  1165. }
  1166. $res .= "]";
  1167. $res .= "\n>>\nendobj";
  1168. return $res;
  1169. }
  1170. }
  1171. /**
  1172. * a page object, it also creates a contents object to hold its contents
  1173. */
  1174. protected function o_page($id, $action, $options = '')
  1175. {
  1176. if ($action !== 'new') {
  1177. $o = &$this->objects[$id];
  1178. }
  1179. switch ($action) {
  1180. case 'new':
  1181. $this->numPages++;
  1182. $this->objects[$id] = array(
  1183. 't' => 'page',
  1184. 'info' => array(
  1185. 'parent' => $this->currentNode,
  1186. 'pageNum' => $this->numPages,
  1187. 'mediaBox' => $this->objects[$this->currentNode]['info']['mediaBox']
  1188. )
  1189. );
  1190. if (is_array($options)) {
  1191. // then this must be a page insertion, array should contain 'rid','pos'=[before|after]
  1192. $options['id'] = $id;
  1193. $this->o_pages($this->currentNode, 'page', $options);
  1194. } else {
  1195. $this->o_pages($this->currentNode, 'page', $id);
  1196. }
  1197. $this->currentPage = $id;
  1198. //make a contents object to go with this page
  1199. $this->numObj++;
  1200. $this->o_contents($this->numObj, 'new', $id);
  1201. $this->currentContents = $this->numObj;
  1202. $this->objects[$id]['info']['contents'] = array();
  1203. $this->objects[$id]['info']['contents'][] = $this->numObj;
  1204. $match = ($this->numPages % 2 ? 'odd' : 'even');
  1205. foreach ($this->addLooseObjects as $oId => $target) {
  1206. if ($target === 'all' || $match === $target) {
  1207. $this->objects[$id]['info']['contents'][] = $oId;
  1208. }
  1209. }
  1210. break;
  1211. case 'content':
  1212. $o['info']['contents'][] = $options;
  1213. break;
  1214. case 'annot':
  1215. // add an annotation to this page
  1216. if (!isset($o['info']['annot'])) {
  1217. $o['info']['annot'] = array();
  1218. }
  1219. // $options should contain the id of the annotation dictionary
  1220. $o['info']['annot'][] = $options;
  1221. break;
  1222. case 'out':
  1223. $res = "\n$id 0 obj\n<< /Type /Page";
  1224. if (isset($o['info']['mediaBox'])) {
  1225. $tmp = $o['info']['mediaBox'];
  1226. $res .= "\n/MediaBox [" . sprintf(
  1227. '%.3F %.3F %.3F %.3F',
  1228. $tmp[0],
  1229. $tmp[1],
  1230. $tmp[2],
  1231. $tmp[3]
  1232. ) . ']';
  1233. }
  1234. $res .= "\n/Parent " . $o['info']['parent'] . " 0 R";
  1235. if (isset($o['info']['annot'])) {
  1236. $res .= "\n/Annots [";
  1237. foreach ($o['info']['annot'] as $aId) {
  1238. $res .= " $aId 0 R";
  1239. }
  1240. $res .= " ]";
  1241. }
  1242. $count = count($o['info']['contents']);
  1243. if ($count == 1) {
  1244. $res .= "\n/Contents " . $o['info']['contents'][0] . " 0 R";
  1245. } else {
  1246. if ($count > 1) {
  1247. $res .= "\n/Contents [\n";
  1248. // reverse the page contents so added objects are below normal content
  1249. //foreach (array_reverse($o['info']['contents']) as $cId) {
  1250. // Back to normal now that I've got transparency working --Benj
  1251. foreach ($o['info']['contents'] as $cId) {
  1252. $res .= "$cId 0 R\n";
  1253. }
  1254. $res .= "]";
  1255. }
  1256. }
  1257. $res .= "\n>>\nendobj";
  1258. return $res;
  1259. }
  1260. }
  1261. /**
  1262. * the contents objects hold all of the content which appears on pages
  1263. */
  1264. protected function o_contents($id, $action, $options = '')
  1265. {
  1266. if ($action !== 'new') {
  1267. $o = &$this->objects[$id];
  1268. }
  1269. switch ($action) {
  1270. case 'new':
  1271. $this->objects[$id] = array('t' => 'contents', 'c' => '', 'info' => array());
  1272. if (mb_strlen($options, '8bit') && intval($options)) {
  1273. // then this contents is the primary for a page
  1274. $this->objects[$id]['onPage'] = $options;
  1275. } else {
  1276. if ($options === 'raw') {
  1277. // then this page contains some other type of system object
  1278. $this->objects[$id]['raw'] = 1;
  1279. }
  1280. }
  1281. break;
  1282. case 'add':
  1283. // add more options to the declaration
  1284. foreach ($options as $k => $v) {
  1285. $o['info'][$k] = $v;
  1286. }
  1287. case 'out':
  1288. $tmp = $o['c'];
  1289. $res = "\n$id 0 obj\n";
  1290. if (isset($this->objects[$id]['raw'])) {
  1291. $res .= $tmp;
  1292. } else {
  1293. $res .= "<<";
  1294. if ($this->compressionReady && $this->options['compression']) {
  1295. // then implement ZLIB based compression on this content stream
  1296. $res .= " /Filter /FlateDecode";
  1297. $tmp = gzcompress($tmp, 6);
  1298. }
  1299. if ($this->encrypted) {
  1300. $this->encryptInit($id);
  1301. $tmp = $this->ARC4($tmp);
  1302. }
  1303. foreach ($o['info'] as $k => $v) {
  1304. $res .= "\n/$k $v";
  1305. }
  1306. $res .= "\n/Length " . mb_strlen($tmp, '8bit') . " >>\nstream\n$tmp\nendstream";
  1307. }
  1308. $res .= "\nendobj";
  1309. return $res;
  1310. }
  1311. }
  1312. protected function o_embedjs($id, $action)
  1313. {
  1314. if ($action !== 'new') {
  1315. $o = &$this->objects[$id];
  1316. }
  1317. switch ($action) {
  1318. case 'new':
  1319. $this->objects[$id] = array(
  1320. 't' => 'embedjs',
  1321. 'info' => array(
  1322. 'Names' => '[(EmbeddedJS) ' . ($id + 1) . ' 0 R]'
  1323. )
  1324. );
  1325. break;
  1326. case 'out':
  1327. $res = "\n$id 0 obj\n<< ";
  1328. foreach ($o['info'] as $k => $v) {
  1329. $res .= "\n/$k $v";
  1330. }
  1331. $res .= "\n>>\nendobj";
  1332. return $res;
  1333. }
  1334. }
  1335. protected function o_javascript($id, $action, $code = '')
  1336. {
  1337. if ($action !== 'new') {
  1338. $o = &$this->objects[$id];
  1339. }
  1340. switch ($action) {
  1341. case 'new':
  1342. $this->objects[$id] = array(
  1343. 't' => 'javascript',
  1344. 'info' => array(
  1345. 'S' => '/JavaScript',
  1346. 'JS' => '(' . $this->filterText($code) . ')',
  1347. )
  1348. );
  1349. break;
  1350. case 'out':
  1351. $res = "\n$id 0 obj\n<< ";
  1352. foreach ($o['info'] as $k => $v) {
  1353. $res .= "\n/$k $v";
  1354. }
  1355. $res .= "\n>>\nendobj";
  1356. return $res;
  1357. }
  1358. }
  1359. /**
  1360. * an image object, will be an XObject in the document, includes description and data
  1361. */
  1362. protected function o_image($id, $action, $options = '')
  1363. {
  1364. if ($action !== 'new') {
  1365. $o = &$this->objects[$id];
  1366. }
  1367. switch ($action) {
  1368. case 'new':
  1369. // make the new object
  1370. $this->objects[$id] = array('t' => 'image', 'data' => &$options['data'], 'info' => array());
  1371. $info =& $this->objects[$id]['info'];
  1372. $info['Type'] = '/XObject';
  1373. $info['Subtype'] = '/Image';
  1374. $info['Width'] = $options['iw'];
  1375. $info['Height'] = $options['ih'];
  1376. if (isset($options['masked']) && $options['masked']) {
  1377. $info['SMask'] = ($this->numObj - 1) . ' 0 R';
  1378. }
  1379. if (!isset($options['type']) || $options['type'] === 'jpg') {
  1380. if (!isset($options['channels'])) {
  1381. $options['channels'] = 3;
  1382. }
  1383. switch ($options['channels']) {
  1384. case 1:
  1385. $info['ColorSpace'] = '/DeviceGray';
  1386. break;
  1387. case 4:
  1388. $info['ColorSpace'] = '/DeviceCMYK';
  1389. break;
  1390. default:
  1391. $info['ColorSpace'] = '/DeviceRGB';
  1392. break;
  1393. }
  1394. if ($info['ColorSpace'] === '/DeviceCMYK') {
  1395. $info['Decode'] = '[1 0 1 0 1 0 1 0]';
  1396. }
  1397. $info['Filter'] = '/DCTDecode';
  1398. $info['BitsPerComponent'] = 8;
  1399. } else {
  1400. if ($options['type'] === 'png') {
  1401. $info['Filter'] = '/FlateDecode';
  1402. $info['DecodeParms'] = '<< /Predictor 15 /Colors ' . $options['ncolor'] . ' /Columns ' . $options['iw'] . ' /BitsPerComponent ' . $options['bitsPerComponent'] . '>>';
  1403. if ($options['isMask']) {
  1404. $info['ColorSpace'] = '/DeviceGray';
  1405. } else {
  1406. if (mb_strlen($options['pdata'], '8bit')) {
  1407. $tmp = ' [ /Indexed /DeviceRGB ' . (mb_strlen($options['pdata'], '8bit') / 3 - 1) . ' ';
  1408. $this->numObj++;
  1409. $this->o_contents($this->numObj, 'new');
  1410. $this->objects[$this->numObj]['c'] = $options['pdata'];
  1411. $tmp .= $this->numObj . ' 0 R';
  1412. $tmp .= ' ]';
  1413. $info['ColorSpace'] = $tmp;
  1414. if (isset($options['transparency'])) {
  1415. $transparency = $options['transparency'];
  1416. switch ($transparency['type']) {
  1417. case 'indexed':
  1418. $tmp = ' [ ' . $transparency['data'] . ' ' . $transparency['data'] . '] ';
  1419. $info['Mask'] = $tmp;
  1420. break;
  1421. case 'color-key':
  1422. $tmp = ' [ ' .
  1423. $transparency['r'] . ' ' . $transparency['r'] .
  1424. $transparency['g'] . ' ' . $transparency['g'] .
  1425. $transparency['b'] . ' ' . $transparency['b'] .
  1426. ' ] ';
  1427. $info['Mask'] = $tmp;
  1428. break;
  1429. }
  1430. }
  1431. } else {
  1432. if (isset($options['transparency'])) {
  1433. $transparency = $options['transparency'];
  1434. switch ($transparency['type']) {
  1435. case 'indexed':
  1436. $tmp = ' [ ' . $transparency['data'] . ' ' . $transparency['data'] . '] ';
  1437. $info['Mask'] = $tmp;
  1438. break;
  1439. case 'color-key':
  1440. $tmp = ' [ ' .
  1441. $transparency['r'] . ' ' . $transparency['r'] . ' ' .
  1442. $transparency['g'] . ' ' . $transparency['g'] . ' ' .
  1443. $transparency['b'] . ' ' . $transparency['b'] .
  1444. ' ] ';
  1445. $info['Mask'] = $tmp;
  1446. break;
  1447. }
  1448. }
  1449. $info['ColorSpace'] = '/' . $options['color'];
  1450. }
  1451. }
  1452. $info['BitsPerComponent'] = $options['bitsPerComponent'];
  1453. }
  1454. }
  1455. // assign it a place in the named resource dictionary as an external object, according to
  1456. // the label passed in with it.
  1457. $this->o_pages($this->currentNode, 'xObject', array('label' => $options['label'], 'objNum' => $id));
  1458. // also make sure that we have the right procset object for it.
  1459. $this->o_procset($this->procsetObjectId, 'add', 'ImageC');
  1460. break;
  1461. case 'out':
  1462. $tmp = &$o['data'];
  1463. $res = "\n$id 0 obj\n<<";
  1464. foreach ($o['info'] as $k => $v) {
  1465. $res .= "\n/$k $v";
  1466. }
  1467. if ($this->encrypted) {
  1468. $this->encryptInit($id);
  1469. $tmp = $this->ARC4($tmp);
  1470. }
  1471. $res .= "\n/Length " . mb_strlen($tmp, '8bit') . ">>\nstream\n$tmp\nendstream\nendobj";
  1472. return $res;
  1473. }
  1474. }
  1475. /**
  1476. * graphics state object
  1477. */
  1478. protected function o_extGState($id, $action, $options = "")
  1479. {
  1480. static $valid_params = array(
  1481. "LW",
  1482. "LC",
  1483. "LC",
  1484. "LJ",
  1485. "ML",
  1486. "D",
  1487. "RI",
  1488. "OP",
  1489. "op",
  1490. "OPM",
  1491. "Font",
  1492. "BG",
  1493. "BG2",
  1494. "UCR",
  1495. "TR",
  1496. "TR2",
  1497. "HT",
  1498. "FL",
  1499. "SM",
  1500. "SA",
  1501. "BM",
  1502. "SMask",
  1503. "CA",
  1504. "ca",
  1505. "AIS",
  1506. "TK"
  1507. );
  1508. if ($action !== "new") {
  1509. $o = &$this->objects[$id];
  1510. }
  1511. switch ($action) {
  1512. case "new":
  1513. $this->objects[$id] = array('t' => 'extGState', 'info' => $options);
  1514. // Tell the pages about the new resource
  1515. $this->numStates++;
  1516. $this->o_pages($this->currentNode, 'extGState', array("objNum" => $id, "stateNum" => $this->numStates));
  1517. break;
  1518. case "out":
  1519. $res = "\n$id 0 obj\n<< /Type /ExtGState\n";
  1520. foreach ($o["info"] as $k => $v) {
  1521. if (!in_array($k, $valid_params)) {
  1522. continue;
  1523. }
  1524. $res .= "/$k $v\n";
  1525. }
  1526. $res .= ">>\nendobj";
  1527. return $res;
  1528. }
  1529. }
  1530. /**
  1531. * encryption object.
  1532. */
  1533. protected function o_encryption($id, $action, $options = '')
  1534. {
  1535. if ($action !== 'new') {
  1536. $o = &$this->objects[$id];
  1537. }
  1538. switch ($action) {
  1539. case 'new':
  1540. // make the new object
  1541. $this->objects[$id] = array('t' => 'encryption', 'info' => $options);
  1542. $this->arc4_objnum = $id;
  1543. // figure out the additional parameters required
  1544. $pad = chr(0x28) . chr(0xBF) . chr(0x4E) . chr(0x5E) . chr(0x4E) . chr(0x75) . chr(0x8A) . chr(0x41)
  1545. . chr(0x64) . chr(0x00) . chr(0x4E) . chr(0x56) . chr(0xFF) . chr(0xFA) . chr(0x01) . chr(0x08)
  1546. . chr(0x2E) . chr(0x2E) . chr(0x00) . chr(0xB6) . chr(0xD0) . chr(0x68) . chr(0x3E) . chr(0x80)
  1547. . chr(0x2F) . chr(0x0C) . chr(0xA9) . chr(0xFE) . chr(0x64) . chr(0x53) . chr(0x69) . chr(0x7A);
  1548. $len = mb_strlen($options['owner'], '8bit');
  1549. if ($len > 32) {
  1550. $owner = substr($options['owner'], 0, 32);
  1551. } else {
  1552. if ($len < 32) {
  1553. $owner = $options['owner'] . substr($pad, 0, 32 - $len);
  1554. } else {
  1555. $owner = $options['owner'];
  1556. }
  1557. }
  1558. $len = mb_strlen($options['user'], '8bit');
  1559. if ($len > 32) {
  1560. $user = substr($options['user'], 0, 32);
  1561. } else {
  1562. if ($len < 32) {
  1563. $user = $options['user'] . substr($pad, 0, 32 - $len);
  1564. } else {
  1565. $user = $options['user'];
  1566. }
  1567. }
  1568. $tmp = $this->md5_16($owner);
  1569. $okey = substr($tmp, 0, 5);
  1570. $this->ARC4_init($okey);
  1571. $ovalue = $this->ARC4($user);
  1572. $this->objects[$id]['info']['O'] = $ovalue;
  1573. // now make the u value, phew.
  1574. $tmp = $this->md5_16(
  1575. $user . $ovalue . chr($options['p']) . chr(255) . chr(255) . chr(255) . $this->fileIdentifier
  1576. );
  1577. $ukey = substr($tmp, 0, 5);
  1578. $this->ARC4_init($ukey);
  1579. $this->encryptionKey = $ukey;
  1580. $this->encrypted = true;
  1581. $uvalue = $this->ARC4($pad);
  1582. $this->objects[$id]['info']['U'] = $uvalue;
  1583. $this->encryptionKey = $ukey;
  1584. // initialize the arc4 array
  1585. break;
  1586. case 'out':
  1587. $res = "\n$id 0 obj\n<<";
  1588. $res .= "\n/Filter /Standard";
  1589. $res .= "\n/V 1";
  1590. $res .= "\n/R 2";
  1591. $res .= "\n/O (" . $this->filterText($o['info']['O'], true, false) . ')';
  1592. $res .= "\n/U (" . $this->filterText($o['info']['U'], true, false) . ')';
  1593. // and the p-value needs to be converted to account for the twos-complement approach
  1594. $o['info']['p'] = (($o['info']['p'] ^ 255) + 1) * -1;
  1595. $res .= "\n/P " . ($o['info']['p']);
  1596. $res .= "\n>>\nendobj";
  1597. return $res;
  1598. }
  1599. }
  1600. /**
  1601. * ARC4 functions
  1602. * A series of function to implement ARC4 encoding in PHP
  1603. */
  1604. /**
  1605. * calculate the 16 byte version of the 128 bit md5 digest of the string
  1606. */
  1607. function md5_16($string)
  1608. {
  1609. $tmp = md5($string);
  1610. $out = '';
  1611. for ($i = 0; $i <= 30; $i = $i + 2) {
  1612. $out .= chr(hexdec(substr($tmp, $i, 2)));
  1613. }
  1614. return $out;
  1615. }
  1616. /**
  1617. * initialize the encryption for processing a particular object
  1618. */
  1619. function encryptInit($id)
  1620. {
  1621. $tmp = $this->encryptionKey;
  1622. $hex = dechex($id);
  1623. if (mb_strlen($hex, '8bit') < 6) {
  1624. $hex = substr('000000', 0, 6 - mb_strlen($hex, '8bit')) . $hex;
  1625. }
  1626. $tmp .= chr(hexdec(substr($hex, 4, 2))) . chr(hexdec(substr($hex, 2, 2))) . chr(
  1627. hexdec(substr($hex, 0, 2))
  1628. ) . chr(0) . chr(0);
  1629. $key = $this->md5_16($tmp);
  1630. $this->ARC4_init(substr($key, 0, 10));
  1631. }
  1632. /**
  1633. * initialize the ARC4 encryption
  1634. */
  1635. function ARC4_init($key = '')
  1636. {
  1637. $this->arc4 = '';
  1638. // setup the control array
  1639. if (mb_strlen($key, '8bit') == 0) {
  1640. return;
  1641. }
  1642. $k = '';
  1643. while (mb_strlen($k, '8bit') < 256) {
  1644. $k .= $key;
  1645. }
  1646. $k = substr($k, 0, 256);
  1647. for ($i = 0; $i < 256; $i++) {
  1648. $this->arc4 .= chr($i);
  1649. }
  1650. $j = 0;
  1651. for ($i = 0; $i < 256; $i++) {
  1652. $t = $this->arc4[$i];
  1653. $j = ($j + ord($t) + ord($k[$i])) % 256;
  1654. $this->arc4[$i] = $this->arc4[$j];
  1655. $this->arc4[$j] = $t;
  1656. }
  1657. }
  1658. /**
  1659. * ARC4 encrypt a text string
  1660. */
  1661. function ARC4($text)
  1662. {
  1663. $len = mb_strlen($text, '8bit');
  1664. $a = 0;
  1665. $b = 0;
  1666. $c = $this->arc4;
  1667. $out = '';
  1668. for ($i = 0; $i < $len; $i++) {
  1669. $a = ($a + 1) % 256;
  1670. $t = $c[$a];
  1671. $b = ($b + ord($t)) % 256;
  1672. $c[$a] = $c[$b];
  1673. $c[$b] = $t;
  1674. $k = ord($c[(ord($c[$a]) + ord($c[$b])) % 256]);
  1675. $out .= chr(ord($text[$i]) ^ $k);
  1676. }
  1677. return $out;
  1678. }
  1679. /**
  1680. * functions which can be called to adjust or add to the document
  1681. */
  1682. /**
  1683. * add a link in the document to an external URL
  1684. */
  1685. function addLink($url, $x0, $y0, $x1, $y1)
  1686. {
  1687. $this->numObj++;
  1688. $info = array('type' => 'link', 'url' => $url, 'rect' => array($x0, $y0, $x1, $y1));
  1689. $this->o_annotation($this->numObj, 'new', $info);
  1690. }
  1691. /**
  1692. * add a link in the document to an internal destination (ie. within the document)
  1693. */
  1694. function addInternalLink($label, $x0, $y0, $x1, $y1)
  1695. {
  1696. $this->numObj++;
  1697. $info = array('type' => 'ilink', 'label' => $label, 'rect' => array($x0, $y0, $x1, $y1));
  1698. $this->o_annotation($this->numObj, 'new', $info);
  1699. }
  1700. /**
  1701. * set the encryption of the document
  1702. * can be used to turn it on and/or set the passwords which it will have.
  1703. * also the functions that the user will have are set here, such as print, modify, add
  1704. */
  1705. function setEncryption($userPass = '', $ownerPass = '', $pc = array())
  1706. {
  1707. $p = bindec("11000000");
  1708. $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'add' => 32);
  1709. foreach ($pc as $k => $v) {
  1710. if ($v && isset($options[$k])) {
  1711. $p += $options[$k];
  1712. } else {
  1713. if (isset($options[$v])) {
  1714. $p += $options[$v];
  1715. }
  1716. }
  1717. }
  1718. // implement encryption on the document
  1719. if ($this->arc4_objnum == 0) {
  1720. // then the block does not exist already, add it.
  1721. $this->numObj++;
  1722. if (mb_strlen($ownerPass) == 0) {
  1723. $ownerPass = $userPass;
  1724. }
  1725. $this->o_encryption($this->numObj, 'new', array('user' => $userPass, 'owner' => $ownerPass, 'p' => $p));
  1726. }
  1727. }
  1728. /**
  1729. * should be used for internal checks, not implemented as yet
  1730. */
  1731. function checkAllHere()
  1732. {
  1733. }
  1734. /**
  1735. * return the pdf stream as a string returned from the function
  1736. */
  1737. function output($debug = false)
  1738. {
  1739. if ($debug) {
  1740. // turn compression off
  1741. $this->options['compression'] = false;
  1742. }
  1743. if ($this->javascript) {
  1744. $this->numObj++;
  1745. $js_id = $this->numObj;
  1746. $this->o_embedjs($js_id, 'new');
  1747. $this->o_javascript(++$this->numObj, 'new', $this->javascript);
  1748. $id = $this->catalogId;
  1749. $this->o_catalog($id, 'javascript', $js_id);
  1750. }
  1751. if ($this->arc4_objnum) {
  1752. $this->ARC4_init($this->encryptionKey);
  1753. }
  1754. $this->checkAllHere();
  1755. $xref = array();
  1756. $content = '%PDF-1.3';
  1757. $pos = mb_strlen($content, '8bit');
  1758. foreach ($this->objects as $k => $v) {
  1759. $tmp = 'o_' . $v['t'];
  1760. $cont = $this->$tmp($k, 'out');
  1761. $content .= $cont;
  1762. $xref[] = $pos + 1; //+1 to account for \n at the start of each object
  1763. $pos += mb_strlen($cont, '8bit');
  1764. }
  1765. $content .= "\nxref\n0 " . (count($xref) + 1) . "\n0000000000 65535 f \n";
  1766. foreach ($xref as $p) {
  1767. $content .= str_pad($p, 10, "0", STR_PAD_LEFT) . " 00000 n \n";
  1768. }
  1769. $content .= "trailer\n<<\n/Size " . (count($xref) + 1) . "\n/Root 1 0 R\n/Info $this->infoObject 0 R\n";
  1770. // if encryption has been applied to this document then add the marker for this dictionary
  1771. if ($this->arc4_objnum > 0) {
  1772. $content .= "/Encrypt $this->arc4_objnum 0 R\n";
  1773. }
  1774. if (mb_strlen($this->fileIdentifier, '8bit')) {
  1775. $content .= "/ID[<$this->fileIdentifier><$this->fileIdentifier>]\n";
  1776. }
  1777. // account for \n added at start of xref table
  1778. $pos++;
  1779. $content .= ">>\nstartxref\n$pos\n%%EOF\n";
  1780. return $content;
  1781. }
  1782. /**
  1783. * initialize a new document
  1784. * if this is called on an existing document results may be unpredictable, but the existing document would be lost at minimum
  1785. * this function is called automatically by the constructor function
  1786. */
  1787. private function newDocument($pageSize = array(0, 0, 612, 792))
  1788. {
  1789. $this->numObj = 0;
  1790. $this->objects = array();
  1791. $this->numObj++;
  1792. $this->o_catalog($this->numObj, 'new');
  1793. $this->numObj++;
  1794. $this->o_outlines($this->numObj, 'new');
  1795. $this->numObj++;
  1796. $this->o_pages($this->numObj, 'new');
  1797. $this->o_pages($this->numObj, 'mediaBox', $pageSize);
  1798. $this->currentNode = 3;
  1799. $this->numObj++;
  1800. $this->o_procset($this->numObj, 'new');
  1801. $this->numObj++;
  1802. $this->o_info($this->numObj, 'new');
  1803. $this->numObj++;
  1804. $this->o_page($this->numObj, 'new');
  1805. // need to store the first page id as there is no way to get it to the user during
  1806. // startup
  1807. $this->firstPageId = $this->currentContents;
  1808. }
  1809. /**
  1810. * open the font file and return a php structure containing it.
  1811. * first check if this one has been done before and saved in a form more suited to php
  1812. * note that if a php serialized version does not exist it will try and make one, but will
  1813. * require write access to the directory to do it... it is MUCH faster to have these serialized
  1814. * files.
  1815. */
  1816. private function openFont($font)
  1817. {
  1818. // assume that $font contains the path and file but not the extension
  1819. $name = basename($font);
  1820. $dir = dirname($font) . '/';
  1821. $fontcache = $this->fontcache;
  1822. if ($fontcache == '') {
  1823. $fontcache = rtrim($dir, DIRECTORY_SEPARATOR."/\\");
  1824. }
  1825. //$name filename without folder and extension of font metrics
  1826. //$dir folder of font metrics
  1827. //$fontcache folder of runtime created php serialized version of font metrics.
  1828. // If this is not given, the same folder as the font metrics will be used.
  1829. // Storing and reusing serialized versions improves speed much
  1830. $this->addMessage("openFont: $font - $name");
  1831. if (!$this->isUnicode || in_array(mb_strtolower(basename($name)), self::$coreFonts)) {
  1832. $metrics_name = "$name.afm";
  1833. } else {
  1834. $metrics_name = "$name.ufm";
  1835. }
  1836. $cache_name = "$metrics_name.php";
  1837. $this->addMessage("metrics: $metrics_name, cache: $cache_name");
  1838. if (file_exists($fontcache . '/' . $cache_name)) {
  1839. $this->addMessage("openFont: php file exists $fontcache/$cache_name");
  1840. $this->fonts[$font] = require($fontcache . '/' . $cache_name);
  1841. if (!isset($this->fonts[$font]['_version_']) || $this->fonts[$font]['_version_'] != $this->fontcacheVersion) {
  1842. // if the font file is old, then clear it out and prepare for re-creation
  1843. $this->addMessage('openFont: clear out, make way for new version.');
  1844. $this->fonts[$font] = null;
  1845. unset($this->fonts[$font]);
  1846. }
  1847. } else {
  1848. $old_cache_name = "php_$metrics_name";
  1849. if (file_exists($fontcache . '/' . $old_cache_name)) {
  1850. $this->addMessage(
  1851. "openFont: php file doesn't exist $fontcache/$cache_name, creating it from the old format"
  1852. );
  1853. $old_cache = file_get_contents($fontcache . '/' . $old_cache_name);
  1854. file_put_contents($fontcache . '/' . $cache_name, '<?php return ' . $old_cache . ';');
  1855. return $this->openFont($font);
  1856. }
  1857. }
  1858. if (!isset($this->fonts[$font]) && file_exists($dir . $metrics_name)) {
  1859. // then rebuild the php_<font>.afm file from the <font>.afm file
  1860. $this->addMessage("openFont: build php file from $dir$metrics_name");
  1861. $data = array();
  1862. // 20 => 'space'
  1863. $data['codeToName'] = array();
  1864. // Since we're not going to enable Unicode for the core fonts we need to use a font-based
  1865. // setting for Unicode support rather than a global setting.
  1866. $data['isUnicode'] = (strtolower(substr($metrics_name, -3)) !== 'afm');
  1867. $cidtogid = '';
  1868. if ($data['isUnicode']) {
  1869. $cidtogid = str_pad('', 256 * 256 * 2, "\x00");
  1870. }
  1871. $file = file($dir . $metrics_name);
  1872. foreach ($file as $rowA) {
  1873. $row = trim($rowA);
  1874. $pos = strpos($row, ' ');
  1875. if ($pos) {
  1876. // then there must be some keyword
  1877. $key = substr($row, 0, $pos);
  1878. switch ($key) {
  1879. case 'FontName':
  1880. case 'FullName':
  1881. case 'FamilyName':
  1882. case 'PostScriptName':
  1883. case 'Weight':
  1884. case 'ItalicAngle':
  1885. case 'IsFixedPitch':
  1886. case 'CharacterSet':
  1887. case 'UnderlinePosition':
  1888. case 'UnderlineThickness':
  1889. case 'Version':
  1890. case 'EncodingScheme':
  1891. case 'CapHeight':
  1892. case 'XHeight':
  1893. case 'Ascender':
  1894. case 'Descender':
  1895. case 'StdHW':
  1896. case 'StdVW':
  1897. case 'StartCharMetrics':
  1898. case 'FontHeightOffset': // OAR - Added so we can offset the height calculation of a Windows font. Otherwise it's too big.
  1899. $data[$key] = trim(substr($row, $pos));
  1900. break;
  1901. case 'FontBBox':
  1902. $data[$key] = explode(' ', trim(substr($row, $pos)));
  1903. break;
  1904. //C 39 ; WX 222 ; N quoteright ; B 53 463 157 718 ;
  1905. case 'C': // Found in AFM files
  1906. $bits = explode(';', trim($row));
  1907. $dtmp = array();
  1908. foreach ($bits as $bit) {
  1909. $bits2 = explode(' ', trim($bit));
  1910. if (mb_strlen($bits2[0], '8bit') == 0) {
  1911. continue;
  1912. }
  1913. if (count($bits2) > 2) {
  1914. $dtmp[$bits2[0]] = array();
  1915. for ($i = 1; $i < count($bits2); $i++) {
  1916. $dtmp[$bits2[0]][] = $bits2[$i];
  1917. }
  1918. } else {
  1919. if (count($bits2) == 2) {
  1920. $dtmp[$bits2[0]] = $bits2[1];
  1921. }
  1922. }
  1923. }
  1924. $c = (int)$dtmp['C'];
  1925. $n = $dtmp['N'];
  1926. $width = floatval($dtmp['WX']);
  1927. if ($c >= 0) {
  1928. if ($c != hexdec($n)) {
  1929. $data['codeToName'][$c] = $n;
  1930. }
  1931. $data['C'][$c] = $width;
  1932. } else {
  1933. $data['C'][$n] = $width;
  1934. }
  1935. if (!isset($data['MissingWidth']) && $c == -1 && $n === '.notdef') {
  1936. $data['MissingWidth'] = $width;
  1937. }
  1938. break;
  1939. // U 827 ; WX 0 ; N squaresubnosp ; G 675 ;
  1940. case 'U': // Found in UFM files
  1941. if (!$data['isUnicode']) {
  1942. break;
  1943. }
  1944. $bits = explode(';', trim($row));
  1945. $dtmp = array();
  1946. foreach ($bits as $bit) {
  1947. $bits2 = explode(' ', trim($bit));
  1948. if (mb_strlen($bits2[0], '8bit') === 0) {
  1949. continue;
  1950. }
  1951. if (count($bits2) > 2) {
  1952. $dtmp[$bits2[0]] = array();
  1953. for ($i = 1; $i < count($bits2); $i++) {
  1954. $dtmp[$bits2[0]][] = $bits2[$i];
  1955. }
  1956. } else {
  1957. if (count($bits2) == 2) {
  1958. $dtmp[$bits2[0]] = $bits2[1];
  1959. }
  1960. }
  1961. }
  1962. $c = (int)$dtmp['U'];
  1963. $n = $dtmp['N'];
  1964. $glyph = $dtmp['G'];
  1965. $width = floatval($dtmp['WX']);
  1966. if ($c >= 0) {
  1967. // Set values in CID to GID map
  1968. if ($c >= 0 && $c < 0xFFFF && $glyph) {
  1969. $cidtogid[$c * 2] = chr($glyph >> 8);
  1970. $cidtogid[$c * 2 + 1] = chr($glyph & 0xFF);
  1971. }
  1972. if ($c != hexdec($n)) {
  1973. $data['codeToName'][$c] = $n;
  1974. }
  1975. $data['C'][$c] = $width;
  1976. } else {
  1977. $data['C'][$n] = $width;
  1978. }
  1979. if (!isset($data['MissingWidth']) && $c == -1 && $n === '.notdef') {
  1980. $data['MissingWidth'] = $width;
  1981. }
  1982. break;
  1983. case 'KPX':
  1984. break; // don't include them as they are not used yet
  1985. //KPX Adieresis yacute -40
  1986. $bits = explode(' ', trim($row));
  1987. $data['KPX'][$bits[1]][$bits[2]] = $bits[3];
  1988. break;
  1989. }
  1990. }
  1991. }
  1992. if ($this->compressionReady && $this->options['compression']) {
  1993. // then implement ZLIB based compression on CIDtoGID string
  1994. $data['CIDtoGID_Compressed'] = true;
  1995. $cidtogid = gzcompress($cidtogid, 6);
  1996. }
  1997. $data['CIDtoGID'] = base64_encode($cidtogid);
  1998. $data['_version_'] = $this->fontcacheVersion;
  1999. $this->fonts[$font] = $data;
  2000. //Because of potential trouble with php safe mode, expect that the folder already exists.
  2001. //If not existing, this will hit performance because of missing cached results.
  2002. if (is_dir($fontcache) && is_writable($fontcache)) {
  2003. file_put_contents($fontcache . '/' . $cache_name, '<?php return ' . var_export($data, true) . ';');
  2004. }
  2005. $data = null;
  2006. }
  2007. if (!isset($this->fonts[$font])) {
  2008. $this->addMessage("openFont: no font file found for $font. Do you need to run load_font.php?");
  2009. }
  2010. //pre_r($this->messages);
  2011. }
  2012. /**
  2013. * if the font is not loaded then load it and make the required object
  2014. * else just make it the current font
  2015. * the encoding array can contain 'encoding'=> 'none','WinAnsiEncoding','MacRomanEncoding' or 'MacExpertEncoding'
  2016. * note that encoding='none' will need to be used for symbolic fonts
  2017. * and 'differences' => an array of mappings between numbers 0->255 and character names.
  2018. *
  2019. */
  2020. function selectFont($fontName, $encoding = '', $set = true)
  2021. {
  2022. $ext = substr($fontName, -4);
  2023. if ($ext === '.afm' || $ext === '.ufm') {
  2024. $fontName = substr($fontName, 0, mb_strlen($fontName) - 4);
  2025. }
  2026. if (!isset($this->fonts[$fontName])) {
  2027. $this->addMessage("selectFont: selecting - $fontName - $encoding, $set");
  2028. // load the file
  2029. $this->openFont($fontName);
  2030. if (isset($this->fonts[$fontName])) {
  2031. $this->numObj++;
  2032. $this->numFonts++;
  2033. $font = &$this->fonts[$fontName];
  2034. $name = basename($fontName);
  2035. $dir = dirname($fontName) . '/';
  2036. $options = array('name' => $name, 'fontFileName' => $fontName);
  2037. if (is_array($encoding)) {
  2038. // then encoding and differences might be set
  2039. if (isset($encoding['encoding'])) {
  2040. $options['encoding'] = $encoding['encoding'];
  2041. }
  2042. if (isset($encoding['differences'])) {
  2043. $options['differences'] = $encoding['differences'];
  2044. }
  2045. } else {
  2046. if (mb_strlen($encoding, '8bit')) {
  2047. // then perhaps only the encoding has been set
  2048. $options['encoding'] = $encoding;
  2049. }
  2050. }
  2051. $fontObj = $this->numObj;
  2052. $this->o_font($this->numObj, 'new', $options);
  2053. $font['fontNum'] = $this->numFonts;
  2054. // if this is a '.afm' font, and there is a '.pfa' file to go with it ( as there
  2055. // should be for all non-basic fonts), then load it into an object and put the
  2056. // references into the font object
  2057. $basefile = $fontName;
  2058. $fbtype = '';
  2059. if (file_exists("$basefile.pfb")) {
  2060. $fbtype = 'pfb';
  2061. } else {
  2062. if (file_exists("$basefile.ttf")) {
  2063. $fbtype = 'ttf';
  2064. }
  2065. }
  2066. $fbfile = "$basefile.$fbtype";
  2067. // $pfbfile = substr($fontName,0,strlen($fontName)-4).'.pfb';
  2068. // $ttffile = substr($fontName,0,strlen($fontName)-4).'.ttf';
  2069. $this->addMessage('selectFont: checking for - ' . $fbfile);
  2070. // OAR - I don't understand this old check
  2071. // if (substr($fontName, -4) === '.afm' && strlen($fbtype)) {
  2072. if ($fbtype) {
  2073. $adobeFontName = isset($font['PostScriptName']) ? $font['PostScriptName'] : $font['FontName'];
  2074. // $fontObj = $this->numObj;
  2075. $this->addMessage("selectFont: adding font file - $fbfile - $adobeFontName");
  2076. // find the array of font widths, and put that into an object.
  2077. $firstChar = -1;
  2078. $lastChar = 0;
  2079. $widths = array();
  2080. $cid_widths = array();
  2081. foreach ($font['C'] as $num => $d) {
  2082. if (intval($num) > 0 || $num == '0') {
  2083. if (!$font['isUnicode']) {
  2084. // With Unicode, widths array isn't used
  2085. if ($lastChar > 0 && $num > $lastChar + 1) {
  2086. for ($i = $lastChar + 1; $i < $num; $i++) {
  2087. $widths[] = 0;
  2088. }
  2089. }
  2090. }
  2091. $widths[] = $d;
  2092. if ($font['isUnicode']) {
  2093. $cid_widths[$num] = $d;
  2094. }
  2095. if ($firstChar == -1) {
  2096. $firstChar = $num;
  2097. }
  2098. $lastChar = $num;
  2099. }
  2100. }
  2101. // also need to adjust the widths for the differences array
  2102. if (isset($options['differences'])) {
  2103. foreach ($options['differences'] as $charNum => $charName) {
  2104. if ($charNum > $lastChar) {
  2105. if (!$font['isUnicode']) {
  2106. // With Unicode, widths array isn't used
  2107. for ($i = $lastChar + 1; $i <= $charNum; $i++) {
  2108. $widths[] = 0;
  2109. }
  2110. }
  2111. $lastChar = $charNum;
  2112. }
  2113. if (isset($font['C'][$charName])) {
  2114. $widths[$charNum - $firstChar] = $font['C'][$charName];
  2115. if ($font['isUnicode']) {
  2116. $cid_widths[$charName] = $font['C'][$charName];
  2117. }
  2118. }
  2119. }
  2120. }
  2121. if ($font['isUnicode']) {
  2122. $font['CIDWidths'] = $cid_widths;
  2123. }
  2124. $this->addMessage('selectFont: FirstChar = ' . $firstChar);
  2125. $this->addMessage('selectFont: LastChar = ' . $lastChar);
  2126. $widthid = -1;
  2127. if (!$font['isUnicode']) {
  2128. // With Unicode, widths array isn't used
  2129. $this->numObj++;
  2130. $this->o_contents($this->numObj, 'new', 'raw');
  2131. $this->objects[$this->numObj]['c'] .= '[' . implode(' ', $widths) . ']';
  2132. $widthid = $this->numObj;
  2133. }
  2134. $missing_width = 500;
  2135. $stemV = 70;
  2136. if (isset($font['MissingWidth'])) {
  2137. $missing_width = $font['MissingWidth'];
  2138. }
  2139. if (isset($font['StdVW'])) {
  2140. $stemV = $font['StdVW'];
  2141. } else {
  2142. if (isset($font['Weight']) && preg_match('!(bold|black)!i', $font['Weight'])) {
  2143. $stemV = 120;
  2144. }
  2145. }
  2146. // load the pfb file, and put that into an object too.
  2147. // note that pdf supports only binary format type 1 font files, though there is a
  2148. // simple utility to convert them from pfa to pfb.
  2149. // FIXME: should we move font subset creation to CPDF::output? See notes in issue #750.
  2150. if (!$this->isUnicode || $fbtype !== 'ttf' || empty($this->stringSubsets)) {
  2151. $data = file_get_contents($fbfile);
  2152. } else {
  2153. $this->stringSubsets[$fontName][] = 32; // Force space if not in yet
  2154. $subset = $this->stringSubsets[$fontName];
  2155. sort($subset);
  2156. // Load font
  2157. $font_obj = Font::load($fbfile);
  2158. $font_obj->parse();
  2159. // Define subset
  2160. $font_obj->setSubset($subset);
  2161. $font_obj->reduce();
  2162. // Write new font
  2163. $tmp_name = $this->tmp . "/" . basename($fbfile) . ".tmp." . uniqid();
  2164. $font_obj->open($tmp_name, BinaryStream::modeWrite);
  2165. $font_obj->encode(array("OS/2"));
  2166. $font_obj->close();
  2167. // Parse the new font to get cid2gid and widths
  2168. $font_obj = Font::load($tmp_name);
  2169. // Find Unicode char map table
  2170. $subtable = null;
  2171. foreach ($font_obj->getData("cmap", "subtables") as $_subtable) {
  2172. if ($_subtable["platformID"] == 0 || $_subtable["platformID"] == 3 && $_subtable["platformSpecificID"] == 1) {
  2173. $subtable = $_subtable;
  2174. break;
  2175. }
  2176. }
  2177. if ($subtable) {
  2178. $glyphIndexArray = $subtable["glyphIndexArray"];
  2179. $hmtx = $font_obj->getData("hmtx");
  2180. unset($glyphIndexArray[0xFFFF]);
  2181. $cidtogid = str_pad('', max(array_keys($glyphIndexArray)) * 2 + 1, "\x00");
  2182. $font['CIDWidths'] = array();
  2183. foreach ($glyphIndexArray as $cid => $gid) {
  2184. if ($cid >= 0 && $cid < 0xFFFF && $gid) {
  2185. $cidtogid[$cid * 2] = chr($gid >> 8);
  2186. $cidtogid[$cid * 2 + 1] = chr($gid & 0xFF);
  2187. }
  2188. $width = $font_obj->normalizeFUnit(isset($hmtx[$gid]) ? $hmtx[$gid][0] : $hmtx[0][0]);
  2189. $font['CIDWidths'][$cid] = $width;
  2190. }
  2191. $font['CIDtoGID'] = base64_encode(gzcompress($cidtogid));
  2192. $font['CIDtoGID_Compressed'] = true;
  2193. $data = file_get_contents($tmp_name);
  2194. } else {
  2195. $data = file_get_contents($fbfile);
  2196. }
  2197. $font_obj->close();
  2198. unlink($tmp_name);
  2199. }
  2200. // create the font descriptor
  2201. $this->numObj++;
  2202. $fontDescriptorId = $this->numObj;
  2203. $this->numObj++;
  2204. $pfbid = $this->numObj;
  2205. // determine flags (more than a little flakey, hopefully will not matter much)
  2206. $flags = 0;
  2207. if ($font['ItalicAngle'] != 0) {
  2208. $flags += pow(2, 6);
  2209. }
  2210. if ($font['IsFixedPitch'] === 'true') {
  2211. $flags += 1;
  2212. }
  2213. $flags += pow(2, 5); // assume non-sybolic
  2214. $list = array(
  2215. 'Ascent' => 'Ascender',
  2216. 'CapHeight' => 'Ascender', //FIXME: php-font-lib is not grabbing this value, so we'll fake it and use the Ascender value // 'CapHeight'
  2217. 'MissingWidth' => 'MissingWidth',
  2218. 'Descent' => 'Descender',
  2219. 'FontBBox' => 'FontBBox',
  2220. 'ItalicAngle' => 'ItalicAngle'
  2221. );
  2222. $fdopt = array(
  2223. 'Flags' => $flags,
  2224. 'FontName' => $adobeFontName,
  2225. 'StemV' => $stemV
  2226. );
  2227. foreach ($list as $k => $v) {
  2228. if (isset($font[$v])) {
  2229. $fdopt[$k] = $font[$v];
  2230. }
  2231. }
  2232. if ($fbtype === 'pfb') {
  2233. $fdopt['FontFile'] = $pfbid;
  2234. } else {
  2235. if ($fbtype === 'ttf') {
  2236. $fdopt['FontFile2'] = $pfbid;
  2237. }
  2238. }
  2239. $this->o_fontDescriptor($fontDescriptorId, 'new', $fdopt);
  2240. // embed the font program
  2241. $this->o_contents($this->numObj, 'new');
  2242. $this->objects[$pfbid]['c'] .= $data;
  2243. // determine the cruicial lengths within this file
  2244. if ($fbtype === 'pfb') {
  2245. $l1 = strpos($data, 'eexec') + 6;
  2246. $l2 = strpos($data, '00000000') - $l1;
  2247. $l3 = mb_strlen($data, '8bit') - $l2 - $l1;
  2248. $this->o_contents(
  2249. $this->numObj,
  2250. 'add',
  2251. array('Length1' => $l1, 'Length2' => $l2, 'Length3' => $l3)
  2252. );
  2253. } else {
  2254. if ($fbtype == 'ttf') {
  2255. $l1 = mb_strlen($data, '8bit');
  2256. $this->o_contents($this->numObj, 'add', array('Length1' => $l1));
  2257. }
  2258. }
  2259. // tell the font object about all this new stuff
  2260. $tmp = array(
  2261. 'BaseFont' => $adobeFontName,
  2262. 'MissingWidth' => $missing_width,
  2263. 'Widths' => $widthid,
  2264. 'FirstChar' => $firstChar,
  2265. 'LastChar' => $lastChar,
  2266. 'FontDescriptor' => $fontDescriptorId
  2267. );
  2268. if ($fbtype === 'ttf') {
  2269. $tmp['SubType'] = 'TrueType';
  2270. }
  2271. $this->addMessage("adding extra info to font.($fontObj)");
  2272. foreach ($tmp as $fk => $fv) {
  2273. $this->addMessage("$fk : $fv");
  2274. }
  2275. $this->o_font($fontObj, 'add', $tmp);
  2276. } else {
  2277. $this->addMessage(
  2278. 'selectFont: pfb or ttf file not found, ok if this is one of the 14 standard fonts'
  2279. );
  2280. }
  2281. // also set the differences here, note that this means that these will take effect only the
  2282. //first time that a font is selected, else they are ignored
  2283. if (isset($options['differences'])) {
  2284. $font['differences'] = $options['differences'];
  2285. }
  2286. }
  2287. }
  2288. if ($set && isset($this->fonts[$fontName])) {
  2289. // so if for some reason the font was not set in the last one then it will not be selected
  2290. $this->currentBaseFont = $fontName;
  2291. // the next lines mean that if a new font is selected, then the current text state will be
  2292. // applied to it as well.
  2293. $this->currentFont = $this->currentBaseFont;
  2294. $this->currentFontNum = $this->fonts[$this->currentFont]['fontNum'];
  2295. //$this->setCurrentFont();
  2296. }
  2297. return $this->currentFontNum;
  2298. //return $this->numObj;
  2299. }
  2300. /**
  2301. * sets up the current font, based on the font families, and the current text state
  2302. * note that this system is quite flexible, a bold-italic font can be completely different to a
  2303. * italic-bold font, and even bold-bold will have to be defined within the family to have meaning
  2304. * This function is to be called whenever the currentTextState is changed, it will update
  2305. * the currentFont setting to whatever the appropriate family one is.
  2306. * If the user calls selectFont themselves then that will reset the currentBaseFont, and the currentFont
  2307. * This function will change the currentFont to whatever it should be, but will not change the
  2308. * currentBaseFont.
  2309. */
  2310. private function setCurrentFont()
  2311. {
  2312. // if (strlen($this->currentBaseFont) == 0){
  2313. // // then assume an initial font
  2314. // $this->selectFont($this->defaultFont);
  2315. // }
  2316. // $cf = substr($this->currentBaseFont,strrpos($this->currentBaseFont,'/')+1);
  2317. // if (strlen($this->currentTextState)
  2318. // && isset($this->fontFamilies[$cf])
  2319. // && isset($this->fontFamilies[$cf][$this->currentTextState])){
  2320. // // then we are in some state or another
  2321. // // and this font has a family, and the current setting exists within it
  2322. // // select the font, then return it
  2323. // $nf = substr($this->currentBaseFont,0,strrpos($this->currentBaseFont,'/')+1).$this->fontFamilies[$cf][$this->currentTextState];
  2324. // $this->selectFont($nf,'',0);
  2325. // $this->currentFont = $nf;
  2326. // $this->currentFontNum = $this->fonts[$nf]['fontNum'];
  2327. // } else {
  2328. // // the this font must not have the right family member for the current state
  2329. // // simply assume the base font
  2330. $this->currentFont = $this->currentBaseFont;
  2331. $this->currentFontNum = $this->fonts[$this->currentFont]['fontNum'];
  2332. // }
  2333. }
  2334. /**
  2335. * function for the user to find out what the ID is of the first page that was created during
  2336. * startup - useful if they wish to add something to it later.
  2337. */
  2338. function getFirstPageId()
  2339. {
  2340. return $this->firstPageId;
  2341. }
  2342. /**
  2343. * add content to the currently active object
  2344. */
  2345. private function addContent($content)
  2346. {
  2347. $this->objects[$this->currentContents]['c'] .= $content;
  2348. }
  2349. /**
  2350. * sets the color for fill operations
  2351. */
  2352. function setColor($color, $force = false)
  2353. {
  2354. $new_color = array($color[0], $color[1], $color[2], isset($color[3]) ? $color[3] : null);
  2355. if (!$force && $this->currentColor == $new_color) {
  2356. return;
  2357. }
  2358. if (isset($new_color[3])) {
  2359. $this->currentColor = $new_color;
  2360. $this->addContent(vsprintf("\n%.3F %.3F %.3F %.3F k", $this->currentColor));
  2361. } else {
  2362. if (isset($new_color[2])) {
  2363. $this->currentColor = $new_color;
  2364. $this->addContent(vsprintf("\n%.3F %.3F %.3F rg", $this->currentColor));
  2365. }
  2366. }
  2367. }
  2368. /**
  2369. * sets the color for fill operations
  2370. */
  2371. function setFillRule($fillRule)
  2372. {
  2373. if (!in_array($fillRule, array("nonzero", "evenodd"))) {
  2374. return;
  2375. }
  2376. $this->fillRule = $fillRule;
  2377. }
  2378. /**
  2379. * sets the color for stroke operations
  2380. */
  2381. function setStrokeColor($color, $force = false)
  2382. {
  2383. $new_color = array($color[0], $color[1], $color[2], isset($color[3]) ? $color[3] : null);
  2384. if (!$force && $this->currentStrokeColor == $new_color) {
  2385. return;
  2386. }
  2387. if (isset($new_color[3])) {
  2388. $this->currentStrokeColor = $new_color;
  2389. $this->addContent(vsprintf("\n%.3F %.3F %.3F %.3F K", $this->currentStrokeColor));
  2390. } else {
  2391. if (isset($new_color[2])) {
  2392. $this->currentStrokeColor = $new_color;
  2393. $this->addContent(vsprintf("\n%.3F %.3F %.3F RG", $this->currentStrokeColor));
  2394. }
  2395. }
  2396. }
  2397. /**
  2398. * Set the graphics state for compositions
  2399. */
  2400. function setGraphicsState($parameters)
  2401. {
  2402. // Create a new graphics state object
  2403. // FIXME: should actually keep track of states that have already been created...
  2404. $this->numObj++;
  2405. $this->o_extGState($this->numObj, 'new', $parameters);
  2406. $this->addContent("\n/GS$this->numStates gs");
  2407. }
  2408. /**
  2409. * Set current blend mode & opacity for lines.
  2410. *
  2411. * Valid blend modes are:
  2412. *
  2413. * Normal, Multiply, Screen, Overlay, Darken, Lighten,
  2414. * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
  2415. * Exclusion
  2416. *
  2417. * @param string $mode the blend mode to use
  2418. * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
  2419. */
  2420. function setLineTransparency($mode, $opacity)
  2421. {
  2422. static $blend_modes = array(
  2423. "Normal",
  2424. "Multiply",
  2425. "Screen",
  2426. "Overlay",
  2427. "Darken",
  2428. "Lighten",
  2429. "ColorDogde",
  2430. "ColorBurn",
  2431. "HardLight",
  2432. "SoftLight",
  2433. "Difference",
  2434. "Exclusion"
  2435. );
  2436. if (!in_array($mode, $blend_modes)) {
  2437. $mode = "Normal";
  2438. }
  2439. // Only create a new graphics state if required
  2440. if ($mode === $this->currentLineTransparency["mode"] &&
  2441. $opacity == $this->currentLineTransparency["opacity"]
  2442. ) {
  2443. return;
  2444. }
  2445. $this->currentLineTransparency["mode"] = $mode;
  2446. $this->currentLineTransparency["opacity"] = $opacity;
  2447. $options = array(
  2448. "BM" => "/$mode",
  2449. "CA" => (float)$opacity
  2450. );
  2451. $this->setGraphicsState($options);
  2452. }
  2453. /**
  2454. * Set current blend mode & opacity for filled objects.
  2455. *
  2456. * Valid blend modes are:
  2457. *
  2458. * Normal, Multiply, Screen, Overlay, Darken, Lighten,
  2459. * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
  2460. * Exclusion
  2461. *
  2462. * @param string $mode the blend mode to use
  2463. * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
  2464. */
  2465. function setFillTransparency($mode, $opacity)
  2466. {
  2467. static $blend_modes = array(
  2468. "Normal",
  2469. "Multiply",
  2470. "Screen",
  2471. "Overlay",
  2472. "Darken",
  2473. "Lighten",
  2474. "ColorDogde",
  2475. "ColorBurn",
  2476. "HardLight",
  2477. "SoftLight",
  2478. "Difference",
  2479. "Exclusion"
  2480. );
  2481. if (!in_array($mode, $blend_modes)) {
  2482. $mode = "Normal";
  2483. }
  2484. if ($mode === $this->currentFillTransparency["mode"] &&
  2485. $opacity == $this->currentFillTransparency["opacity"]
  2486. ) {
  2487. return;
  2488. }
  2489. $this->currentFillTransparency["mode"] = $mode;
  2490. $this->currentFillTransparency["opacity"] = $opacity;
  2491. $options = array(
  2492. "BM" => "/$mode",
  2493. "ca" => (float)$opacity,
  2494. );
  2495. $this->setGraphicsState($options);
  2496. }
  2497. /**
  2498. * draw a line from one set of coordinates to another
  2499. */
  2500. function line($x1, $y1, $x2, $y2, $stroke = true)
  2501. {
  2502. $this->addContent(sprintf("\n%.3F %.3F m %.3F %.3F l", $x1, $y1, $x2, $y2));
  2503. if ($stroke) {
  2504. $this->addContent(' S');
  2505. }
  2506. }
  2507. /**
  2508. * draw a bezier curve based on 4 control points
  2509. */
  2510. function curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3)
  2511. {
  2512. // in the current line style, draw a bezier curve from (x0,y0) to (x3,y3) using the other two points
  2513. // as the control points for the curve.
  2514. $this->addContent(
  2515. sprintf("\n%.3F %.3F m %.3F %.3F %.3F %.3F %.3F %.3F c S", $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3)
  2516. );
  2517. }
  2518. /**
  2519. * draw a part of an ellipse
  2520. */
  2521. function partEllipse($x0, $y0, $astart, $afinish, $r1, $r2 = 0, $angle = 0, $nSeg = 8)
  2522. {
  2523. $this->ellipse($x0, $y0, $r1, $r2, $angle, $nSeg, $astart, $afinish, false);
  2524. }
  2525. /**
  2526. * draw a filled ellipse
  2527. */
  2528. function filledEllipse($x0, $y0, $r1, $r2 = 0, $angle = 0, $nSeg = 8, $astart = 0, $afinish = 360)
  2529. {
  2530. return $this->ellipse($x0, $y0, $r1, $r2, $angle, $nSeg, $astart, $afinish, true, true);
  2531. }
  2532. function lineTo($x, $y)
  2533. {
  2534. $this->addContent(sprintf("\n%.3F %.3F l", $x, $y));
  2535. }
  2536. function moveTo($x, $y)
  2537. {
  2538. $this->addContent(sprintf("\n%.3F %.3F m", $x, $y));
  2539. }
  2540. /**
  2541. * draw a bezier curve based on 4 control points
  2542. */
  2543. function curveTo($x1, $y1, $x2, $y2, $x3, $y3)
  2544. {
  2545. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F %.3F %.3F c", $x1, $y1, $x2, $y2, $x3, $y3));
  2546. }
  2547. function closePath()
  2548. {
  2549. //$this->addContent(' s');
  2550. }
  2551. function endPath()
  2552. {
  2553. $this->addContent(' n');
  2554. }
  2555. /**
  2556. * draw an ellipse
  2557. * note that the part and filled ellipse are just special cases of this function
  2558. *
  2559. * draws an ellipse in the current line style
  2560. * centered at $x0,$y0, radii $r1,$r2
  2561. * if $r2 is not set, then a circle is drawn
  2562. * from $astart to $afinish, measured in degrees, running anti-clockwise from the right hand side of the ellipse.
  2563. * nSeg is not allowed to be less than 2, as this will simply draw a line (and will even draw a
  2564. * pretty crappy shape at 2, as we are approximating with bezier curves.
  2565. */
  2566. function ellipse(
  2567. $x0,
  2568. $y0,
  2569. $r1,
  2570. $r2 = 0,
  2571. $angle = 0,
  2572. $nSeg = 8,
  2573. $astart = 0,
  2574. $afinish = 360,
  2575. $close = true,
  2576. $fill = false,
  2577. $stroke = true,
  2578. $incomplete = false
  2579. ) {
  2580. if ($r1 == 0) {
  2581. return;
  2582. }
  2583. if ($r2 == 0) {
  2584. $r2 = $r1;
  2585. }
  2586. if ($nSeg < 2) {
  2587. $nSeg = 2;
  2588. }
  2589. $astart = deg2rad((float)$astart);
  2590. $afinish = deg2rad((float)$afinish);
  2591. $totalAngle = $afinish - $astart;
  2592. $dt = $totalAngle / $nSeg;
  2593. $dtm = $dt / 3;
  2594. if ($angle != 0) {
  2595. $a = -1 * deg2rad((float)$angle);
  2596. $this->addContent(
  2597. sprintf("\n q %.3F %.3F %.3F %.3F %.3F %.3F cm", cos($a), -sin($a), sin($a), cos($a), $x0, $y0)
  2598. );
  2599. $x0 = 0;
  2600. $y0 = 0;
  2601. }
  2602. $t1 = $astart;
  2603. $a0 = $x0 + $r1 * cos($t1);
  2604. $b0 = $y0 + $r2 * sin($t1);
  2605. $c0 = -$r1 * sin($t1);
  2606. $d0 = $r2 * cos($t1);
  2607. if (!$incomplete) {
  2608. $this->addContent(sprintf("\n%.3F %.3F m ", $a0, $b0));
  2609. }
  2610. for ($i = 1; $i <= $nSeg; $i++) {
  2611. // draw this bit of the total curve
  2612. $t1 = $i * $dt + $astart;
  2613. $a1 = $x0 + $r1 * cos($t1);
  2614. $b1 = $y0 + $r2 * sin($t1);
  2615. $c1 = -$r1 * sin($t1);
  2616. $d1 = $r2 * cos($t1);
  2617. $this->addContent(
  2618. sprintf(
  2619. "\n%.3F %.3F %.3F %.3F %.3F %.3F c",
  2620. ($a0 + $c0 * $dtm),
  2621. ($b0 + $d0 * $dtm),
  2622. ($a1 - $c1 * $dtm),
  2623. ($b1 - $d1 * $dtm),
  2624. $a1,
  2625. $b1
  2626. )
  2627. );
  2628. $a0 = $a1;
  2629. $b0 = $b1;
  2630. $c0 = $c1;
  2631. $d0 = $d1;
  2632. }
  2633. if (!$incomplete) {
  2634. if ($fill) {
  2635. $this->addContent(' f');
  2636. }
  2637. if ($stroke) {
  2638. if ($close) {
  2639. $this->addContent(' s'); // small 's' signifies closing the path as well
  2640. } else {
  2641. $this->addContent(' S');
  2642. }
  2643. }
  2644. }
  2645. if ($angle != 0) {
  2646. $this->addContent(' Q');
  2647. }
  2648. }
  2649. /**
  2650. * this sets the line drawing style.
  2651. * width, is the thickness of the line in user units
  2652. * cap is the type of cap to put on the line, values can be 'butt','round','square'
  2653. * where the diffference between 'square' and 'butt' is that 'square' projects a flat end past the
  2654. * end of the line.
  2655. * join can be 'miter', 'round', 'bevel'
  2656. * dash is an array which sets the dash pattern, is a series of length values, which are the lengths of the
  2657. * on and off dashes.
  2658. * (2) represents 2 on, 2 off, 2 on , 2 off ...
  2659. * (2,1) is 2 on, 1 off, 2 on, 1 off.. etc
  2660. * phase is a modifier on the dash pattern which is used to shift the point at which the pattern starts.
  2661. */
  2662. function setLineStyle($width = 1, $cap = '', $join = '', $dash = '', $phase = 0)
  2663. {
  2664. // this is quite inefficient in that it sets all the parameters whenever 1 is changed, but will fix another day
  2665. $string = '';
  2666. if ($width > 0) {
  2667. $string .= "$width w";
  2668. }
  2669. $ca = array('butt' => 0, 'round' => 1, 'square' => 2);
  2670. if (isset($ca[$cap])) {
  2671. $string .= " $ca[$cap] J";
  2672. }
  2673. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  2674. if (isset($ja[$join])) {
  2675. $string .= " $ja[$join] j";
  2676. }
  2677. if (is_array($dash)) {
  2678. $string .= ' [ ' . implode(' ', $dash) . " ] $phase d";
  2679. }
  2680. $this->currentLineStyle = $string;
  2681. $this->addContent("\n$string");
  2682. }
  2683. /**
  2684. * draw a polygon, the syntax for this is similar to the GD polygon command
  2685. */
  2686. function polygon($p, $np, $f = false)
  2687. {
  2688. $this->addContent(sprintf("\n%.3F %.3F m ", $p[0], $p[1]));
  2689. for ($i = 2; $i < $np * 2; $i = $i + 2) {
  2690. $this->addContent(sprintf("%.3F %.3F l ", $p[$i], $p[$i + 1]));
  2691. }
  2692. if ($f) {
  2693. $this->addContent(' f');
  2694. } else {
  2695. $this->addContent(' S');
  2696. }
  2697. }
  2698. /**
  2699. * a filled rectangle, note that it is the width and height of the rectangle which are the secondary parameters, not
  2700. * the coordinates of the upper-right corner
  2701. */
  2702. function filledRectangle($x1, $y1, $width, $height)
  2703. {
  2704. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re f", $x1, $y1, $width, $height));
  2705. }
  2706. /**
  2707. * draw a rectangle, note that it is the width and height of the rectangle which are the secondary parameters, not
  2708. * the coordinates of the upper-right corner
  2709. */
  2710. function rectangle($x1, $y1, $width, $height)
  2711. {
  2712. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re S", $x1, $y1, $width, $height));
  2713. }
  2714. /**
  2715. * draw a rectangle, note that it is the width and height of the rectangle which are the secondary parameters, not
  2716. * the coordinates of the upper-right corner
  2717. */
  2718. function rect($x1, $y1, $width, $height)
  2719. {
  2720. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re", $x1, $y1, $width, $height));
  2721. }
  2722. function stroke()
  2723. {
  2724. $this->addContent("\nS");
  2725. }
  2726. function fill()
  2727. {
  2728. $this->addContent("\nf" . ($this->fillRule === "evenodd" ? "*" : ""));
  2729. }
  2730. function fillStroke()
  2731. {
  2732. $this->addContent("\nb" . ($this->fillRule === "evenodd" ? "*" : ""));
  2733. }
  2734. /**
  2735. * save the current graphic state
  2736. */
  2737. function save()
  2738. {
  2739. // we must reset the color cache or it will keep bad colors after clipping
  2740. $this->currentColor = null;
  2741. $this->currentStrokeColor = null;
  2742. $this->addContent("\nq");
  2743. }
  2744. /**
  2745. * restore the last graphic state
  2746. */
  2747. function restore()
  2748. {
  2749. // we must reset the color cache or it will keep bad colors after clipping
  2750. $this->currentColor = null;
  2751. $this->currentStrokeColor = null;
  2752. $this->addContent("\nQ");
  2753. }
  2754. /**
  2755. * draw a clipping rectangle, all the elements added after this will be clipped
  2756. */
  2757. function clippingRectangle($x1, $y1, $width, $height)
  2758. {
  2759. $this->save();
  2760. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re W n", $x1, $y1, $width, $height));
  2761. }
  2762. /**
  2763. * draw a clipping rounded rectangle, all the elements added after this will be clipped
  2764. */
  2765. function clippingRectangleRounded($x1, $y1, $w, $h, $rTL, $rTR, $rBR, $rBL)
  2766. {
  2767. $this->save();
  2768. // start: top edge, left end
  2769. $this->addContent(sprintf("\n%.3F %.3F m ", $x1, $y1 - $rTL + $h));
  2770. // line: bottom edge, left end
  2771. $this->addContent(sprintf("\n%.3F %.3F l ", $x1, $y1 - $rBL));
  2772. // curve: bottom-left corner
  2773. $this->ellipse($x1 + $rBL, $y1 + $rBL, $rBL, 0, 0, 8, 180, 270, false, false, false, true);
  2774. // line: right edge, bottom end
  2775. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $w - $rBR, $y1));
  2776. // curve: bottom-right corner
  2777. $this->ellipse($x1 + $w - $rBR, $y1 + $rBR, $rBR, 0, 0, 8, 270, 360, false, false, false, true);
  2778. // line: right edge, top end
  2779. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $w, $y1 + $h - $rTR));
  2780. // curve: bottom-right corner
  2781. $this->ellipse($x1 + $w - $rTR, $y1 + $h - $rTR, $rTR, 0, 0, 8, 0, 90, false, false, false, true);
  2782. // line: bottom edge, right end
  2783. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $rTL, $y1 + $h));
  2784. // curve: top-right corner
  2785. $this->ellipse($x1 + $rTL, $y1 + $h - $rTL, $rTL, 0, 0, 8, 90, 180, false, false, false, true);
  2786. // line: top edge, left end
  2787. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $rBL, $y1));
  2788. // Close & clip
  2789. $this->addContent(" W n");
  2790. }
  2791. /**
  2792. * ends the last clipping shape
  2793. */
  2794. function clippingEnd()
  2795. {
  2796. $this->restore();
  2797. }
  2798. /**
  2799. * scale
  2800. *
  2801. * @param float $s_x scaling factor for width as percent
  2802. * @param float $s_y scaling factor for height as percent
  2803. * @param float $x Origin abscissa
  2804. * @param float $y Origin ordinate
  2805. */
  2806. function scale($s_x, $s_y, $x, $y)
  2807. {
  2808. $y = $this->currentPageSize["height"] - $y;
  2809. $tm = array(
  2810. $s_x,
  2811. 0,
  2812. 0,
  2813. $s_y,
  2814. $x * (1 - $s_x),
  2815. $y * (1 - $s_y)
  2816. );
  2817. $this->transform($tm);
  2818. }
  2819. /**
  2820. * translate
  2821. *
  2822. * @param float $t_x movement to the right
  2823. * @param float $t_y movement to the bottom
  2824. */
  2825. function translate($t_x, $t_y)
  2826. {
  2827. $tm = array(
  2828. 1,
  2829. 0,
  2830. 0,
  2831. 1,
  2832. $t_x,
  2833. -$t_y
  2834. );
  2835. $this->transform($tm);
  2836. }
  2837. /**
  2838. * rotate
  2839. *
  2840. * @param float $angle angle in degrees for counter-clockwise rotation
  2841. * @param float $x Origin abscissa
  2842. * @param float $y Origin ordinate
  2843. */
  2844. function rotate($angle, $x, $y)
  2845. {
  2846. $y = $this->currentPageSize["height"] - $y;
  2847. $a = deg2rad($angle);
  2848. $cos_a = cos($a);
  2849. $sin_a = sin($a);
  2850. $tm = array(
  2851. $cos_a,
  2852. -$sin_a,
  2853. $sin_a,
  2854. $cos_a,
  2855. $x - $sin_a * $y - $cos_a * $x,
  2856. $y - $cos_a * $y + $sin_a * $x,
  2857. );
  2858. $this->transform($tm);
  2859. }
  2860. /**
  2861. * skew
  2862. *
  2863. * @param float $angle_x
  2864. * @param float $angle_y
  2865. * @param float $x Origin abscissa
  2866. * @param float $y Origin ordinate
  2867. */
  2868. function skew($angle_x, $angle_y, $x, $y)
  2869. {
  2870. $y = $this->currentPageSize["height"] - $y;
  2871. $tan_x = tan(deg2rad($angle_x));
  2872. $tan_y = tan(deg2rad($angle_y));
  2873. $tm = array(
  2874. 1,
  2875. -$tan_y,
  2876. -$tan_x,
  2877. 1,
  2878. $tan_x * $y,
  2879. $tan_y * $x,
  2880. );
  2881. $this->transform($tm);
  2882. }
  2883. /**
  2884. * apply graphic transformations
  2885. *
  2886. * @param array $tm transformation matrix
  2887. */
  2888. function transform($tm)
  2889. {
  2890. $this->addContent(vsprintf("\n %.3F %.3F %.3F %.3F %.3F %.3F cm", $tm));
  2891. }
  2892. /**
  2893. * add a new page to the document
  2894. * this also makes the new page the current active object
  2895. */
  2896. function newPage($insert = 0, $id = 0, $pos = 'after')
  2897. {
  2898. // if there is a state saved, then go up the stack closing them
  2899. // then on the new page, re-open them with the right setings
  2900. if ($this->nStateStack) {
  2901. for ($i = $this->nStateStack; $i >= 1; $i--) {
  2902. $this->restoreState($i);
  2903. }
  2904. }
  2905. $this->numObj++;
  2906. if ($insert) {
  2907. // the id from the ezPdf class is the id of the contents of the page, not the page object itself
  2908. // query that object to find the parent
  2909. $rid = $this->objects[$id]['onPage'];
  2910. $opt = array('rid' => $rid, 'pos' => $pos);
  2911. $this->o_page($this->numObj, 'new', $opt);
  2912. } else {
  2913. $this->o_page($this->numObj, 'new');
  2914. }
  2915. // if there is a stack saved, then put that onto the page
  2916. if ($this->nStateStack) {
  2917. for ($i = 1; $i <= $this->nStateStack; $i++) {
  2918. $this->saveState($i);
  2919. }
  2920. }
  2921. // and if there has been a stroke or fill color set, then transfer them
  2922. if (isset($this->currentColor)) {
  2923. $this->setColor($this->currentColor, true);
  2924. }
  2925. if (isset($this->currentStrokeColor)) {
  2926. $this->setStrokeColor($this->currentStrokeColor, true);
  2927. }
  2928. // if there is a line style set, then put this in too
  2929. if (mb_strlen($this->currentLineStyle, '8bit')) {
  2930. $this->addContent("\n$this->currentLineStyle");
  2931. }
  2932. // the call to the o_page object set currentContents to the present page, so this can be returned as the page id
  2933. return $this->currentContents;
  2934. }
  2935. /**
  2936. * output the pdf code, streaming it to the browser
  2937. * the relevant headers are set so that hopefully the browser will recognise it
  2938. */
  2939. function stream($options = '')
  2940. {
  2941. // setting the options allows the adjustment of the headers
  2942. // values at the moment are:
  2943. // 'Content-Disposition' => 'filename' - sets the filename, though not too sure how well this will
  2944. // work as in my trial the browser seems to use the filename of the php file with .pdf on the end
  2945. // 'Accept-Ranges' => 1 or 0 - if this is not set to 1, then this header is not included, off by default
  2946. // this header seems to have caused some problems despite tha fact that it is supposed to solve
  2947. // them, so I am leaving it off by default.
  2948. // 'compress' = > 1 or 0 - apply content stream compression, this is on (1) by default
  2949. // 'Attachment' => 1 or 0 - if 1, force the browser to open a download dialog
  2950. if (!is_array($options)) {
  2951. $options = array();
  2952. }
  2953. if (headers_sent()) {
  2954. die("Unable to stream pdf: headers already sent");
  2955. }
  2956. $debug = empty($options['compression']);
  2957. $tmp = ltrim($this->output($debug));
  2958. header("Cache-Control: private");
  2959. header("Content-type: application/pdf");
  2960. //FIXME: I don't know that this is sufficient for determining content length (i.e. what about transport compression?)
  2961. header("Content-Length: " . mb_strlen($tmp, '8bit'));
  2962. $filename = (isset($options['Content-Disposition']) ? $options['Content-Disposition'] : 'document.pdf');
  2963. $filename = str_replace(array("\n", "'"), "", basename($filename)) . '.pdf';
  2964. if (!isset($options["Attachment"])) {
  2965. $options["Attachment"] = true;
  2966. }
  2967. $attachment = $options["Attachment"] ? "attachment" : "inline";
  2968. // detect the character encoding of the incoming file
  2969. $encoding = mb_detect_encoding($filename);
  2970. $fallbackfilename = mb_convert_encoding($filename, "ISO-8859-1", $encoding);
  2971. $encodedfallbackfilename = rawurlencode($fallbackfilename);
  2972. $encodedfilename = rawurlencode($filename);
  2973. header(
  2974. "Content-Disposition: $attachment; filename=" . $encodedfallbackfilename . "; filename*=UTF-8''$encodedfilename"
  2975. );
  2976. if (isset($options['Accept-Ranges']) && $options['Accept-Ranges'] == 1) {
  2977. //FIXME: Is this the correct value ... spec says 1#range-unit
  2978. header("Accept-Ranges: " . mb_strlen($tmp, '8bit'));
  2979. }
  2980. echo $tmp;
  2981. flush();
  2982. }
  2983. /**
  2984. * return the height in units of the current font in the given size
  2985. */
  2986. function getFontHeight($size)
  2987. {
  2988. if (!$this->numFonts) {
  2989. $this->selectFont($this->defaultFont);
  2990. }
  2991. $font = $this->fonts[$this->currentFont];
  2992. // for the current font, and the given size, what is the height of the font in user units
  2993. if (isset($font['Ascender']) && isset($font['Descender'])) {
  2994. $h = $font['Ascender'] - $font['Descender'];
  2995. } else {
  2996. $h = $font['FontBBox'][3] - $font['FontBBox'][1];
  2997. }
  2998. // have to adjust by a font offset for Windows fonts. unfortunately it looks like
  2999. // the bounding box calculations are wrong and I don't know why.
  3000. if (isset($font['FontHeightOffset'])) {
  3001. // For CourierNew from Windows this needs to be -646 to match the
  3002. // Adobe native Courier font.
  3003. //
  3004. // For FreeMono from GNU this needs to be -337 to match the
  3005. // Courier font.
  3006. //
  3007. // Both have been added manually to the .afm and .ufm files.
  3008. $h += (int)$font['FontHeightOffset'];
  3009. }
  3010. return $size * $h / 1000;
  3011. }
  3012. function getFontXHeight($size)
  3013. {
  3014. if (!$this->numFonts) {
  3015. $this->selectFont($this->defaultFont);
  3016. }
  3017. $font = $this->fonts[$this->currentFont];
  3018. // for the current font, and the given size, what is the height of the font in user units
  3019. if (isset($font['XHeight'])) {
  3020. $xh = $font['Ascender'] - $font['Descender'];
  3021. } else {
  3022. $xh = $this->getFontHeight($size) / 2;
  3023. }
  3024. return $size * $xh / 1000;
  3025. }
  3026. /**
  3027. * return the font descender, this will normally return a negative number
  3028. * if you add this number to the baseline, you get the level of the bottom of the font
  3029. * it is in the pdf user units
  3030. */
  3031. function getFontDescender($size)
  3032. {
  3033. // note that this will most likely return a negative value
  3034. if (!$this->numFonts) {
  3035. $this->selectFont($this->defaultFont);
  3036. }
  3037. //$h = $this->fonts[$this->currentFont]['FontBBox'][1];
  3038. $h = $this->fonts[$this->currentFont]['Descender'];
  3039. return $size * $h / 1000;
  3040. }
  3041. /**
  3042. * filter the text, this is applied to all text just before being inserted into the pdf document
  3043. * it escapes the various things that need to be escaped, and so on
  3044. *
  3045. * @access private
  3046. */
  3047. function filterText($text, $bom = true, $convert_encoding = true)
  3048. {
  3049. if (!$this->numFonts) {
  3050. $this->selectFont($this->defaultFont);
  3051. }
  3052. if ($convert_encoding) {
  3053. $cf = $this->currentFont;
  3054. if (isset($this->fonts[$cf]) && $this->fonts[$cf]['isUnicode']) {
  3055. $text = $this->utf8toUtf16BE($text, $bom);
  3056. } else {
  3057. //$text = html_entity_decode($text, ENT_QUOTES);
  3058. $text = mb_convert_encoding($text, self::$targetEncoding, 'UTF-8');
  3059. }
  3060. }
  3061. // the chr(13) substitution fixes a bug seen in TCPDF (bug #1421290)
  3062. return strtr($text, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
  3063. }
  3064. /**
  3065. * return array containing codepoints (UTF-8 character values) for the
  3066. * string passed in.
  3067. *
  3068. * based on the excellent TCPDF code by Nicola Asuni and the
  3069. * RFC for UTF-8 at http://www.faqs.org/rfcs/rfc3629.html
  3070. *
  3071. * @access private
  3072. * @author Orion Richardson
  3073. * @since January 5, 2008
  3074. *
  3075. * @param string $text UTF-8 string to process
  3076. *
  3077. * @return array UTF-8 codepoints array for the string
  3078. */
  3079. function utf8toCodePointsArray(&$text)
  3080. {
  3081. $length = mb_strlen($text, '8bit'); // http://www.php.net/manual/en/function.mb-strlen.php#77040
  3082. $unicode = array(); // array containing unicode values
  3083. $bytes = array(); // array containing single character byte sequences
  3084. $numbytes = 1; // number of octets needed to represent the UTF-8 character
  3085. for ($i = 0; $i < $length; $i++) {
  3086. $c = ord($text[$i]); // get one string character at time
  3087. if (count($bytes) === 0) { // get starting octect
  3088. if ($c <= 0x7F) {
  3089. $unicode[] = $c; // use the character "as is" because is ASCII
  3090. $numbytes = 1;
  3091. } elseif (($c >> 0x05) === 0x06) { // 2 bytes character (0x06 = 110 BIN)
  3092. $bytes[] = ($c - 0xC0) << 0x06;
  3093. $numbytes = 2;
  3094. } elseif (($c >> 0x04) === 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
  3095. $bytes[] = ($c - 0xE0) << 0x0C;
  3096. $numbytes = 3;
  3097. } elseif (($c >> 0x03) === 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
  3098. $bytes[] = ($c - 0xF0) << 0x12;
  3099. $numbytes = 4;
  3100. } else {
  3101. // use replacement character for other invalid sequences
  3102. $unicode[] = 0xFFFD;
  3103. $bytes = array();
  3104. $numbytes = 1;
  3105. }
  3106. } elseif (($c >> 0x06) === 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  3107. $bytes[] = $c - 0x80;
  3108. if (count($bytes) === $numbytes) {
  3109. // compose UTF-8 bytes to a single unicode value
  3110. $c = $bytes[0];
  3111. for ($j = 1; $j < $numbytes; $j++) {
  3112. $c += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
  3113. }
  3114. if ((($c >= 0xD800) AND ($c <= 0xDFFF)) OR ($c >= 0x10FFFF)) {
  3115. // The definition of UTF-8 prohibits encoding character numbers between
  3116. // U+D800 and U+DFFF, which are reserved for use with the UTF-16
  3117. // encoding form (as surrogate pairs) and do not directly represent
  3118. // characters.
  3119. $unicode[] = 0xFFFD; // use replacement character
  3120. } else {
  3121. $unicode[] = $c; // add char to array
  3122. }
  3123. // reset data for next char
  3124. $bytes = array();
  3125. $numbytes = 1;
  3126. }
  3127. } else {
  3128. // use replacement character for other invalid sequences
  3129. $unicode[] = 0xFFFD;
  3130. $bytes = array();
  3131. $numbytes = 1;
  3132. }
  3133. }
  3134. return $unicode;
  3135. }
  3136. /**
  3137. * convert UTF-8 to UTF-16 with an additional byte order marker
  3138. * at the front if required.
  3139. *
  3140. * based on the excellent TCPDF code by Nicola Asuni and the
  3141. * RFC for UTF-8 at http://www.faqs.org/rfcs/rfc3629.html
  3142. *
  3143. * @access private
  3144. * @author Orion Richardson
  3145. * @since January 5, 2008
  3146. *
  3147. * @param string $text UTF-8 string to process
  3148. * @param boolean $bom whether to add the byte order marker
  3149. *
  3150. * @return string UTF-16 result string
  3151. */
  3152. function utf8toUtf16BE(&$text, $bom = true)
  3153. {
  3154. $cf = $this->currentFont;
  3155. if (!$this->fonts[$cf]['isUnicode']) {
  3156. return $text;
  3157. }
  3158. $out = $bom ? "\xFE\xFF" : '';
  3159. $unicode = $this->utf8toCodePointsArray($text);
  3160. foreach ($unicode as $c) {
  3161. if ($c === 0xFFFD) {
  3162. $out .= "\xFF\xFD"; // replacement character
  3163. } elseif ($c < 0x10000) {
  3164. $out .= chr($c >> 0x08) . chr($c & 0xFF);
  3165. } else {
  3166. $c -= 0x10000;
  3167. $w1 = 0xD800 | ($c >> 0x10);
  3168. $w2 = 0xDC00 | ($c & 0x3FF);
  3169. $out .= chr($w1 >> 0x08) . chr($w1 & 0xFF) . chr($w2 >> 0x08) . chr($w2 & 0xFF);
  3170. }
  3171. }
  3172. return $out;
  3173. }
  3174. /**
  3175. * given a start position and information about how text is to be laid out, calculate where
  3176. * on the page the text will end
  3177. */
  3178. private function getTextPosition($x, $y, $angle, $size, $wa, $text)
  3179. {
  3180. // given this information return an array containing x and y for the end position as elements 0 and 1
  3181. $w = $this->getTextWidth($size, $text);
  3182. // need to adjust for the number of spaces in this text
  3183. $words = explode(' ', $text);
  3184. $nspaces = count($words) - 1;
  3185. $w += $wa * $nspaces;
  3186. $a = deg2rad((float)$angle);
  3187. return array(cos($a) * $w + $x, -sin($a) * $w + $y);
  3188. }
  3189. /**
  3190. * Callback method used by smallCaps
  3191. *
  3192. * @param array $matches
  3193. *
  3194. * @return string
  3195. */
  3196. function toUpper($matches)
  3197. {
  3198. return mb_strtoupper($matches[0]);
  3199. }
  3200. function concatMatches($matches)
  3201. {
  3202. $str = "";
  3203. foreach ($matches as $match) {
  3204. $str .= $match[0];
  3205. }
  3206. return $str;
  3207. }
  3208. /**
  3209. * add text to the document, at a specified location, size and angle on the page
  3210. */
  3211. function registerText($font, $text)
  3212. {
  3213. if (!$this->isUnicode || in_array(mb_strtolower(basename($font)), self::$coreFonts)) {
  3214. return;
  3215. }
  3216. if (!isset($this->stringSubsets[$font])) {
  3217. $this->stringSubsets[$font] = array();
  3218. }
  3219. $this->stringSubsets[$font] = array_unique(
  3220. array_merge($this->stringSubsets[$font], $this->utf8toCodePointsArray($text))
  3221. );
  3222. }
  3223. /**
  3224. * add text to the document, at a specified location, size and angle on the page
  3225. */
  3226. function addText($x, $y, $size, $text, $angle = 0, $wordSpaceAdjust = 0, $charSpaceAdjust = 0, $smallCaps = false)
  3227. {
  3228. if (!$this->numFonts) {
  3229. $this->selectFont($this->defaultFont);
  3230. }
  3231. $text = str_replace(array("\r", "\n"), "", $text);
  3232. if ($smallCaps) {
  3233. preg_match_all("/(\P{Ll}+)/u", $text, $matches, PREG_SET_ORDER);
  3234. $lower = $this->concatMatches($matches);
  3235. d($lower);
  3236. preg_match_all("/(\p{Ll}+)/u", $text, $matches, PREG_SET_ORDER);
  3237. $other = $this->concatMatches($matches);
  3238. d($other);
  3239. //$text = preg_replace_callback("/\p{Ll}/u", array($this, "toUpper"), $text);
  3240. }
  3241. // if there are any open callbacks, then they should be called, to show the start of the line
  3242. if ($this->nCallback > 0) {
  3243. for ($i = $this->nCallback; $i > 0; $i--) {
  3244. // call each function
  3245. $info = array(
  3246. 'x' => $x,
  3247. 'y' => $y,
  3248. 'angle' => $angle,
  3249. 'status' => 'sol',
  3250. 'p' => $this->callback[$i]['p'],
  3251. 'nCallback' => $this->callback[$i]['nCallback'],
  3252. 'height' => $this->callback[$i]['height'],
  3253. 'descender' => $this->callback[$i]['descender']
  3254. );
  3255. $func = $this->callback[$i]['f'];
  3256. $this->$func($info);
  3257. }
  3258. }
  3259. if ($angle == 0) {
  3260. $this->addContent(sprintf("\nBT %.3F %.3F Td", $x, $y));
  3261. } else {
  3262. $a = deg2rad((float)$angle);
  3263. $this->addContent(
  3264. sprintf("\nBT %.3F %.3F %.3F %.3F %.3F %.3F Tm", cos($a), -sin($a), sin($a), cos($a), $x, $y)
  3265. );
  3266. }
  3267. if ($wordSpaceAdjust != 0) {
  3268. $this->addContent(sprintf(" %.3F Tw", $wordSpaceAdjust));
  3269. }
  3270. if ($charSpaceAdjust != 0) {
  3271. $this->addContent(sprintf(" %.3F Tc", $charSpaceAdjust));
  3272. }
  3273. $len = mb_strlen($text);
  3274. $start = 0;
  3275. if ($start < $len) {
  3276. $part = $text; // OAR - Don't need this anymore, given that $start always equals zero. substr($text, $start);
  3277. $place_text = $this->filterText($part, false);
  3278. // modify unicode text so that extra word spacing is manually implemented (bug #)
  3279. $cf = $this->currentFont;
  3280. if ($this->fonts[$cf]['isUnicode'] && $wordSpaceAdjust != 0) {
  3281. $space_scale = 1000 / $size;
  3282. $place_text = str_replace("\x00\x20", "\x00\x20)\x00\x20" . (-round($space_scale * $wordSpaceAdjust)) . "\x00\x20(", $place_text);
  3283. }
  3284. $this->addContent(" /F$this->currentFontNum " . sprintf('%.1F Tf ', $size));
  3285. $this->addContent(" [($place_text)] TJ");
  3286. }
  3287. if ($wordSpaceAdjust != 0) {
  3288. $this->addContent(sprintf(" %.3F Tw", 0));
  3289. }
  3290. if ($charSpaceAdjust != 0) {
  3291. $this->addContent(sprintf(" %.3F Tc", 0));
  3292. }
  3293. $this->addContent(' ET');
  3294. // if there are any open callbacks, then they should be called, to show the end of the line
  3295. if ($this->nCallback > 0) {
  3296. for ($i = $this->nCallback; $i > 0; $i--) {
  3297. // call each function
  3298. $tmp = $this->getTextPosition($x, $y, $angle, $size, $wordSpaceAdjust, $text);
  3299. $info = array(
  3300. 'x' => $tmp[0],
  3301. 'y' => $tmp[1],
  3302. 'angle' => $angle,
  3303. 'status' => 'eol',
  3304. 'p' => $this->callback[$i]['p'],
  3305. 'nCallback' => $this->callback[$i]['nCallback'],
  3306. 'height' => $this->callback[$i]['height'],
  3307. 'descender' => $this->callback[$i]['descender']
  3308. );
  3309. $func = $this->callback[$i]['f'];
  3310. $this->$func($info);
  3311. }
  3312. }
  3313. }
  3314. /**
  3315. * calculate how wide a given text string will be on a page, at a given size.
  3316. * this can be called externally, but is also used by the other class functions
  3317. */
  3318. function getTextWidth($size, $text, $word_spacing = 0, $char_spacing = 0)
  3319. {
  3320. static $ord_cache = array();
  3321. // this function should not change any of the settings, though it will need to
  3322. // track any directives which change during calculation, so copy them at the start
  3323. // and put them back at the end.
  3324. $store_currentTextState = $this->currentTextState;
  3325. if (!$this->numFonts) {
  3326. $this->selectFont($this->defaultFont);
  3327. }
  3328. $text = str_replace(array("\r", "\n"), "", $text);
  3329. // converts a number or a float to a string so it can get the width
  3330. $text = "$text";
  3331. // hmm, this is where it all starts to get tricky - use the font information to
  3332. // calculate the width of each character, add them up and convert to user units
  3333. $w = 0;
  3334. $cf = $this->currentFont;
  3335. $current_font = $this->fonts[$cf];
  3336. $space_scale = 1000 / ($size > 0 ? $size : 1);
  3337. $n_spaces = 0;
  3338. if ($current_font['isUnicode']) {
  3339. // for Unicode, use the code points array to calculate width rather
  3340. // than just the string itself
  3341. $unicode = $this->utf8toCodePointsArray($text);
  3342. foreach ($unicode as $char) {
  3343. // check if we have to replace character
  3344. if (isset($current_font['differences'][$char])) {
  3345. $char = $current_font['differences'][$char];
  3346. }
  3347. if (isset($current_font['C'][$char])) {
  3348. $char_width = $current_font['C'][$char];
  3349. // add the character width
  3350. $w += $char_width;
  3351. // add additional padding for space
  3352. if (isset($current_font['codeToName'][$char]) && $current_font['codeToName'][$char] === 'space') { // Space
  3353. $w += $word_spacing * $space_scale;
  3354. $n_spaces++;
  3355. }
  3356. }
  3357. }
  3358. // add additional char spacing
  3359. if ($char_spacing != 0) {
  3360. $w += $char_spacing * $space_scale * (count($unicode) + $n_spaces);
  3361. }
  3362. } else {
  3363. // If CPDF is in Unicode mode but the current font does not support Unicode we need to convert the character set to Windows-1252
  3364. if ($this->isUnicode) {
  3365. $text = mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
  3366. }
  3367. $len = mb_strlen($text, 'Windows-1252');
  3368. for ($i = 0; $i < $len; $i++) {
  3369. $c = $text[$i];
  3370. $char = isset($ord_cache[$c]) ? $ord_cache[$c] : ($ord_cache[$c] = ord($c));
  3371. // check if we have to replace character
  3372. if (isset($current_font['differences'][$char])) {
  3373. $char = $current_font['differences'][$char];
  3374. }
  3375. if (isset($current_font['C'][$char])) {
  3376. $char_width = $current_font['C'][$char];
  3377. // add the character width
  3378. $w += $char_width;
  3379. // add additional padding for space
  3380. if (isset($current_font['codeToName'][$char]) && $current_font['codeToName'][$char] === 'space') { // Space
  3381. $w += $word_spacing * $space_scale;
  3382. $n_spaces++;
  3383. }
  3384. }
  3385. }
  3386. // add additional char spacing
  3387. if ($char_spacing != 0) {
  3388. $w += $char_spacing * $space_scale * ($len + $n_spaces);
  3389. }
  3390. }
  3391. $this->currentTextState = $store_currentTextState;
  3392. $this->setCurrentFont();
  3393. return $w * $size / 1000;
  3394. }
  3395. /**
  3396. * this will be called at a new page to return the state to what it was on the
  3397. * end of the previous page, before the stack was closed down
  3398. * This is to get around not being able to have open 'q' across pages
  3399. *
  3400. */
  3401. function saveState($pageEnd = 0)
  3402. {
  3403. if ($pageEnd) {
  3404. // this will be called at a new page to return the state to what it was on the
  3405. // end of the previous page, before the stack was closed down
  3406. // This is to get around not being able to have open 'q' across pages
  3407. $opt = $this->stateStack[$pageEnd];
  3408. // ok to use this as stack starts numbering at 1
  3409. $this->setColor($opt['col'], true);
  3410. $this->setStrokeColor($opt['str'], true);
  3411. $this->addContent("\n" . $opt['lin']);
  3412. // $this->currentLineStyle = $opt['lin'];
  3413. } else {
  3414. $this->nStateStack++;
  3415. $this->stateStack[$this->nStateStack] = array(
  3416. 'col' => $this->currentColor,
  3417. 'str' => $this->currentStrokeColor,
  3418. 'lin' => $this->currentLineStyle
  3419. );
  3420. }
  3421. $this->save();
  3422. }
  3423. /**
  3424. * restore a previously saved state
  3425. */
  3426. function restoreState($pageEnd = 0)
  3427. {
  3428. if (!$pageEnd) {
  3429. $n = $this->nStateStack;
  3430. $this->currentColor = $this->stateStack[$n]['col'];
  3431. $this->currentStrokeColor = $this->stateStack[$n]['str'];
  3432. $this->addContent("\n" . $this->stateStack[$n]['lin']);
  3433. $this->currentLineStyle = $this->stateStack[$n]['lin'];
  3434. $this->stateStack[$n] = null;
  3435. unset($this->stateStack[$n]);
  3436. $this->nStateStack--;
  3437. }
  3438. $this->restore();
  3439. }
  3440. /**
  3441. * make a loose object, the output will go into this object, until it is closed, then will revert to
  3442. * the current one.
  3443. * this object will not appear until it is included within a page.
  3444. * the function will return the object number
  3445. */
  3446. function openObject()
  3447. {
  3448. $this->nStack++;
  3449. $this->stack[$this->nStack] = array('c' => $this->currentContents, 'p' => $this->currentPage);
  3450. // add a new object of the content type, to hold the data flow
  3451. $this->numObj++;
  3452. $this->o_contents($this->numObj, 'new');
  3453. $this->currentContents = $this->numObj;
  3454. $this->looseObjects[$this->numObj] = 1;
  3455. return $this->numObj;
  3456. }
  3457. /**
  3458. * open an existing object for editing
  3459. */
  3460. function reopenObject($id)
  3461. {
  3462. $this->nStack++;
  3463. $this->stack[$this->nStack] = array('c' => $this->currentContents, 'p' => $this->currentPage);
  3464. $this->currentContents = $id;
  3465. // also if this object is the primary contents for a page, then set the current page to its parent
  3466. if (isset($this->objects[$id]['onPage'])) {
  3467. $this->currentPage = $this->objects[$id]['onPage'];
  3468. }
  3469. }
  3470. /**
  3471. * close an object
  3472. */
  3473. function closeObject()
  3474. {
  3475. // close the object, as long as there was one open in the first place, which will be indicated by
  3476. // an objectId on the stack.
  3477. if ($this->nStack > 0) {
  3478. $this->currentContents = $this->stack[$this->nStack]['c'];
  3479. $this->currentPage = $this->stack[$this->nStack]['p'];
  3480. $this->nStack--;
  3481. // easier to probably not worry about removing the old entries, they will be overwritten
  3482. // if there are new ones.
  3483. }
  3484. }
  3485. /**
  3486. * stop an object from appearing on pages from this point on
  3487. */
  3488. function stopObject($id)
  3489. {
  3490. // if an object has been appearing on pages up to now, then stop it, this page will
  3491. // be the last one that could contain it.
  3492. if (isset($this->addLooseObjects[$id])) {
  3493. $this->addLooseObjects[$id] = '';
  3494. }
  3495. }
  3496. /**
  3497. * after an object has been created, it wil only show if it has been added, using this function.
  3498. */
  3499. function addObject($id, $options = 'add')
  3500. {
  3501. // add the specified object to the page
  3502. if (isset($this->looseObjects[$id]) && $this->currentContents != $id) {
  3503. // then it is a valid object, and it is not being added to itself
  3504. switch ($options) {
  3505. case 'all':
  3506. // then this object is to be added to this page (done in the next block) and
  3507. // all future new pages.
  3508. $this->addLooseObjects[$id] = 'all';
  3509. case 'add':
  3510. if (isset($this->objects[$this->currentContents]['onPage'])) {
  3511. // then the destination contents is the primary for the page
  3512. // (though this object is actually added to that page)
  3513. $this->o_page($this->objects[$this->currentContents]['onPage'], 'content', $id);
  3514. }
  3515. break;
  3516. case 'even':
  3517. $this->addLooseObjects[$id] = 'even';
  3518. $pageObjectId = $this->objects[$this->currentContents]['onPage'];
  3519. if ($this->objects[$pageObjectId]['info']['pageNum'] % 2 == 0) {
  3520. $this->addObject($id);
  3521. // hacky huh :)
  3522. }
  3523. break;
  3524. case 'odd':
  3525. $this->addLooseObjects[$id] = 'odd';
  3526. $pageObjectId = $this->objects[$this->currentContents]['onPage'];
  3527. if ($this->objects[$pageObjectId]['info']['pageNum'] % 2 == 1) {
  3528. $this->addObject($id);
  3529. // hacky huh :)
  3530. }
  3531. break;
  3532. case 'next':
  3533. $this->addLooseObjects[$id] = 'all';
  3534. break;
  3535. case 'nexteven':
  3536. $this->addLooseObjects[$id] = 'even';
  3537. break;
  3538. case 'nextodd':
  3539. $this->addLooseObjects[$id] = 'odd';
  3540. break;
  3541. }
  3542. }
  3543. }
  3544. /**
  3545. * return a storable representation of a specific object
  3546. */
  3547. function serializeObject($id)
  3548. {
  3549. if (array_key_exists($id, $this->objects)) {
  3550. return serialize($this->objects[$id]);
  3551. }
  3552. }
  3553. /**
  3554. * restore an object from its stored representation. returns its new object id.
  3555. */
  3556. function restoreSerializedObject($obj)
  3557. {
  3558. $obj_id = $this->openObject();
  3559. $this->objects[$obj_id] = unserialize($obj);
  3560. $this->closeObject();
  3561. return $obj_id;
  3562. }
  3563. /**
  3564. * add content to the documents info object
  3565. */
  3566. function addInfo($label, $value = 0)
  3567. {
  3568. // this will only work if the label is one of the valid ones.
  3569. // modify this so that arrays can be passed as well.
  3570. // if $label is an array then assume that it is key => value pairs
  3571. // else assume that they are both scalar, anything else will probably error
  3572. if (is_array($label)) {
  3573. foreach ($label as $l => $v) {
  3574. $this->o_info($this->infoObject, $l, $v);
  3575. }
  3576. } else {
  3577. $this->o_info($this->infoObject, $label, $value);
  3578. }
  3579. }
  3580. /**
  3581. * set the viewer preferences of the document, it is up to the browser to obey these.
  3582. */
  3583. function setPreferences($label, $value = 0)
  3584. {
  3585. // this will only work if the label is one of the valid ones.
  3586. if (is_array($label)) {
  3587. foreach ($label as $l => $v) {
  3588. $this->o_catalog($this->catalogId, 'viewerPreferences', array($l => $v));
  3589. }
  3590. } else {
  3591. $this->o_catalog($this->catalogId, 'viewerPreferences', array($label => $value));
  3592. }
  3593. }
  3594. /**
  3595. * extract an integer from a position in a byte stream
  3596. */
  3597. private function getBytes(&$data, $pos, $num)
  3598. {
  3599. // return the integer represented by $num bytes from $pos within $data
  3600. $ret = 0;
  3601. for ($i = 0; $i < $num; $i++) {
  3602. $ret *= 256;
  3603. $ret += ord($data[$pos + $i]);
  3604. }
  3605. return $ret;
  3606. }
  3607. /**
  3608. * Check if image already added to pdf image directory.
  3609. * If yes, need not to create again (pass empty data)
  3610. */
  3611. function image_iscached($imgname)
  3612. {
  3613. return isset($this->imagelist[$imgname]);
  3614. }
  3615. /**
  3616. * add a PNG image into the document, from a GD object
  3617. * this should work with remote files
  3618. *
  3619. * @param string $file The PNG file
  3620. * @param float $x X position
  3621. * @param float $y Y position
  3622. * @param float $w Width
  3623. * @param float $h Height
  3624. * @param resource $img A GD resource
  3625. * @param bool $is_mask true if the image is a mask
  3626. * @param bool $mask true if the image is masked
  3627. */
  3628. function addImagePng($file, $x, $y, $w = 0.0, $h = 0.0, &$img, $is_mask = false, $mask = null)
  3629. {
  3630. if (!function_exists("imagepng")) {
  3631. throw new Exception("The PHP GD extension is required, but is not installed.");
  3632. }
  3633. //if already cached, need not to read again
  3634. if (isset($this->imagelist[$file])) {
  3635. $data = null;
  3636. } else {
  3637. // Example for transparency handling on new image. Retain for current image
  3638. // $tIndex = imagecolortransparent($img);
  3639. // if ($tIndex > 0) {
  3640. // $tColor = imagecolorsforindex($img, $tIndex);
  3641. // $new_tIndex = imagecolorallocate($new_img, $tColor['red'], $tColor['green'], $tColor['blue']);
  3642. // imagefill($new_img, 0, 0, $new_tIndex);
  3643. // imagecolortransparent($new_img, $new_tIndex);
  3644. // }
  3645. // blending mode (literal/blending) on drawing into current image. not relevant when not saved or not drawn
  3646. //imagealphablending($img, true);
  3647. //default, but explicitely set to ensure pdf compatibility
  3648. imagesavealpha($img, false/*!$is_mask && !$mask*/);
  3649. $error = 0;
  3650. //DEBUG_IMG_TEMP
  3651. //debugpng
  3652. if (defined("DEBUGPNG") && DEBUGPNG) {
  3653. print '[addImagePng ' . $file . ']';
  3654. }
  3655. ob_start();
  3656. @imagepng($img);
  3657. $data = ob_get_clean();
  3658. if ($data == '') {
  3659. $error = 1;
  3660. $errormsg = 'trouble writing file from GD';
  3661. //DEBUG_IMG_TEMP
  3662. //debugpng
  3663. if (defined("DEBUGPNG") && DEBUGPNG) {
  3664. print 'trouble writing file from GD';
  3665. }
  3666. }
  3667. if ($error) {
  3668. $this->addMessage('PNG error - (' . $file . ') ' . $errormsg);
  3669. return;
  3670. }
  3671. } //End isset($this->imagelist[$file]) (png Duplicate removal)
  3672. $this->addPngFromBuf($file, $x, $y, $w, $h, $data, $is_mask, $mask);
  3673. }
  3674. protected function addImagePngAlpha($file, $x, $y, $w, $h, $byte)
  3675. {
  3676. // generate images
  3677. $img = imagecreatefrompng($file);
  3678. if ($img === false) {
  3679. return;
  3680. }
  3681. // FIXME The pixel transformation doesn't work well with 8bit PNGs
  3682. $eight_bit = ($byte & 4) !== 4;
  3683. $wpx = imagesx($img);
  3684. $hpx = imagesy($img);
  3685. imagesavealpha($img, false);
  3686. // create temp alpha file
  3687. $tempfile_alpha = tempnam($this->tmp, "cpdf_img_");
  3688. @unlink($tempfile_alpha);
  3689. $tempfile_alpha = "$tempfile_alpha.png";
  3690. // create temp plain file
  3691. $tempfile_plain = tempnam($this->tmp, "cpdf_img_");
  3692. @unlink($tempfile_plain);
  3693. $tempfile_plain = "$tempfile_plain.png";
  3694. $imgalpha = imagecreate($wpx, $hpx);
  3695. imagesavealpha($imgalpha, false);
  3696. // generate gray scale palette (0 -> 255)
  3697. for ($c = 0; $c < 256; ++$c) {
  3698. imagecolorallocate($imgalpha, $c, $c, $c);
  3699. }
  3700. // Use PECL gmagick + Graphics Magic to process transparent PNG images
  3701. if (extension_loaded("gmagick")) {
  3702. $gmagick = new Gmagick($file);
  3703. $gmagick->setimageformat('png');
  3704. // Get opacity channel (negative of alpha channel)
  3705. $alpha_channel_neg = clone $gmagick;
  3706. $alpha_channel_neg->separateimagechannel(Gmagick::CHANNEL_OPACITY);
  3707. // Negate opacity channel
  3708. $alpha_channel = new Gmagick();
  3709. $alpha_channel->newimage($wpx, $hpx, "#FFFFFF", "png");
  3710. $alpha_channel->compositeimage($alpha_channel_neg, Gmagick::COMPOSITE_DIFFERENCE, 0, 0);
  3711. $alpha_channel->separateimagechannel(Gmagick::CHANNEL_RED);
  3712. $alpha_channel->writeimage($tempfile_alpha);
  3713. // Cast to 8bit+palette
  3714. $imgalpha_ = imagecreatefrompng($tempfile_alpha);
  3715. imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx);
  3716. imagedestroy($imgalpha_);
  3717. imagepng($imgalpha, $tempfile_alpha);
  3718. // Make opaque image
  3719. $color_channels = new Gmagick();
  3720. $color_channels->newimage($wpx, $hpx, "#FFFFFF", "png");
  3721. $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYRED, 0, 0);
  3722. $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYGREEN, 0, 0);
  3723. $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYBLUE, 0, 0);
  3724. $color_channels->writeimage($tempfile_plain);
  3725. $imgplain = imagecreatefrompng($tempfile_plain);
  3726. } // Use PECL imagick + ImageMagic to process transparent PNG images
  3727. elseif (extension_loaded("imagick")) {
  3728. // Native cloning was added to pecl-imagick in svn commit 263814
  3729. // the first version containing it was 3.0.1RC1
  3730. static $imagickClonable = null;
  3731. if ($imagickClonable === null) {
  3732. $imagickClonable = version_compare(phpversion('imagick'), '3.0.1rc1') > 0;
  3733. }
  3734. $imagick = new Imagick($file);
  3735. $imagick->setFormat('png');
  3736. // Get opacity channel (negative of alpha channel)
  3737. $alpha_channel = $imagickClonable ? clone $imagick : $imagick->clone();
  3738. $alpha_channel->separateImageChannel(Imagick::CHANNEL_ALPHA);
  3739. $alpha_channel->negateImage(true);
  3740. $alpha_channel->writeImage($tempfile_alpha);
  3741. // Cast to 8bit+palette
  3742. $imgalpha_ = imagecreatefrompng($tempfile_alpha);
  3743. imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx);
  3744. imagedestroy($imgalpha_);
  3745. imagepng($imgalpha, $tempfile_alpha);
  3746. // Make opaque image
  3747. $color_channels = new Imagick();
  3748. $color_channels->newImage($wpx, $hpx, "#FFFFFF", "png");
  3749. $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYRED, 0, 0);
  3750. $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYGREEN, 0, 0);
  3751. $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYBLUE, 0, 0);
  3752. $color_channels->writeImage($tempfile_plain);
  3753. $imgplain = imagecreatefrompng($tempfile_plain);
  3754. } else {
  3755. // allocated colors cache
  3756. $allocated_colors = array();
  3757. // extract alpha channel
  3758. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  3759. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  3760. $color = imagecolorat($img, $xpx, $ypx);
  3761. $col = imagecolorsforindex($img, $color);
  3762. $alpha = $col['alpha'];
  3763. if ($eight_bit) {
  3764. // with gamma correction
  3765. $gammacorr = 2.2;
  3766. $pixel = pow((((127 - $alpha) * 255 / 127) / 255), $gammacorr) * 255;
  3767. } else {
  3768. // without gamma correction
  3769. $pixel = (127 - $alpha) * 2;
  3770. $key = $col['red'] . $col['green'] . $col['blue'];
  3771. if (!isset($allocated_colors[$key])) {
  3772. $pixel_img = imagecolorallocate($img, $col['red'], $col['green'], $col['blue']);
  3773. $allocated_colors[$key] = $pixel_img;
  3774. } else {
  3775. $pixel_img = $allocated_colors[$key];
  3776. }
  3777. imagesetpixel($img, $xpx, $ypx, $pixel_img);
  3778. }
  3779. imagesetpixel($imgalpha, $xpx, $ypx, $pixel);
  3780. }
  3781. }
  3782. // extract image without alpha channel
  3783. $imgplain = imagecreatetruecolor($wpx, $hpx);
  3784. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  3785. imagedestroy($img);
  3786. imagepng($imgalpha, $tempfile_alpha);
  3787. imagepng($imgplain, $tempfile_plain);
  3788. }
  3789. // embed mask image
  3790. $this->addImagePng($tempfile_alpha, $x, $y, $w, $h, $imgalpha, true);
  3791. imagedestroy($imgalpha);
  3792. // embed image, masked with previously embedded mask
  3793. $this->addImagePng($tempfile_plain, $x, $y, $w, $h, $imgplain, false, true);
  3794. imagedestroy($imgplain);
  3795. // remove temp files
  3796. unlink($tempfile_alpha);
  3797. unlink($tempfile_plain);
  3798. }
  3799. /**
  3800. * add a PNG image into the document, from a file
  3801. * this should work with remote files
  3802. */
  3803. function addPngFromFile($file, $x, $y, $w = 0, $h = 0)
  3804. {
  3805. if (!function_exists("imagecreatefrompng")) {
  3806. throw new Exception("The PHP GD extension is required, but is not installed.");
  3807. }
  3808. //if already cached, need not to read again
  3809. if (isset($this->imagelist[$file])) {
  3810. $img = null;
  3811. } else {
  3812. $info = file_get_contents($file, false, null, 24, 5);
  3813. $meta = unpack("CbitDepth/CcolorType/CcompressionMethod/CfilterMethod/CinterlaceMethod", $info);
  3814. $bit_depth = $meta["bitDepth"];
  3815. $color_type = $meta["colorType"];
  3816. // http://www.w3.org/TR/PNG/#11IHDR
  3817. // 3 => indexed
  3818. // 4 => greyscale with alpha
  3819. // 6 => fullcolor with alpha
  3820. $is_alpha = in_array($color_type, array(4, 6)) || ($color_type == 3 && $bit_depth != 4);
  3821. if ($is_alpha) { // exclude grayscale alpha
  3822. return $this->addImagePngAlpha($file, $x, $y, $w, $h, $color_type);
  3823. }
  3824. //png files typically contain an alpha channel.
  3825. //pdf file format or class.pdf does not support alpha blending.
  3826. //on alpha blended images, more transparent areas have a color near black.
  3827. //This appears in the result on not storing the alpha channel.
  3828. //Correct would be the box background image or its parent when transparent.
  3829. //But this would make the image dependent on the background.
  3830. //Therefore create an image with white background and copy in
  3831. //A more natural background than black is white.
  3832. //Therefore create an empty image with white background and merge the
  3833. //image in with alpha blending.
  3834. $imgtmp = @imagecreatefrompng($file);
  3835. if (!$imgtmp) {
  3836. return;
  3837. }
  3838. $sx = imagesx($imgtmp);
  3839. $sy = imagesy($imgtmp);
  3840. $img = imagecreatetruecolor($sx, $sy);
  3841. imagealphablending($img, true);
  3842. // @todo is it still needed ??
  3843. $ti = imagecolortransparent($imgtmp);
  3844. if ($ti >= 0) {
  3845. $tc = imagecolorsforindex($imgtmp, $ti);
  3846. $ti = imagecolorallocate($img, $tc['red'], $tc['green'], $tc['blue']);
  3847. imagefill($img, 0, 0, $ti);
  3848. imagecolortransparent($img, $ti);
  3849. } else {
  3850. imagefill($img, 1, 1, imagecolorallocate($img, 255, 255, 255));
  3851. }
  3852. imagecopy($img, $imgtmp, 0, 0, 0, 0, $sx, $sy);
  3853. imagedestroy($imgtmp);
  3854. }
  3855. $this->addImagePng($file, $x, $y, $w, $h, $img);
  3856. if ($img) {
  3857. imagedestroy($img);
  3858. }
  3859. }
  3860. /**
  3861. * add a PNG image into the document, from a file
  3862. * this should work with remote files
  3863. */
  3864. function addSvgFromFile($file, $x, $y, $w = 0, $h = 0)
  3865. {
  3866. $doc = new \Svg\Document();
  3867. $doc->loadFile($file);
  3868. $dimensions = $doc->getDimensions();
  3869. $this->save();
  3870. $this->transform(array($w / $dimensions["width"], 0, 0, $h / $dimensions["height"], $x, $y));
  3871. $surface = new \Svg\Surface\SurfaceCpdf($doc, $this);
  3872. $doc->render($surface);
  3873. $this->restore();
  3874. }
  3875. /**
  3876. * add a PNG image into the document, from a memory buffer of the file
  3877. */
  3878. function addPngFromBuf($file, $x, $y, $w = 0.0, $h = 0.0, &$data, $is_mask = false, $mask = null)
  3879. {
  3880. if (isset($this->imagelist[$file])) {
  3881. $data = null;
  3882. $info['width'] = $this->imagelist[$file]['w'];
  3883. $info['height'] = $this->imagelist[$file]['h'];
  3884. $label = $this->imagelist[$file]['label'];
  3885. } else {
  3886. if ($data == null) {
  3887. $this->addMessage('addPngFromBuf error - data not present!');
  3888. return;
  3889. }
  3890. $error = 0;
  3891. if (!$error) {
  3892. $header = chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10);
  3893. if (mb_substr($data, 0, 8, '8bit') != $header) {
  3894. $error = 1;
  3895. if (defined("DEBUGPNG") && DEBUGPNG) {
  3896. print '[addPngFromFile this file does not have a valid header ' . $file . ']';
  3897. }
  3898. $errormsg = 'this file does not have a valid header';
  3899. }
  3900. }
  3901. if (!$error) {
  3902. // set pointer
  3903. $p = 8;
  3904. $len = mb_strlen($data, '8bit');
  3905. // cycle through the file, identifying chunks
  3906. $haveHeader = 0;
  3907. $info = array();
  3908. $idata = '';
  3909. $pdata = '';
  3910. while ($p < $len) {
  3911. $chunkLen = $this->getBytes($data, $p, 4);
  3912. $chunkType = mb_substr($data, $p + 4, 4, '8bit');
  3913. switch ($chunkType) {
  3914. case 'IHDR':
  3915. // this is where all the file information comes from
  3916. $info['width'] = $this->getBytes($data, $p + 8, 4);
  3917. $info['height'] = $this->getBytes($data, $p + 12, 4);
  3918. $info['bitDepth'] = ord($data[$p + 16]);
  3919. $info['colorType'] = ord($data[$p + 17]);
  3920. $info['compressionMethod'] = ord($data[$p + 18]);
  3921. $info['filterMethod'] = ord($data[$p + 19]);
  3922. $info['interlaceMethod'] = ord($data[$p + 20]);
  3923. //print_r($info);
  3924. $haveHeader = 1;
  3925. if ($info['compressionMethod'] != 0) {
  3926. $error = 1;
  3927. //debugpng
  3928. if (defined("DEBUGPNG") && DEBUGPNG) {
  3929. print '[addPngFromFile unsupported compression method ' . $file . ']';
  3930. }
  3931. $errormsg = 'unsupported compression method';
  3932. }
  3933. if ($info['filterMethod'] != 0) {
  3934. $error = 1;
  3935. //debugpng
  3936. if (defined("DEBUGPNG") && DEBUGPNG) {
  3937. print '[addPngFromFile unsupported filter method ' . $file . ']';
  3938. }
  3939. $errormsg = 'unsupported filter method';
  3940. }
  3941. break;
  3942. case 'PLTE':
  3943. $pdata .= mb_substr($data, $p + 8, $chunkLen, '8bit');
  3944. break;
  3945. case 'IDAT':
  3946. $idata .= mb_substr($data, $p + 8, $chunkLen, '8bit');
  3947. break;
  3948. case 'tRNS':
  3949. //this chunk can only occur once and it must occur after the PLTE chunk and before IDAT chunk
  3950. //print "tRNS found, color type = ".$info['colorType']."\n";
  3951. $transparency = array();
  3952. switch ($info['colorType']) {
  3953. // indexed color, rbg
  3954. case 3:
  3955. /* corresponding to entries in the plte chunk
  3956. Alpha for palette index 0: 1 byte
  3957. Alpha for palette index 1: 1 byte
  3958. ...etc...
  3959. */
  3960. // there will be one entry for each palette entry. up until the last non-opaque entry.
  3961. // set up an array, stretching over all palette entries which will be o (opaque) or 1 (transparent)
  3962. $transparency['type'] = 'indexed';
  3963. $trans = 0;
  3964. for ($i = $chunkLen; $i >= 0; $i--) {
  3965. if (ord($data[$p + 8 + $i]) == 0) {
  3966. $trans = $i;
  3967. }
  3968. }
  3969. $transparency['data'] = $trans;
  3970. break;
  3971. // grayscale
  3972. case 0:
  3973. /* corresponding to entries in the plte chunk
  3974. Gray: 2 bytes, range 0 .. (2^bitdepth)-1
  3975. */
  3976. // $transparency['grayscale'] = $this->PRVT_getBytes($data,$p+8,2); // g = grayscale
  3977. $transparency['type'] = 'indexed';
  3978. $transparency['data'] = ord($data[$p + 8 + 1]);
  3979. break;
  3980. // truecolor
  3981. case 2:
  3982. /* corresponding to entries in the plte chunk
  3983. Red: 2 bytes, range 0 .. (2^bitdepth)-1
  3984. Green: 2 bytes, range 0 .. (2^bitdepth)-1
  3985. Blue: 2 bytes, range 0 .. (2^bitdepth)-1
  3986. */
  3987. $transparency['r'] = $this->getBytes($data, $p + 8, 2);
  3988. // r from truecolor
  3989. $transparency['g'] = $this->getBytes($data, $p + 10, 2);
  3990. // g from truecolor
  3991. $transparency['b'] = $this->getBytes($data, $p + 12, 2);
  3992. // b from truecolor
  3993. $transparency['type'] = 'color-key';
  3994. break;
  3995. //unsupported transparency type
  3996. default:
  3997. if (defined("DEBUGPNG") && DEBUGPNG) {
  3998. print '[addPngFromFile unsupported transparency type ' . $file . ']';
  3999. }
  4000. break;
  4001. }
  4002. // KS End new code
  4003. break;
  4004. default:
  4005. break;
  4006. }
  4007. $p += $chunkLen + 12;
  4008. }
  4009. if (!$haveHeader) {
  4010. $error = 1;
  4011. //debugpng
  4012. if (defined("DEBUGPNG") && DEBUGPNG) {
  4013. print '[addPngFromFile information header is missing ' . $file . ']';
  4014. }
  4015. $errormsg = 'information header is missing';
  4016. }
  4017. if (isset($info['interlaceMethod']) && $info['interlaceMethod']) {
  4018. $error = 1;
  4019. //debugpng
  4020. if (defined("DEBUGPNG") && DEBUGPNG) {
  4021. print '[addPngFromFile no support for interlaced images in pdf ' . $file . ']';
  4022. }
  4023. $errormsg = 'There appears to be no support for interlaced images in pdf.';
  4024. }
  4025. }
  4026. if (!$error && $info['bitDepth'] > 8) {
  4027. $error = 1;
  4028. //debugpng
  4029. if (defined("DEBUGPNG") && DEBUGPNG) {
  4030. print '[addPngFromFile bit depth of 8 or less is supported ' . $file . ']';
  4031. }
  4032. $errormsg = 'only bit depth of 8 or less is supported';
  4033. }
  4034. if (!$error) {
  4035. switch ($info['colorType']) {
  4036. case 3:
  4037. $color = 'DeviceRGB';
  4038. $ncolor = 1;
  4039. break;
  4040. case 2:
  4041. $color = 'DeviceRGB';
  4042. $ncolor = 3;
  4043. break;
  4044. case 0:
  4045. $color = 'DeviceGray';
  4046. $ncolor = 1;
  4047. break;
  4048. default:
  4049. $error = 1;
  4050. //debugpng
  4051. if (defined("DEBUGPNG") && DEBUGPNG) {
  4052. print '[addPngFromFile alpha channel not supported: ' . $info['colorType'] . ' ' . $file . ']';
  4053. }
  4054. $errormsg = 'transparency alpha channel not supported, transparency only supported for palette images.';
  4055. }
  4056. }
  4057. if ($error) {
  4058. $this->addMessage('PNG error - (' . $file . ') ' . $errormsg);
  4059. return;
  4060. }
  4061. //print_r($info);
  4062. // so this image is ok... add it in.
  4063. $this->numImages++;
  4064. $im = $this->numImages;
  4065. $label = "I$im";
  4066. $this->numObj++;
  4067. // $this->o_image($this->numObj,'new',array('label' => $label,'data' => $idata,'iw' => $w,'ih' => $h,'type' => 'png','ic' => $info['width']));
  4068. $options = array(
  4069. 'label' => $label,
  4070. 'data' => $idata,
  4071. 'bitsPerComponent' => $info['bitDepth'],
  4072. 'pdata' => $pdata,
  4073. 'iw' => $info['width'],
  4074. 'ih' => $info['height'],
  4075. 'type' => 'png',
  4076. 'color' => $color,
  4077. 'ncolor' => $ncolor,
  4078. 'masked' => $mask,
  4079. 'isMask' => $is_mask
  4080. );
  4081. if (isset($transparency)) {
  4082. $options['transparency'] = $transparency;
  4083. }
  4084. $this->o_image($this->numObj, 'new', $options);
  4085. $this->imagelist[$file] = array('label' => $label, 'w' => $info['width'], 'h' => $info['height']);
  4086. }
  4087. if ($is_mask) {
  4088. return;
  4089. }
  4090. if ($w <= 0 && $h <= 0) {
  4091. $w = $info['width'];
  4092. $h = $info['height'];
  4093. }
  4094. if ($w <= 0) {
  4095. $w = $h / $info['height'] * $info['width'];
  4096. }
  4097. if ($h <= 0) {
  4098. $h = $w * $info['height'] / $info['width'];
  4099. }
  4100. $this->addContent(sprintf("\nq\n%.3F 0 0 %.3F %.3F %.3F cm /%s Do\nQ", $w, $h, $x, $y, $label));
  4101. }
  4102. /**
  4103. * add a JPEG image into the document, from a file
  4104. */
  4105. function addJpegFromFile($img, $x, $y, $w = 0, $h = 0)
  4106. {
  4107. // attempt to add a jpeg image straight from a file, using no GD commands
  4108. // note that this function is unable to operate on a remote file.
  4109. if (!file_exists($img)) {
  4110. return;
  4111. }
  4112. if ($this->image_iscached($img)) {
  4113. $data = null;
  4114. $imageWidth = $this->imagelist[$img]['w'];
  4115. $imageHeight = $this->imagelist[$img]['h'];
  4116. $channels = $this->imagelist[$img]['c'];
  4117. } else {
  4118. $tmp = getimagesize($img);
  4119. $imageWidth = $tmp[0];
  4120. $imageHeight = $tmp[1];
  4121. if (isset($tmp['channels'])) {
  4122. $channels = $tmp['channels'];
  4123. } else {
  4124. $channels = 3;
  4125. }
  4126. $data = file_get_contents($img);
  4127. }
  4128. if ($w <= 0 && $h <= 0) {
  4129. $w = $imageWidth;
  4130. }
  4131. if ($w == 0) {
  4132. $w = $h / $imageHeight * $imageWidth;
  4133. }
  4134. if ($h == 0) {
  4135. $h = $w * $imageHeight / $imageWidth;
  4136. }
  4137. $this->addJpegImage_common($data, $x, $y, $w, $h, $imageWidth, $imageHeight, $channels, $img);
  4138. }
  4139. /**
  4140. * common code used by the two JPEG adding functions
  4141. */
  4142. private function addJpegImage_common(
  4143. &$data,
  4144. $x,
  4145. $y,
  4146. $w = 0,
  4147. $h = 0,
  4148. $imageWidth,
  4149. $imageHeight,
  4150. $channels = 3,
  4151. $imgname
  4152. ) {
  4153. if ($this->image_iscached($imgname)) {
  4154. $label = $this->imagelist[$imgname]['label'];
  4155. //debugpng
  4156. //if (DEBUGPNG) print '[addJpegImage_common Duplicate '.$imgname.']';
  4157. } else {
  4158. if ($data == null) {
  4159. $this->addMessage('addJpegImage_common error - (' . $imgname . ') data not present!');
  4160. return;
  4161. }
  4162. // note that this function is not to be called externally
  4163. // it is just the common code between the GD and the file options
  4164. $this->numImages++;
  4165. $im = $this->numImages;
  4166. $label = "I$im";
  4167. $this->numObj++;
  4168. $this->o_image(
  4169. $this->numObj,
  4170. 'new',
  4171. array(
  4172. 'label' => $label,
  4173. 'data' => &$data,
  4174. 'iw' => $imageWidth,
  4175. 'ih' => $imageHeight,
  4176. 'channels' => $channels
  4177. )
  4178. );
  4179. $this->imagelist[$imgname] = array(
  4180. 'label' => $label,
  4181. 'w' => $imageWidth,
  4182. 'h' => $imageHeight,
  4183. 'c' => $channels
  4184. );
  4185. }
  4186. $this->addContent(sprintf("\nq\n%.3F 0 0 %.3F %.3F %.3F cm /%s Do\nQ ", $w, $h, $x, $y, $label));
  4187. }
  4188. /**
  4189. * specify where the document should open when it first starts
  4190. */
  4191. function openHere($style, $a = 0, $b = 0, $c = 0)
  4192. {
  4193. // this function will open the document at a specified page, in a specified style
  4194. // the values for style, and the required parameters are:
  4195. // 'XYZ' left, top, zoom
  4196. // 'Fit'
  4197. // 'FitH' top
  4198. // 'FitV' left
  4199. // 'FitR' left,bottom,right
  4200. // 'FitB'
  4201. // 'FitBH' top
  4202. // 'FitBV' left
  4203. $this->numObj++;
  4204. $this->o_destination(
  4205. $this->numObj,
  4206. 'new',
  4207. array('page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c)
  4208. );
  4209. $id = $this->catalogId;
  4210. $this->o_catalog($id, 'openHere', $this->numObj);
  4211. }
  4212. /**
  4213. * Add JavaScript code to the PDF document
  4214. *
  4215. * @param string $code
  4216. *
  4217. * @return void
  4218. */
  4219. function addJavascript($code)
  4220. {
  4221. $this->javascript .= $code;
  4222. }
  4223. /**
  4224. * create a labelled destination within the document
  4225. */
  4226. function addDestination($label, $style, $a = 0, $b = 0, $c = 0)
  4227. {
  4228. // associates the given label with the destination, it is done this way so that a destination can be specified after
  4229. // it has been linked to
  4230. // styles are the same as the 'openHere' function
  4231. $this->numObj++;
  4232. $this->o_destination(
  4233. $this->numObj,
  4234. 'new',
  4235. array('page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c)
  4236. );
  4237. $id = $this->numObj;
  4238. // store the label->idf relationship, note that this means that labels can be used only once
  4239. $this->destinations["$label"] = $id;
  4240. }
  4241. /**
  4242. * define font families, this is used to initialize the font families for the default fonts
  4243. * and for the user to add new ones for their fonts. The default bahavious can be overridden should
  4244. * that be desired.
  4245. */
  4246. function setFontFamily($family, $options = '')
  4247. {
  4248. if (!is_array($options)) {
  4249. if ($family === 'init') {
  4250. // set the known family groups
  4251. // these font families will be used to enable bold and italic markers to be included
  4252. // within text streams. html forms will be used... <b></b> <i></i>
  4253. $this->fontFamilies['Helvetica.afm'] =
  4254. array(
  4255. 'b' => 'Helvetica-Bold.afm',
  4256. 'i' => 'Helvetica-Oblique.afm',
  4257. 'bi' => 'Helvetica-BoldOblique.afm',
  4258. 'ib' => 'Helvetica-BoldOblique.afm'
  4259. );
  4260. $this->fontFamilies['Courier.afm'] =
  4261. array(
  4262. 'b' => 'Courier-Bold.afm',
  4263. 'i' => 'Courier-Oblique.afm',
  4264. 'bi' => 'Courier-BoldOblique.afm',
  4265. 'ib' => 'Courier-BoldOblique.afm'
  4266. );
  4267. $this->fontFamilies['Times-Roman.afm'] =
  4268. array(
  4269. 'b' => 'Times-Bold.afm',
  4270. 'i' => 'Times-Italic.afm',
  4271. 'bi' => 'Times-BoldItalic.afm',
  4272. 'ib' => 'Times-BoldItalic.afm'
  4273. );
  4274. }
  4275. } else {
  4276. // the user is trying to set a font family
  4277. // note that this can also be used to set the base ones to something else
  4278. if (mb_strlen($family)) {
  4279. $this->fontFamilies[$family] = $options;
  4280. }
  4281. }
  4282. }
  4283. /**
  4284. * used to add messages for use in debugging
  4285. */
  4286. function addMessage($message)
  4287. {
  4288. $this->messages .= $message . "\n";
  4289. }
  4290. /**
  4291. * a few functions which should allow the document to be treated transactionally.
  4292. */
  4293. function transaction($action)
  4294. {
  4295. switch ($action) {
  4296. case 'start':
  4297. // store all the data away into the checkpoint variable
  4298. $data = get_object_vars($this);
  4299. $this->checkpoint = $data;
  4300. unset($data);
  4301. break;
  4302. case 'commit':
  4303. if (is_array($this->checkpoint) && isset($this->checkpoint['checkpoint'])) {
  4304. $tmp = $this->checkpoint['checkpoint'];
  4305. $this->checkpoint = $tmp;
  4306. unset($tmp);
  4307. } else {
  4308. $this->checkpoint = '';
  4309. }
  4310. break;
  4311. case 'rewind':
  4312. // do not destroy the current checkpoint, but move us back to the state then, so that we can try again
  4313. if (is_array($this->checkpoint)) {
  4314. // can only abort if were inside a checkpoint
  4315. $tmp = $this->checkpoint;
  4316. foreach ($tmp as $k => $v) {
  4317. if ($k !== 'checkpoint') {
  4318. $this->$k = $v;
  4319. }
  4320. }
  4321. unset($tmp);
  4322. }
  4323. break;
  4324. case 'abort':
  4325. if (is_array($this->checkpoint)) {
  4326. // can only abort if were inside a checkpoint
  4327. $tmp = $this->checkpoint;
  4328. foreach ($tmp as $k => $v) {
  4329. $this->$k = $v;
  4330. }
  4331. unset($tmp);
  4332. }
  4333. break;
  4334. }
  4335. }
  4336. }