PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/smartpdf/code/lib/Cpdf.php

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