PageRenderTime 72ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/mainapp/plugins/dompdf/lib/class.pdf.php

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