PageRenderTime 93ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/class.pdf.php

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