PageRenderTime 117ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 1ms

/filemanager/tp/dompdf/lib/class.pdf.php

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