PageRenderTime 39ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/include/PHPExcel/Writer/PDF/lib/class.pdf.php

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