PageRenderTime 78ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/phenx/php-svg-lib/src/Svg/Surface/CPdf.php

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