Pdf.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Pdf
  17. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /** Zend_Pdf_Page */
  21. require_once 'Zend/Pdf/Page.php';
  22. /** Zend_Pdf_Cmap */
  23. require_once 'Zend/Pdf/Cmap.php';
  24. /** Zend_Pdf_Font */
  25. require_once 'Zend/Pdf/Font.php';
  26. /** Zend_Pdf_Style */
  27. require_once 'Zend/Pdf/Style.php';
  28. /** Zend_Pdf_Parser */
  29. require_once 'Zend/Pdf/Parser.php';
  30. /** Zend_Pdf_Trailer */
  31. require_once 'Zend/Pdf/Trailer.php';
  32. /** Zend_Pdf_Trailer_Generator */
  33. require_once 'Zend/Pdf/Trailer/Generator.php';
  34. /** Zend_Pdf_Color */
  35. require_once 'Zend/Pdf/Color.php';
  36. /** Zend_Pdf_Color_GrayScale */
  37. require_once 'Zend/Pdf/Color/GrayScale.php';
  38. /** Zend_Pdf_Color_Rgb */
  39. require_once 'Zend/Pdf/Color/Rgb.php';
  40. /** Zend_Pdf_Color_Cmyk */
  41. require_once 'Zend/Pdf/Color/Cmyk.php';
  42. /** Zend_Pdf_Color_Html */
  43. require_once 'Zend/Pdf/Color/Html.php';
  44. /** Zend_Pdf_Image */
  45. require_once 'Zend/Pdf/Resource/Image.php';
  46. /** Zend_Pdf_Image */
  47. require_once 'Zend/Pdf/Image.php';
  48. /** Zend_Pdf_Image_Jpeg */
  49. require_once 'Zend/Pdf/Resource/Image/Jpeg.php';
  50. /** Zend_Pdf_Image_Tiff */
  51. require_once 'Zend/Pdf/Resource/Image/Tiff.php';
  52. /** Zend_Pdf_Image_Png */
  53. require_once 'Zend/Pdf/Resource/Image/Png.php';
  54. /** Zend_Memory */
  55. require_once 'Zend/Memory.php';
  56. /**
  57. * General entity which describes PDF document.
  58. * It implements document abstraction with a document level operations.
  59. *
  60. * Class is used to create new PDF document or load existing document.
  61. * See details in a class constructor description
  62. *
  63. * Class agregates document level properties and entities (pages, bookmarks,
  64. * document level actions, attachments, form object, etc)
  65. *
  66. * @category Zend
  67. * @package Zend_Pdf
  68. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  69. * @license http://framework.zend.com/license/new-bsd New BSD License
  70. */
  71. class Zend_Pdf
  72. {
  73. /**** Class Constants ****/
  74. /**
  75. * Version number of generated PDF documents.
  76. */
  77. const PDF_VERSION = '1.4';
  78. /**
  79. * PDF file header.
  80. */
  81. const PDF_HEADER = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
  82. /**
  83. * Pages collection
  84. *
  85. * @todo implement it as a class, which supports ArrayAccess and Iterator interfaces,
  86. * to provide incremental parsing and pages tree updating.
  87. * That will give good performance and memory (PDF size) benefits.
  88. *
  89. * @var array - array of Zend_Pdf_Page object
  90. */
  91. public $pages = array();
  92. /**
  93. * Document properties
  94. *
  95. * It's an associative array with PDF meta information, values may
  96. * be string, boolean or float.
  97. * Returned array could be used directly to access, add, modify or remove
  98. * document properties.
  99. *
  100. * Standard document properties: Title (must be set for PDF/X documents), Author,
  101. * Subject, Keywords (comma separated list), Creator (the name of the application,
  102. * that created document, if it was converted from other format), Trapped (must be
  103. * true, false or null, can not be null for PDF/X documents)
  104. *
  105. * @var array
  106. */
  107. public $properties = array();
  108. /**
  109. * Original properties set.
  110. *
  111. * Used for tracking properties changes
  112. *
  113. * @var array
  114. */
  115. protected $_originalProperties = array();
  116. /**
  117. * Document level javascript
  118. *
  119. * @var string
  120. */
  121. protected $_javaScript = null;
  122. /**
  123. * Document named actions
  124. * "GoTo..." actions, used to refer document parts
  125. * from outside PDF
  126. *
  127. * @var array - array of Zend_Pdf_Action objects
  128. */
  129. protected $_namedActions = array();
  130. /**
  131. * Pdf trailer (last or just created)
  132. *
  133. * @var Zend_Pdf_Trailer
  134. */
  135. protected $_trailer = null;
  136. /**
  137. * PDF version specified in the file header
  138. *
  139. * @var string
  140. */
  141. protected $_pdfHeaderVersion;
  142. /**
  143. * PDF objects factory.
  144. *
  145. * @var Zend_Pdf_ElementFactory_Interface
  146. */
  147. protected $_objFactory = null;
  148. /**
  149. * Memory manager for stream objects
  150. *
  151. * @var Zend_Memory_Manager|null
  152. */
  153. protected static $_memoryManager = null;
  154. /**
  155. * Pdf file parser.
  156. * It's not used, but has to be destroyed only with Zend_Pdf object
  157. *
  158. * @var Zend_Pdf_Parser
  159. */
  160. protected $_parser;
  161. /**
  162. * List of inheritable attributesfor pages tree
  163. *
  164. * @var array
  165. */
  166. protected static $_inheritableAttributes = array('Resources', 'MediaBox', 'CropBox', 'Rotate');
  167. /**
  168. * Request used memory manager
  169. *
  170. * @return Zend_Memory_Manager
  171. */
  172. static public function getMemoryManager()
  173. {
  174. if (self::$_memoryManager === null) {
  175. self::$_memoryManager = Zend_Memory::factory('none');
  176. }
  177. return self::$_memoryManager;
  178. }
  179. /**
  180. * Set user defined memory manager
  181. *
  182. * @param Zend_Memory_Manager $memoryManager
  183. */
  184. static public function setMemoryManager(Zend_Memory_Manager $memoryManager)
  185. {
  186. self::$_memoryManager = $memoryManager;
  187. }
  188. /**
  189. * Create new PDF document from a $source string
  190. *
  191. * @param string $source
  192. * @param integer $revision
  193. * @return Zend_Pdf
  194. */
  195. public static function parse(&$source = null, $revision = null)
  196. {
  197. return new Zend_Pdf($source, $revision);
  198. }
  199. /**
  200. * Load PDF document from a file
  201. *
  202. * @param string $source
  203. * @param integer $revision
  204. * @return Zend_Pdf
  205. */
  206. public static function load($source = null, $revision = null)
  207. {
  208. return new Zend_Pdf($source, $revision, true);
  209. }
  210. /**
  211. * Render PDF document and save it.
  212. *
  213. * If $updateOnly is true, then it only appends new section to the end of file.
  214. *
  215. * @param string $filename
  216. * @param boolean $updateOnly
  217. * @throws Zend_Pdf_Exception
  218. */
  219. public function save($filename, $updateOnly = false)
  220. {
  221. if (($file = @fopen($filename, $updateOnly ? 'ab':'wb')) === false ) {
  222. require_once 'Zend/Pdf/Exception.php';
  223. throw new Zend_Pdf_Exception( "Can not open '$filename' file for writing." );
  224. }
  225. $this->render($updateOnly, $file);
  226. fclose($file);
  227. }
  228. /**
  229. * Creates or loads PDF document.
  230. *
  231. * If $source is null, then it creates a new document.
  232. *
  233. * If $source is a string and $load is false, then it loads document
  234. * from a binary string.
  235. *
  236. * If $source is a string and $load is true, then it loads document
  237. * from a file.
  238. * $revision used to roll back document to specified version
  239. * (0 - currtent version, 1 - previous version, 2 - ...)
  240. *
  241. * @param string $source - PDF file to load
  242. * @param integer $revision
  243. * @throws Zend_Pdf_Exception
  244. * @return Zend_Pdf
  245. */
  246. public function __construct($source = null, $revision = null, $load = false)
  247. {
  248. $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1);
  249. if ($source !== null) {
  250. $this->_parser = new Zend_Pdf_Parser($source, $this->_objFactory, $load);
  251. $this->_pdfHeaderVersion = $this->_parser->getPDFVersion();
  252. $this->_trailer = $this->_parser->getTrailer();
  253. if ($this->_trailer->Encrypt !== null) {
  254. require_once 'Zend/Pdf/Exception.php';
  255. throw new Zend_Pdf_Exception('Encrypted document modification is not supported');
  256. }
  257. if ($revision !== null) {
  258. $this->rollback($revision);
  259. } else {
  260. $this->_loadPages($this->_trailer->Root->Pages);
  261. }
  262. if ($this->_trailer->Info !== null) {
  263. $this->properties = $this->_trailer->Info->toPhp();
  264. if (isset($this->properties['Trapped'])) {
  265. switch ($this->properties['Trapped']) {
  266. case 'True':
  267. $this->properties['Trapped'] = true;
  268. break;
  269. case 'False':
  270. $this->properties['Trapped'] = false;
  271. break;
  272. case 'Unknown':
  273. $this->properties['Trapped'] = null;
  274. break;
  275. default:
  276. // Wrong property value
  277. // Do nothing
  278. break;
  279. }
  280. }
  281. $this->_originalProperties = $this->properties;
  282. }
  283. } else {
  284. $this->_pdfHeaderVersion = Zend_Pdf::PDF_VERSION;
  285. $trailerDictionary = new Zend_Pdf_Element_Dictionary();
  286. /**
  287. * Document id
  288. */
  289. $docId = md5(uniqid(rand(), true)); // 32 byte (128 bit) identifier
  290. $docIdLow = substr($docId, 0, 16); // first 16 bytes
  291. $docIdHigh = substr($docId, 16, 16); // second 16 bytes
  292. $trailerDictionary->ID = new Zend_Pdf_Element_Array();
  293. $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdLow);
  294. $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdHigh);
  295. $trailerDictionary->Size = new Zend_Pdf_Element_Numeric(0);
  296. $this->_trailer = new Zend_Pdf_Trailer_Generator($trailerDictionary);
  297. /**
  298. * Document catalog indirect object.
  299. */
  300. $docCatalog = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  301. $docCatalog->Type = new Zend_Pdf_Element_Name('Catalog');
  302. $docCatalog->Version = new Zend_Pdf_Element_Name(Zend_Pdf::PDF_VERSION);
  303. $this->_trailer->Root = $docCatalog;
  304. /**
  305. * Pages container
  306. */
  307. $docPages = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  308. $docPages->Type = new Zend_Pdf_Element_Name('Pages');
  309. $docPages->Kids = new Zend_Pdf_Element_Array();
  310. $docPages->Count = new Zend_Pdf_Element_Numeric(0);
  311. $docCatalog->Pages = $docPages;
  312. }
  313. }
  314. /**
  315. * Retrive number of revisions.
  316. *
  317. * @return integer
  318. */
  319. public function revisions()
  320. {
  321. $revisions = 1;
  322. $currentTrailer = $this->_trailer;
  323. while ($currentTrailer->getPrev() !== null && $currentTrailer->getPrev()->Root !== null ) {
  324. $revisions++;
  325. $currentTrailer = $currentTrailer->getPrev();
  326. }
  327. return $revisions++;
  328. }
  329. /**
  330. * Rollback document $steps number of revisions.
  331. * This method must be invoked before any changes, applied to the document.
  332. * Otherwise behavior is undefined.
  333. *
  334. * @param integer $steps
  335. */
  336. public function rollback($steps)
  337. {
  338. for ($count = 0; $count < $steps; $count++) {
  339. if ($this->_trailer->getPrev() !== null && $this->_trailer->getPrev()->Root !== null) {
  340. $this->_trailer = $this->_trailer->getPrev();
  341. } else {
  342. break;
  343. }
  344. }
  345. $this->_objFactory->setObjectCount($this->_trailer->Size->value);
  346. // Mark content as modified to force new trailer generation at render time
  347. $this->_trailer->Root->touch();
  348. $this->pages = array();
  349. $this->_loadPages($this->_trailer->Root->Pages);
  350. }
  351. /**
  352. * Load pages recursively
  353. *
  354. * @param Zend_Pdf_Element_Reference $pages
  355. * @param array|null $attributes
  356. */
  357. protected function _loadPages(Zend_Pdf_Element_Reference $pages, $attributes = array())
  358. {
  359. if ($pages->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
  360. require_once 'Zend/Pdf/Exception.php';
  361. throw new Zend_Pdf_Exception('Wrong argument');
  362. }
  363. foreach ($pages->getKeys() as $property) {
  364. if (in_array($property, self::$_inheritableAttributes)) {
  365. $attributes[$property] = $pages->$property;
  366. $pages->$property = null;
  367. }
  368. }
  369. foreach ($pages->Kids->items as $child) {
  370. if ($child->Type->value == 'Pages') {
  371. $this->_loadPages($child, $attributes);
  372. } else if ($child->Type->value == 'Page') {
  373. foreach (self::$_inheritableAttributes as $property) {
  374. if ($child->$property === null && array_key_exists($property, $attributes)) {
  375. /**
  376. * Important note.
  377. * If any attribute or dependant object is an indirect object, then it's still
  378. * shared between pages.
  379. */
  380. if ($attributes[$property] instanceof Zend_Pdf_Element_Object) {
  381. $child->$property = $attributes[$property];
  382. } else {
  383. $child->$property = $this->_objFactory->newObject($attributes[$property]);
  384. }
  385. }
  386. }
  387. $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory);
  388. }
  389. }
  390. }
  391. /**
  392. * Orginize pages to tha pages tree structure.
  393. *
  394. * @todo atomatically attach page to the document, if it's not done yet.
  395. * @todo check, that page is attached to the current document
  396. *
  397. * @todo Dump pages as a balanced tree instead of a plain set.
  398. */
  399. protected function _dumpPages()
  400. {
  401. $root = $this->_trailer->Root;
  402. $pagesContainer = $root->Pages;
  403. $pagesContainer->touch();
  404. $pagesContainer->Kids->items->clear();
  405. $pageReferences = array();
  406. foreach ($this->pages as $page ) {
  407. $page->render($this->_objFactory);
  408. $pageDictionary = $page->getPageDictionary();
  409. $pageDictionary->touch();
  410. $pageDictionary->Parent = $pagesContainer;
  411. $pagesContainer->Kids->items[] = $pageDictionary;
  412. // Collect page references
  413. $pageReferences[$pageDictionary->toString($this->_objFactory)] = 1;
  414. }
  415. // Collect named destinations (exclude not referenced pages)
  416. $namedDestinations = array();
  417. // Walk through destinations structure
  418. if ($root->Version !== null && version_compare($root->Version->value, $this->_pdfHeaderVersion, '>')) {
  419. $versionIs_1_2_plus = version_compare($root->Version->value, '1.1', '>');
  420. } else {
  421. $versionIs_1_2_plus = version_compare($this->_pdfHeaderVersion, '1.1', '>');
  422. }
  423. if ($versionIs_1_2_plus) {
  424. // PDF version is 1.2+
  425. // Look for Destinations structure at Name dictionary
  426. } else {
  427. // PDF version is 1.1 (or earlier)
  428. // Look for Destinations sructure at Dest entry of document catalog
  429. if ($root->Dests !== null) {
  430. if ($root->Dests->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
  431. require_once 'Zend/Pdf/Exception.php';
  432. throw new Zend_Pdf_Exception( 'Document catalog Dests entry must be a dictionary.' );
  433. }
  434. foreach ($root->Dests->getKeys() as $destKey) {
  435. $destination = $root->Dests->$destKey;
  436. if ($destination->getType() == Zend_Pdf_Element::TYPE_ARRAY) {
  437. // Destination is an array, just treat it as an explicit destination array
  438. $destinationArray = $destination;
  439. } else if ($destination->getType() == Zend_Pdf_Element::TYPE_DICTIONARY) {
  440. // Destination is a dictionary, treat it as (remote) go-to action
  441. // Get 'D' entry (an explicit destination array)
  442. if ($destination->D === null || $destination->D->getType() != Zend_Pdf_Element::TYPE_ARRAY) {
  443. require_once 'Zend/Pdf/Exception.php';
  444. throw new Zend_Pdf_Exception( 'Named destination dictionary must have \'D\' array entry.' );
  445. }
  446. $destinationArray = $destination->D;
  447. if ($destination->F !== null) {
  448. // It's a remote Go-To action
  449. // So we don't check page for existance, only check that it's an inderect object reference
  450. rewind($destinationArray->items);
  451. $pageDictionaryObject = current($destinationArray->items);
  452. if ($pageDictionaryObject === false || !$pageDictionaryObject instanceof Zend_Pdf_Element_Object) {
  453. require_once 'Zend/Pdf/Exception.php';
  454. throw new Zend_Pdf_Exception( 'First element of explicit destination array must be an indirect object.' );
  455. }
  456. $namedDestinations[$destKey] = 1;
  457. continue;
  458. } else {
  459. require_once 'Zend/Pdf/Exception.php';
  460. throw new Zend_Pdf_Exception( 'PDF 1.1 named destination entry must be an array or dictionary with \'D\' entry.' );
  461. }
  462. } else {
  463. require_once 'Zend/Pdf/Exception.php';
  464. throw new Zend_Pdf_Exception( 'PDF 1.1 named destination entry must be an array or dictionary.' );
  465. }
  466. rewind($destinationArray->items);
  467. $pageDictionaryObject = current($destinationArray->items);
  468. if ($pageDictionaryObject === false || !$pageDictionaryObject instanceof Zend_Pdf_Element_Object) {
  469. require_once 'Zend/Pdf/Exception.php';
  470. throw new Zend_Pdf_Exception( 'First element of explicit destination array must be an indirect object.' );
  471. }
  472. if (isset($pageReferences[$pageDictionaryObject->toString($this->_objFactory)])) {
  473. // Collect named destination if referenced page is listed within current pages set.
  474. $namedDestinations[$destKey] = 1;
  475. } else {
  476. // Remove named destination from Dest dictionary
  477. $root->Dests->touch();
  478. }
  479. }
  480. }
  481. }
  482. if ($root->OpenAction !== null) {
  483. // if ()
  484. }
  485. $pagesContainer->Count->touch();
  486. $pagesContainer->Count->value = count($this->pages);
  487. }
  488. /**
  489. * Create page object, attached to the PDF document.
  490. * Method signatures:
  491. *
  492. * 1. Create new page with a specified pagesize.
  493. * If $factory is null then it will be created and page must be attached to the document to be
  494. * included into output.
  495. * ---------------------------------------------------------
  496. * new Zend_Pdf_Page(string $pagesize);
  497. * ---------------------------------------------------------
  498. *
  499. * 2. Create new page with a specified pagesize (in default user space units).
  500. * If $factory is null then it will be created and page must be attached to the document to be
  501. * included into output.
  502. * ---------------------------------------------------------
  503. * new Zend_Pdf_Page(numeric $width, numeric $height);
  504. * ---------------------------------------------------------
  505. *
  506. * @param mixed $param1
  507. * @param mixed $param2
  508. * @return Zend_Pdf_Page
  509. */
  510. public function newPage($param1, $param2 = null)
  511. {
  512. if ($param2 === null) {
  513. return new Zend_Pdf_Page($param1, $this->_objFactory);
  514. } else {
  515. return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);
  516. }
  517. }
  518. /**
  519. * Return the document-level Metadata
  520. * or null Metadata stream is not presented
  521. *
  522. * @return string
  523. */
  524. public function getMetadata()
  525. {
  526. if ($this->_trailer->Root->Metadata !== null) {
  527. return $this->_trailer->Root->Metadata->value;
  528. } else {
  529. return null;
  530. }
  531. }
  532. /**
  533. * Sets the document-level Metadata (mast be valid XMP document)
  534. *
  535. * @param string $metadata
  536. */
  537. public function setMetadata($metadata)
  538. {
  539. $metadataObject = $this->_objFactory->newStreamObject($metadata);
  540. $metadataObject->dictionary->Type = new Zend_Pdf_Element_Name('Metadata');
  541. $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');
  542. $this->_trailer->Root->Metadata = $metadataObject;
  543. $this->_trailer->Root->touch();
  544. }
  545. /**
  546. * Return the document-level JavaScript
  547. * or null if there is no JavaScript for this document
  548. *
  549. * @return string
  550. */
  551. public function getJavaScript()
  552. {
  553. return $this->_javaScript;
  554. }
  555. /**
  556. * Return an associative array containing all the named actions in the PDF.
  557. * Named actions (it's always "GoTo" actions) can be used to reference from outside
  558. * the PDF, ex: 'http://www.something.com/mydocument.pdf#MyAction'
  559. *
  560. * @return array
  561. */
  562. public function getNamedActions()
  563. {
  564. return $this->_namedActions;
  565. }
  566. /**
  567. * Extract fonts attached to the document
  568. *
  569. * returns array of Zend_Pdf_Resource_Font_Extracted objects
  570. *
  571. * @return array
  572. */
  573. public function extractFonts()
  574. {
  575. $fontResourcesUnique = array();
  576. foreach ($this->pages as $page) {
  577. $pageResources = $page->extractResources();
  578. if ($pageResources->Font === null) {
  579. // Page doesn't contain have any font reference
  580. continue;
  581. }
  582. $fontResources = $pageResources->Font;
  583. foreach ($fontResources->getKeys() as $fontResourceName) {
  584. $fontDictionary = $fontResources->$fontResourceName;
  585. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  586. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  587. // Font dictionary has to be an indirect object or object reference
  588. continue;
  589. }
  590. $fontResourcesUnique[$fontDictionary->toString($this->_objFactory)] = $fontDictionary;
  591. }
  592. }
  593. $fonts = array();
  594. require_once 'Zend/Pdf/Exception.php';
  595. foreach ($fontResourcesUnique as $resourceReference => $fontDictionary) {
  596. try {
  597. // Try to extract font
  598. $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  599. $fonts[$resourceReference] = $extractedFont;
  600. } catch (Zend_Pdf_Exception $e) {
  601. if ($e->getMessage() != 'Unsupported font type.') {
  602. throw $e;
  603. }
  604. }
  605. }
  606. return $fonts;
  607. }
  608. /**
  609. * Extract font attached to the page by specific font name
  610. *
  611. * $fontName should be specified in UTF-8 encoding
  612. *
  613. * @return Zend_Pdf_Resource_Font_Extracted|null
  614. */
  615. public function extractFont($fontName)
  616. {
  617. $fontResourcesUnique = array();
  618. require_once 'Zend/Pdf/Exception.php';
  619. foreach ($this->pages as $page) {
  620. $pageResources = $page->extractResources();
  621. if ($pageResources->Font === null) {
  622. // Page doesn't contain have any font reference
  623. continue;
  624. }
  625. $fontResources = $pageResources->Font;
  626. foreach ($fontResources->getKeys() as $fontResourceName) {
  627. $fontDictionary = $fontResources->$fontResourceName;
  628. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  629. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  630. // Font dictionary has to be an indirect object or object reference
  631. continue;
  632. }
  633. $resourceReference = $fontDictionary->toString($this->_objFactory);
  634. if (isset($fontResourcesUnique[$resourceReference])) {
  635. continue;
  636. } else {
  637. // Mark resource as processed
  638. $fontResourcesUnique[$resourceReference] = 1;
  639. }
  640. if ($fontDictionary->BaseFont->value != $fontName) {
  641. continue;
  642. }
  643. try {
  644. // Try to extract font
  645. return new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  646. } catch (Zend_Pdf_Exception $e) {
  647. if ($e->getMessage() != 'Unsupported font type.') {
  648. throw $e;
  649. }
  650. // Continue searhing
  651. }
  652. }
  653. }
  654. return null;
  655. }
  656. /**
  657. * Render the completed PDF to a string.
  658. * If $newSegmentOnly is true, then only appended part of PDF is returned.
  659. *
  660. * @param boolean $newSegmentOnly
  661. * @param resource $outputStream
  662. * @return string
  663. * @throws Zend_Pdf_Exception
  664. */
  665. public function render($newSegmentOnly = false, $outputStream = null)
  666. {
  667. // Save document properties if necessary
  668. if ($this->properties != $this->_originalProperties) {
  669. $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  670. foreach ($this->properties as $key => $value) {
  671. switch ($key) {
  672. case 'Trapped':
  673. switch ($value) {
  674. case true:
  675. $docInfo->$key = new Zend_Pdf_Element_Name('True');
  676. break;
  677. case false:
  678. $docInfo->$key = new Zend_Pdf_Element_Name('False');
  679. break;
  680. case null:
  681. $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');
  682. break;
  683. default:
  684. require_once 'Zend/Pdf/Exception.php';
  685. throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');
  686. break;
  687. }
  688. case 'CreationDate':
  689. // break intentionally omitted
  690. case 'ModDate':
  691. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  692. break;
  693. case 'Title':
  694. // break intentionally omitted
  695. case 'Author':
  696. // break intentionally omitted
  697. case 'Subject':
  698. // break intentionally omitted
  699. case 'Keywords':
  700. // break intentionally omitted
  701. case 'Creator':
  702. // break intentionally omitted
  703. case 'Producer':
  704. if (extension_loaded('mbstring') === true) {
  705. $detected = mb_detect_encoding($value);
  706. if ($detected !== 'ASCII') {
  707. $value = chr(254) . chr(255) . mb_convert_encoding($value, 'UTF-16', $detected);
  708. }
  709. }
  710. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  711. break;
  712. default:
  713. // Set property using PDF type based on PHP type
  714. $docInfo->$key = Zend_Pdf_Element::phpToPdf($value);
  715. break;
  716. }
  717. }
  718. $this->_trailer->Info = $docInfo;
  719. }
  720. $this->_dumpPages();
  721. // Check, that PDF file was modified
  722. // File is always modified by _dumpPages() now, but future implementations may eliminate this.
  723. if (!$this->_objFactory->isModified()) {
  724. if ($newSegmentOnly) {
  725. // Do nothing, return
  726. return '';
  727. }
  728. if ($outputStream === null) {
  729. return $this->_trailer->getPDFString();
  730. } else {
  731. $pdfData = $this->_trailer->getPDFString();
  732. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  733. $pdfData = substr($pdfData, $byteCount);
  734. }
  735. return '';
  736. }
  737. }
  738. // offset (from a start of PDF file) of new PDF file segment
  739. $offset = $this->_trailer->getPDFLength();
  740. // Last Object number in a list of free objects
  741. $lastFreeObject = $this->_trailer->getLastFreeObject();
  742. // Array of cross-reference table subsections
  743. $xrefTable = array();
  744. // Object numbers of first objects in each subsection
  745. $xrefSectionStartNums = array();
  746. // Last cross-reference table subsection
  747. $xrefSection = array();
  748. // Dummy initialization of the first element (specail case - header of linked list of free objects).
  749. $xrefSection[] = 0;
  750. $xrefSectionStartNums[] = 0;
  751. // Object number of last processed PDF object.
  752. // Used to manage cross-reference subsections.
  753. // Initialized by zero (specail case - header of linked list of free objects).
  754. $lastObjNum = 0;
  755. if ($outputStream !== null) {
  756. if (!$newSegmentOnly) {
  757. $pdfData = $this->_trailer->getPDFString();
  758. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  759. $pdfData = substr($pdfData, $byteCount);
  760. }
  761. }
  762. } else {
  763. $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());
  764. }
  765. // Iterate objects to create new reference table
  766. foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {
  767. $objNum = $updateInfo->getObjNum();
  768. if ($objNum - $lastObjNum != 1) {
  769. // Save cross-reference table subsection and start new one
  770. $xrefTable[] = $xrefSection;
  771. $xrefSection = array();
  772. $xrefSectionStartNums[] = $objNum;
  773. }
  774. if ($updateInfo->isFree()) {
  775. // Free object cross-reference table entry
  776. $xrefSection[] = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());
  777. $lastFreeObject = $objNum;
  778. } else {
  779. // In-use object cross-reference table entry
  780. $xrefSection[] = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());
  781. $pdfBlock = $updateInfo->getObjectDump();
  782. $offset += strlen($pdfBlock);
  783. if ($outputStream === null) {
  784. $pdfSegmentBlocks[] = $pdfBlock;
  785. } else {
  786. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  787. $pdfBlock = substr($pdfBlock, $byteCount);
  788. }
  789. }
  790. }
  791. $lastObjNum = $objNum;
  792. }
  793. // Save last cross-reference table subsection
  794. $xrefTable[] = $xrefSection;
  795. // Modify first entry (specail case - header of linked list of free objects).
  796. $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);
  797. $xrefTableStr = "xref\n";
  798. foreach ($xrefTable as $sectId => $xrefSection) {
  799. $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));
  800. foreach ($xrefSection as $xrefTableEntry) {
  801. $xrefTableStr .= $xrefTableEntry;
  802. }
  803. }
  804. $this->_trailer->Size->value = $this->_objFactory->getObjectCount();
  805. $pdfBlock = $xrefTableStr
  806. . $this->_trailer->toString()
  807. . "startxref\n" . $offset . "\n"
  808. . "%%EOF\n";
  809. if ($outputStream === null) {
  810. $pdfSegmentBlocks[] = $pdfBlock;
  811. return implode('', $pdfSegmentBlocks);
  812. } else {
  813. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  814. $pdfBlock = substr($pdfBlock, $byteCount);
  815. }
  816. return '';
  817. }
  818. }
  819. /**
  820. * Set the document-level JavaScript
  821. *
  822. * @param string $javascript
  823. */
  824. public function setJavaScript($javascript)
  825. {
  826. $this->_javaScript = $javascript;
  827. }
  828. /**
  829. * Convert date to PDF format (it's close to ASN.1 (Abstract Syntax Notation
  830. * One) defined in ISO/IEC 8824).
  831. *
  832. * @todo This really isn't the best location for this method. It should
  833. * probably actually exist as Zend_Pdf_Element_Date or something like that.
  834. *
  835. * @todo Address the following E_STRICT issue:
  836. * PHP Strict Standards: date(): It is not safe to rely on the system's
  837. * timezone settings. Please use the date.timezone setting, the TZ
  838. * environment variable or the date_default_timezone_set() function. In
  839. * case you used any of those methods and you are still getting this
  840. * warning, you most likely misspelled the timezone identifier.
  841. *
  842. * @param integer $timestamp (optional) If omitted, uses the current time.
  843. * @return string
  844. */
  845. public static function pdfDate($timestamp = null)
  846. {
  847. if ($timestamp === null) {
  848. $date = date('\D\:YmdHisO');
  849. } else {
  850. $date = date('\D\:YmdHisO', $timestamp);
  851. }
  852. return substr_replace($date, '\'', -2, 0) . '\'';
  853. }
  854. }