Pdf.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /** Zend_Pdf_Page */
  22. require_once 'Zend/Pdf/Page.php';
  23. /** Zend_Pdf_Cmap */
  24. require_once 'Zend/Pdf/Cmap.php';
  25. /** Zend_Pdf_Font */
  26. require_once 'Zend/Pdf/Font.php';
  27. /** Zend_Pdf_Style */
  28. require_once 'Zend/Pdf/Style.php';
  29. /** Zend_Pdf_Parser */
  30. require_once 'Zend/Pdf/Parser.php';
  31. /** Zend_Pdf_Trailer */
  32. require_once 'Zend/Pdf/Trailer.php';
  33. /** Zend_Pdf_Trailer_Generator */
  34. require_once 'Zend/Pdf/Trailer/Generator.php';
  35. /** Zend_Pdf_Color */
  36. require_once 'Zend/Pdf/Color.php';
  37. /** Zend_Pdf_Color_GrayScale */
  38. require_once 'Zend/Pdf/Color/GrayScale.php';
  39. /** Zend_Pdf_Color_Rgb */
  40. require_once 'Zend/Pdf/Color/Rgb.php';
  41. /** Zend_Pdf_Color_Cmyk */
  42. require_once 'Zend/Pdf/Color/Cmyk.php';
  43. /** Zend_Pdf_Color_Html */
  44. require_once 'Zend/Pdf/Color/Html.php';
  45. /** Zend_Pdf_Image */
  46. require_once 'Zend/Pdf/Resource/Image.php';
  47. /** Zend_Pdf_Image */
  48. require_once 'Zend/Pdf/Image.php';
  49. /** Zend_Pdf_Image_Jpeg */
  50. require_once 'Zend/Pdf/Resource/Image/Jpeg.php';
  51. /** Zend_Pdf_Image_Tiff */
  52. require_once 'Zend/Pdf/Resource/Image/Tiff.php';
  53. /** Zend_Pdf_Image_Png */
  54. require_once 'Zend/Pdf/Resource/Image/Png.php';
  55. /** Zend_Memory */
  56. require_once 'Zend/Memory.php';
  57. /** Zend_Pdf_Action */
  58. require_once 'Zend/Pdf/Action.php';
  59. /** Zend_Pdf_Destination */
  60. require_once 'Zend/Pdf/Destination.php';
  61. /** Zend_Pdf_Destination_Explicit */
  62. require_once 'Zend/Pdf/Destination/Explicit.php';
  63. /** Zend_Pdf_Destination_Named */
  64. require_once 'Zend/Pdf/Destination/Named.php';
  65. /** Zend_Pdf_Outline_Created */
  66. require_once 'Zend/Pdf/Outline/Created.php';
  67. /** Zend_Pdf_Outline_Loaded */
  68. require_once 'Zend/Pdf/Outline/Loaded.php';
  69. /** Zend_Pdf_RecursivelyIteratableObjectsContainer */
  70. require_once 'Zend/Pdf/RecursivelyIteratableObjectsContainer.php';
  71. /** Zend_Pdf_NameTree */
  72. require_once 'Zend/Pdf/NameTree.php';
  73. /** Zend_Pdf_Destination */
  74. require_once 'Zend/Pdf/Exception.php';
  75. /**
  76. * General entity which describes PDF document.
  77. * It implements document abstraction with a document level operations.
  78. *
  79. * Class is used to create new PDF document or load existing document.
  80. * See details in a class constructor description
  81. *
  82. * Class agregates document level properties and entities (pages, bookmarks,
  83. * document level actions, attachments, form object, etc)
  84. *
  85. * @category Zend
  86. * @package Zend_Pdf
  87. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  88. * @license http://framework.zend.com/license/new-bsd New BSD License
  89. */
  90. class Zend_Pdf
  91. {
  92. /**** Class Constants ****/
  93. /**
  94. * Version number of generated PDF documents.
  95. */
  96. const PDF_VERSION = '1.4';
  97. /**
  98. * PDF file header.
  99. */
  100. const PDF_HEADER = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
  101. /**
  102. * Pages collection
  103. *
  104. * @todo implement it as a class, which supports ArrayAccess and Iterator interfaces,
  105. * to provide incremental parsing and pages tree updating.
  106. * That will give good performance and memory (PDF size) benefits.
  107. *
  108. * @var array - array of Zend_Pdf_Page object
  109. */
  110. public $pages = array();
  111. /**
  112. * Document properties
  113. *
  114. * It's an associative array with PDF meta information, values may
  115. * be string, boolean or float.
  116. * Returned array could be used directly to access, add, modify or remove
  117. * document properties.
  118. *
  119. * Standard document properties: Title (must be set for PDF/X documents), Author,
  120. * Subject, Keywords (comma separated list), Creator (the name of the application,
  121. * that created document, if it was converted from other format), Trapped (must be
  122. * true, false or null, can not be null for PDF/X documents)
  123. *
  124. * @var array
  125. */
  126. public $properties = array();
  127. /**
  128. * Original properties set.
  129. *
  130. * Used for tracking properties changes
  131. *
  132. * @var array
  133. */
  134. protected $_originalProperties = array();
  135. /**
  136. * Document level javascript
  137. *
  138. * @var string
  139. */
  140. protected $_javaScript = null;
  141. /**
  142. * Document named destinations or "GoTo..." actions, used to refer
  143. * document parts from outside PDF
  144. *
  145. * @var array - array of Zend_Pdf_Target objects
  146. */
  147. protected $_namedTargets = array();
  148. /**
  149. * Document outlines
  150. *
  151. * @var array - array of Zend_Pdf_Outline objects
  152. */
  153. public $outlines = array();
  154. /**
  155. * Original document outlines list
  156. * Used to track outlines update
  157. *
  158. * @var array - array of Zend_Pdf_Outline objects
  159. */
  160. protected $_originalOutlines = array();
  161. /**
  162. * Original document outlines open elements count
  163. * Used to track outlines update
  164. *
  165. * @var integer
  166. */
  167. protected $_originalOpenOutlinesCount = 0;
  168. /**
  169. * Pdf trailer (last or just created)
  170. *
  171. * @var Zend_Pdf_Trailer
  172. */
  173. protected $_trailer = null;
  174. /**
  175. * PDF objects factory.
  176. *
  177. * @var Zend_Pdf_ElementFactory_Interface
  178. */
  179. protected $_objFactory = null;
  180. /**
  181. * Memory manager for stream objects
  182. *
  183. * @var Zend_Memory_Manager|null
  184. */
  185. protected static $_memoryManager = null;
  186. /**
  187. * Pdf file parser.
  188. * It's not used, but has to be destroyed only with Zend_Pdf object
  189. *
  190. * @var Zend_Pdf_Parser
  191. */
  192. protected $_parser;
  193. /**
  194. * List of inheritable attributesfor pages tree
  195. *
  196. * @var array
  197. */
  198. protected static $_inheritableAttributes = array('Resources', 'MediaBox', 'CropBox', 'Rotate');
  199. /**
  200. * Request used memory manager
  201. *
  202. * @return Zend_Memory_Manager
  203. */
  204. static public function getMemoryManager()
  205. {
  206. if (self::$_memoryManager === null) {
  207. self::$_memoryManager = Zend_Memory::factory('none');
  208. }
  209. return self::$_memoryManager;
  210. }
  211. /**
  212. * Set user defined memory manager
  213. *
  214. * @param Zend_Memory_Manager $memoryManager
  215. */
  216. static public function setMemoryManager(Zend_Memory_Manager $memoryManager)
  217. {
  218. self::$_memoryManager = $memoryManager;
  219. }
  220. /**
  221. * Create new PDF document from a $source string
  222. *
  223. * @param string $source
  224. * @param integer $revision
  225. * @return Zend_Pdf
  226. */
  227. public static function parse(&$source = null, $revision = null)
  228. {
  229. return new Zend_Pdf($source, $revision);
  230. }
  231. /**
  232. * Load PDF document from a file
  233. *
  234. * @param string $source
  235. * @param integer $revision
  236. * @return Zend_Pdf
  237. */
  238. public static function load($source = null, $revision = null)
  239. {
  240. return new Zend_Pdf($source, $revision, true);
  241. }
  242. /**
  243. * Render PDF document and save it.
  244. *
  245. * If $updateOnly is true, then it only appends new section to the end of file.
  246. *
  247. * @param string $filename
  248. * @param boolean $updateOnly
  249. * @throws Zend_Pdf_Exception
  250. */
  251. public function save($filename, $updateOnly = false)
  252. {
  253. if (($file = @fopen($filename, $updateOnly ? 'ab':'wb')) === false ) {
  254. require_once 'Zend/Pdf/Exception.php';
  255. throw new Zend_Pdf_Exception( "Can not open '$filename' file for writing." );
  256. }
  257. $this->render($updateOnly, $file);
  258. fclose($file);
  259. }
  260. /**
  261. * Creates or loads PDF document.
  262. *
  263. * If $source is null, then it creates a new document.
  264. *
  265. * If $source is a string and $load is false, then it loads document
  266. * from a binary string.
  267. *
  268. * If $source is a string and $load is true, then it loads document
  269. * from a file.
  270. * $revision used to roll back document to specified version
  271. * (0 - currtent version, 1 - previous version, 2 - ...)
  272. *
  273. * @param string $source - PDF file to load
  274. * @param integer $revision
  275. * @throws Zend_Pdf_Exception
  276. * @return Zend_Pdf
  277. */
  278. public function __construct($source = null, $revision = null, $load = false)
  279. {
  280. $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1);
  281. if ($source !== null) {
  282. $this->_parser = new Zend_Pdf_Parser($source, $this->_objFactory, $load);
  283. $this->_pdfHeaderVersion = $this->_parser->getPDFVersion();
  284. $this->_trailer = $this->_parser->getTrailer();
  285. if ($this->_trailer->Encrypt !== null) {
  286. require_once 'Zend/Pdf/Exception.php';
  287. throw new Zend_Pdf_Exception('Encrypted document modification is not supported');
  288. }
  289. if ($revision !== null) {
  290. $this->rollback($revision);
  291. } else {
  292. $this->_loadPages($this->_trailer->Root->Pages);
  293. }
  294. $this->_loadNamedDestinations($this->_trailer->Root, $this->_parser->getPDFVersion());
  295. $this->_loadOutlines($this->_trailer->Root);
  296. if ($this->_trailer->Info !== null) {
  297. $this->properties = $this->_trailer->Info->toPhp();
  298. if (isset($this->properties['Trapped'])) {
  299. switch ($this->properties['Trapped']) {
  300. case 'True':
  301. $this->properties['Trapped'] = true;
  302. break;
  303. case 'False':
  304. $this->properties['Trapped'] = false;
  305. break;
  306. case 'Unknown':
  307. $this->properties['Trapped'] = null;
  308. break;
  309. default:
  310. // Wrong property value
  311. // Do nothing
  312. break;
  313. }
  314. }
  315. $this->_originalProperties = $this->properties;
  316. }
  317. } else {
  318. $this->_pdfHeaderVersion = Zend_Pdf::PDF_VERSION;
  319. $trailerDictionary = new Zend_Pdf_Element_Dictionary();
  320. /**
  321. * Document id
  322. */
  323. $docId = md5(uniqid(rand(), true)); // 32 byte (128 bit) identifier
  324. $docIdLow = substr($docId, 0, 16); // first 16 bytes
  325. $docIdHigh = substr($docId, 16, 16); // second 16 bytes
  326. $trailerDictionary->ID = new Zend_Pdf_Element_Array();
  327. $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdLow);
  328. $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdHigh);
  329. $trailerDictionary->Size = new Zend_Pdf_Element_Numeric(0);
  330. $this->_trailer = new Zend_Pdf_Trailer_Generator($trailerDictionary);
  331. /**
  332. * Document catalog indirect object.
  333. */
  334. $docCatalog = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  335. $docCatalog->Type = new Zend_Pdf_Element_Name('Catalog');
  336. $docCatalog->Version = new Zend_Pdf_Element_Name(Zend_Pdf::PDF_VERSION);
  337. $this->_trailer->Root = $docCatalog;
  338. /**
  339. * Pages container
  340. */
  341. $docPages = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  342. $docPages->Type = new Zend_Pdf_Element_Name('Pages');
  343. $docPages->Kids = new Zend_Pdf_Element_Array();
  344. $docPages->Count = new Zend_Pdf_Element_Numeric(0);
  345. $docCatalog->Pages = $docPages;
  346. }
  347. }
  348. /**
  349. * Retrive number of revisions.
  350. *
  351. * @return integer
  352. */
  353. public function revisions()
  354. {
  355. $revisions = 1;
  356. $currentTrailer = $this->_trailer;
  357. while ($currentTrailer->getPrev() !== null && $currentTrailer->getPrev()->Root !== null ) {
  358. $revisions++;
  359. $currentTrailer = $currentTrailer->getPrev();
  360. }
  361. return $revisions++;
  362. }
  363. /**
  364. * Rollback document $steps number of revisions.
  365. * This method must be invoked before any changes, applied to the document.
  366. * Otherwise behavior is undefined.
  367. *
  368. * @param integer $steps
  369. */
  370. public function rollback($steps)
  371. {
  372. for ($count = 0; $count < $steps; $count++) {
  373. if ($this->_trailer->getPrev() !== null && $this->_trailer->getPrev()->Root !== null) {
  374. $this->_trailer = $this->_trailer->getPrev();
  375. } else {
  376. break;
  377. }
  378. }
  379. $this->_objFactory->setObjectCount($this->_trailer->Size->value);
  380. // Mark content as modified to force new trailer generation at render time
  381. $this->_trailer->Root->touch();
  382. $this->pages = array();
  383. $this->_loadPages($this->_trailer->Root->Pages);
  384. }
  385. /**
  386. * Load pages recursively
  387. *
  388. * @param Zend_Pdf_Element_Reference $pages
  389. * @param array|null $attributes
  390. */
  391. protected function _loadPages(Zend_Pdf_Element_Reference $pages, $attributes = array())
  392. {
  393. if ($pages->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
  394. require_once 'Zend/Pdf/Exception.php';
  395. throw new Zend_Pdf_Exception('Wrong argument');
  396. }
  397. foreach ($pages->getKeys() as $property) {
  398. if (in_array($property, self::$_inheritableAttributes)) {
  399. $attributes[$property] = $pages->$property;
  400. $pages->$property = null;
  401. }
  402. }
  403. foreach ($pages->Kids->items as $child) {
  404. if ($child->Type->value == 'Pages') {
  405. $this->_loadPages($child, $attributes);
  406. } else if ($child->Type->value == 'Page') {
  407. foreach (self::$_inheritableAttributes as $property) {
  408. if ($child->$property === null && array_key_exists($property, $attributes)) {
  409. /**
  410. * Important note.
  411. * If any attribute or dependant object is an indirect object, then it's still
  412. * shared between pages.
  413. */
  414. if ($attributes[$property] instanceof Zend_Pdf_Element_Object ||
  415. $attributes[$property] instanceof Zend_Pdf_Element_Reference) {
  416. $child->$property = $attributes[$property];
  417. } else {
  418. $child->$property = $this->_objFactory->newObject($attributes[$property]);
  419. }
  420. }
  421. }
  422. $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory);
  423. }
  424. }
  425. }
  426. /**
  427. * Load named destinations recursively
  428. *
  429. * @param Zend_Pdf_Element_Reference $root Document catalog entry
  430. * @param string $pdfHeaderVersion
  431. * @throws Zend_Pdf_Exception
  432. */
  433. protected function _loadNamedDestinations(Zend_Pdf_Element_Reference $root, $pdfHeaderVersion)
  434. {
  435. if ($root->Version !== null && version_compare($root->Version->value, $pdfHeaderVersion, '>')) {
  436. $versionIs_1_2_plus = version_compare($root->Version->value, '1.1', '>');
  437. } else {
  438. $versionIs_1_2_plus = version_compare($pdfHeaderVersion, '1.1', '>');
  439. }
  440. if ($versionIs_1_2_plus) {
  441. // PDF version is 1.2+
  442. // Look for Destinations structure at Name dictionary
  443. if ($root->Names !== null && $root->Names->Dests !== null) {
  444. foreach (new Zend_Pdf_NameTree($root->Names->Dests) as $name => $destination) {
  445. $this->_namedTargets[$name] = Zend_Pdf_Target::load($destination);
  446. }
  447. }
  448. } else {
  449. // PDF version is 1.1 (or earlier)
  450. // Look for Destinations sructure at Dest entry of document catalog
  451. if ($root->Dests !== null) {
  452. if ($root->Dests->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
  453. require_once 'Zend/Pdf/Exception.php';
  454. throw new Zend_Pdf_Exception('Document catalog Dests entry must be a dictionary.');
  455. }
  456. foreach ($root->Dests->getKeys() as $destKey) {
  457. $this->_namedTargets[$destKey] = Zend_Pdf_Target::load($root->Dests->$destKey);
  458. }
  459. }
  460. }
  461. }
  462. /**
  463. * Load outlines recursively
  464. *
  465. * @param Zend_Pdf_Element_Reference $root Document catalog entry
  466. */
  467. protected function _loadOutlines(Zend_Pdf_Element_Reference $root)
  468. {
  469. if ($root->Outlines === null) {
  470. return;
  471. }
  472. if ($root->Outlines->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
  473. require_once 'Zend/Pdf/Exception.php';
  474. throw new Zend_Pdf_Exception('Document catalog Outlines entry must be a dictionary.');
  475. }
  476. if ($root->Outlines->Type !== null && $root->Outlines->Type->value != 'Outlines') {
  477. require_once 'Zend/Pdf/Exception.php';
  478. throw new Zend_Pdf_Exception('Outlines Type entry must be an \'Outlines\' string.');
  479. }
  480. if ($root->Outlines->First === null) {
  481. return;
  482. }
  483. $outlineDictionary = $root->Outlines->First;
  484. $processedDictionaries = new SplObjectStorage();
  485. while ($outlineDictionary !== null && !$processedDictionaries->contains($outlineDictionary)) {
  486. $processedDictionaries->attach($outlineDictionary);
  487. $this->outlines[] = new Zend_Pdf_Outline_Loaded($outlineDictionary);
  488. $outlineDictionary = $outlineDictionary->Next;
  489. }
  490. $this->_originalOutlines = $this->outlines;
  491. if ($root->Outlines->Count !== null) {
  492. $this->_originalOpenOutlinesCount = $root->Outlines->Count->value;
  493. }
  494. }
  495. /**
  496. * Orginize pages to tha pages tree structure.
  497. *
  498. * @todo atomatically attach page to the document, if it's not done yet.
  499. * @todo check, that page is attached to the current document
  500. *
  501. * @todo Dump pages as a balanced tree instead of a plain set.
  502. */
  503. protected function _dumpPages()
  504. {
  505. $root = $this->_trailer->Root;
  506. $pagesContainer = $root->Pages;
  507. $pagesContainer->touch();
  508. $pagesContainer->Kids->items->clear();
  509. foreach ($this->pages as $page ) {
  510. $page->render($this->_objFactory);
  511. $pageDictionary = $page->getPageDictionary();
  512. $pageDictionary->touch();
  513. $pageDictionary->Parent = $pagesContainer;
  514. $pagesContainer->Kids->items[] = $pageDictionary;
  515. }
  516. $this->_refreshPagesHash();
  517. $pagesContainer->Count->touch();
  518. $pagesContainer->Count->value = count($this->pages);
  519. // Refresh named destinations list
  520. foreach ($this->_namedTargets as $name => $namedTarget) {
  521. if ($namedTarget instanceof Zend_Pdf_Destination_Explicit) {
  522. // Named target is an explicit destination
  523. if ($this->resolveDestination($namedTarget, false) === null) {
  524. unset($this->_namedTargets[$name]);
  525. }
  526. } else if ($namedTarget instanceof Zend_Pdf_Action) {
  527. // Named target is an action
  528. if ($this->_cleanUpAction($namedTarget, false) === null) {
  529. // Action is a GoTo action with an unresolved destination
  530. unset($this->_namedTargets[$name]);
  531. }
  532. } else {
  533. require_once 'Zend/Pdf/Exception.php';
  534. throw new Zend_Pdf_Exception('Wrong type of named targed (\'' . get_class($namedTarget) . '\').');
  535. }
  536. }
  537. // Refresh outlines
  538. $iterator = new RecursiveIteratorIterator(new Zend_Pdf_RecursivelyIteratableObjectsContainer($this->outlines), RecursiveIteratorIterator::SELF_FIRST);
  539. foreach ($iterator as $outline) {
  540. $target = $outline->getTarget();
  541. if ($target !== null) {
  542. if ($target instanceof Zend_Pdf_Destination) {
  543. // Outline target is a destination
  544. if ($this->resolveDestination($target, false) === null) {
  545. $outline->setTarget(null);
  546. }
  547. } else if ($target instanceof Zend_Pdf_Action) {
  548. // Outline target is an action
  549. if ($this->_cleanUpAction($target, false) === null) {
  550. // Action is a GoTo action with an unresolved destination
  551. $outline->setTarget(null);
  552. }
  553. } else {
  554. require_once 'Zend/Pdf/Exception.php';
  555. throw new Zend_Pdf_Exception('Wrong outline target.');
  556. }
  557. }
  558. }
  559. $openAction = $this->getOpenAction();
  560. if ($openAction !== null) {
  561. if ($openAction instanceof Zend_Pdf_Action) {
  562. // OpenAction is an action
  563. if ($this->_cleanUpAction($openAction, false) === null) {
  564. // Action is a GoTo action with an unresolved destination
  565. $this->setOpenAction(null);
  566. }
  567. } else if ($openAction instanceof Zend_Pdf_Destination) {
  568. // OpenAction target is a destination
  569. if ($this->resolveDestination($openAction, false) === null) {
  570. $this->setOpenAction(null);
  571. }
  572. } else {
  573. require_once 'Zend/Pdf/Exception.php';
  574. throw new Zend_Pdf_Exception('OpenAction has to be either PDF Action or Destination.');
  575. }
  576. }
  577. }
  578. /**
  579. * Dump named destinations
  580. *
  581. * @todo Create a balanced tree instead of plain structure.
  582. */
  583. protected function _dumpNamedDestinations()
  584. {
  585. ksort($this->_namedTargets, SORT_STRING);
  586. $destArray = $this->_objFactory->newObject(new Zend_Pdf_Element_Array());
  587. $destArrayItems = &$destArray->items;
  588. foreach ($this->_namedTargets as $name => $destination) {
  589. $destArrayItems[] = new Zend_Pdf_Element_String($name);
  590. if ($destination instanceof Zend_Pdf_Target) {
  591. $destArrayItems[] = $destination->getResource();
  592. } else {
  593. require_once 'Zend/Pdf/Exception.php';
  594. throw new Zend_Pdf_Exception('PDF named destinations must be a Zend_Pdf_Target object.');
  595. }
  596. }
  597. $DestTree = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  598. $DestTree->Names = $destArray;
  599. $root = $this->_trailer->Root;
  600. if ($root->Names === null) {
  601. $root->touch();
  602. $root->Names = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  603. } else {
  604. $root->Names->touch();
  605. }
  606. $root->Names->Dests = $DestTree;
  607. }
  608. /**
  609. * Dump outlines recursively
  610. */
  611. protected function _dumpOutlines()
  612. {
  613. $root = $this->_trailer->Root;
  614. if ($root->Outlines === null) {
  615. if (count($this->outlines) == 0) {
  616. return;
  617. } else {
  618. $root->Outlines = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  619. $root->Outlines->Type = new Zend_Pdf_Element_Name('Outlines');
  620. $updateOutlinesNavigation = true;
  621. }
  622. } else {
  623. $updateOutlinesNavigation = false;
  624. if (count($this->_originalOutlines) != count($this->outlines)) {
  625. // If original and current outlines arrays have different size then outlines list was updated
  626. $updateOutlinesNavigation = true;
  627. } else if ( !(array_keys($this->_originalOutlines) === array_keys($this->outlines)) ) {
  628. // If original and current outlines arrays have different keys (with a glance to an order) then outlines list was updated
  629. $updateOutlinesNavigation = true;
  630. } else {
  631. foreach ($this->outlines as $key => $outline) {
  632. if ($this->_originalOutlines[$key] !== $outline) {
  633. $updateOutlinesNavigation = true;
  634. }
  635. }
  636. }
  637. }
  638. $lastOutline = null;
  639. $openOutlinesCount = 0;
  640. if ($updateOutlinesNavigation) {
  641. $root->Outlines->touch();
  642. $root->Outlines->First = null;
  643. foreach ($this->outlines as $outline) {
  644. if ($lastOutline === null) {
  645. // First pass. Update Outlines dictionary First entry using corresponding value
  646. $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines);
  647. $root->Outlines->First = $lastOutline;
  648. } else {
  649. // Update previous outline dictionary Next entry (Prev is updated within dumpOutline() method)
  650. $currentOutlineDictionary = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
  651. $lastOutline->Next = $currentOutlineDictionary;
  652. $lastOutline = $currentOutlineDictionary;
  653. }
  654. $openOutlinesCount += $outline->openOutlinesCount();
  655. }
  656. $root->Outlines->Last = $lastOutline;
  657. } else {
  658. foreach ($this->outlines as $outline) {
  659. $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
  660. $openOutlinesCount += $outline->openOutlinesCount();
  661. }
  662. }
  663. if ($openOutlinesCount != $this->_originalOpenOutlinesCount) {
  664. $root->Outlines->touch;
  665. $root->Outlines->Count = new Zend_Pdf_Element_Numeric($openOutlinesCount);
  666. }
  667. }
  668. /**
  669. * Create page object, attached to the PDF document.
  670. * Method signatures:
  671. *
  672. * 1. Create new page with a specified pagesize.
  673. * If $factory is null then it will be created and page must be attached to the document to be
  674. * included into output.
  675. * ---------------------------------------------------------
  676. * new Zend_Pdf_Page(string $pagesize);
  677. * ---------------------------------------------------------
  678. *
  679. * 2. Create new page with a specified pagesize (in default user space units).
  680. * If $factory is null then it will be created and page must be attached to the document to be
  681. * included into output.
  682. * ---------------------------------------------------------
  683. * new Zend_Pdf_Page(numeric $width, numeric $height);
  684. * ---------------------------------------------------------
  685. *
  686. * @param mixed $param1
  687. * @param mixed $param2
  688. * @return Zend_Pdf_Page
  689. */
  690. public function newPage($param1, $param2 = null)
  691. {
  692. if ($param2 === null) {
  693. return new Zend_Pdf_Page($param1, $this->_objFactory);
  694. } else {
  695. return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);
  696. }
  697. }
  698. /**
  699. * Return the document-level Metadata
  700. * or null Metadata stream is not presented
  701. *
  702. * @return string
  703. */
  704. public function getMetadata()
  705. {
  706. if ($this->_trailer->Root->Metadata !== null) {
  707. return $this->_trailer->Root->Metadata->value;
  708. } else {
  709. return null;
  710. }
  711. }
  712. /**
  713. * Sets the document-level Metadata (mast be valid XMP document)
  714. *
  715. * @param string $metadata
  716. */
  717. public function setMetadata($metadata)
  718. {
  719. $metadataObject = $this->_objFactory->newStreamObject($metadata);
  720. $metadataObject->dictionary->Type = new Zend_Pdf_Element_Name('Metadata');
  721. $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');
  722. $this->_trailer->Root->Metadata = $metadataObject;
  723. $this->_trailer->Root->touch();
  724. }
  725. /**
  726. * Return the document-level JavaScript
  727. * or null if there is no JavaScript for this document
  728. *
  729. * @return string
  730. */
  731. public function getJavaScript()
  732. {
  733. return $this->_javaScript;
  734. }
  735. /**
  736. * Get open Action
  737. * Returns Zend_Pdf_Destination or Zend_Pdf_Action (which is actually GoTo Action) object
  738. *
  739. * @return Zend_Pdf_Destination|Zend_Pdf_Action
  740. */
  741. public function getOpenAction()
  742. {
  743. if ($this->_trailer->Root->OpenAction !== null) {
  744. return Zend_Pdf_Target::load($this->_trailer->Root->OpenAction);
  745. } else {
  746. return null;
  747. }
  748. }
  749. /**
  750. * Set open Action which is actually Zend_Pdf_Destination or Zend_Pdf_Action object
  751. *
  752. * @param Zend_Pdf_Destination|Zend_Pdf_Action $openAction
  753. * @throws Zend_Pdf_Exception
  754. */
  755. public function setOpenAction($openAction)
  756. {
  757. $root = $this->_trailer->Root;
  758. $root->touch();
  759. if ($openAction === null) {
  760. $root->OpenAction = null;
  761. } else if ($openAction instanceof Zend_Pdf_Target) {
  762. $root->OpenAction = $openAction->getResource();
  763. $openAction->dumpAction($this->_objFactory);
  764. } else {
  765. require_once 'Zend/Pdf/Exception.php';
  766. throw new Zend_Pdf_Exception('Open action must be a Zend_Pdf_Target or null.');
  767. }
  768. }
  769. /**
  770. * Return an associative array containing all the named destinations (or GoTo actions) in the PDF.
  771. * Named targets can be used to reference from outside
  772. * the PDF, ex: 'http://www.something.com/mydocument.pdf#MyAction'
  773. *
  774. * @return array
  775. */
  776. public function getNamedDestinations()
  777. {
  778. return $this->_namedTargets;
  779. }
  780. /**
  781. * Return specified named destination
  782. *
  783. * @param string $name
  784. * @return Zend_Pdf_Destination_Explicit|Zend_Pdf_Action_GoTo
  785. */
  786. public function getNamedDestination($name)
  787. {
  788. if (isset($this->_namedTargets[$name])) {
  789. return $this->_namedTargets[$name];
  790. } else {
  791. return null;
  792. }
  793. }
  794. /**
  795. * Set specified named destination
  796. *
  797. * @param string $name
  798. * @param Zend_Pdf_Destination_Explicit|Zend_Pdf_Action_GoTo $target
  799. */
  800. public function setNamedDestination($name, $destination = null)
  801. {
  802. if ($destination !== null &&
  803. !$destination instanceof Zend_Pdf_Action_GoTo &&
  804. !$destination instanceof Zend_Pdf_Destination_Explicit) {
  805. require_once 'Zend/Pdf/Exception.php';
  806. throw new Zend_Pdf_Exception('PDF named destination must refer an explicit destination or a GoTo PDF action.');
  807. }
  808. if ($destination !== null) {
  809. $this->_namedTargets[$name] = $destination;
  810. } else {
  811. unset($this->_namedTargets[$name]);
  812. }
  813. }
  814. /**
  815. * Pages collection hash:
  816. * <page dictionary object hash id> => Zend_Pdf_Page
  817. *
  818. * @var SplObjectStorage
  819. */
  820. protected $_pageReferences = null;
  821. /**
  822. * Pages collection hash:
  823. * <page number> => Zend_Pdf_Page
  824. *
  825. * @var array
  826. */
  827. protected $_pageNumbers = null;
  828. /**
  829. * Refresh page collection hashes
  830. *
  831. * @return Zend_Pdf
  832. */
  833. protected function _refreshPagesHash()
  834. {
  835. $this->_pageReferences = array();
  836. $this->_pageNumbers = array();
  837. $count = 1;
  838. foreach ($this->pages as $page) {
  839. $pageDictionaryHashId = spl_object_hash($page->getPageDictionary()->getObject());
  840. $this->_pageReferences[$pageDictionaryHashId] = $page;
  841. $this->_pageNumbers[$count++] = $page;
  842. }
  843. return $this;
  844. }
  845. /**
  846. * Resolve destination.
  847. *
  848. * Returns Zend_Pdf_Page page object or null if destination is not found within PDF document.
  849. *
  850. * @param Zend_Pdf_Destination $destination Destination to resolve
  851. * @param boolean $refreshPagesHash Refresh page collection hashes before processing
  852. * @return Zend_Pdf_Page|null
  853. * @throws Zend_Pdf_Exception
  854. */
  855. public function resolveDestination(Zend_Pdf_Destination $destination, $refreshPageCollectionHashes = true)
  856. {
  857. if ($this->_pageReferences === null || $refreshPageCollectionHashes) {
  858. $this->_refreshPagesHash();
  859. }
  860. if ($destination instanceof Zend_Pdf_Destination_Named) {
  861. if (!isset($this->_namedTargets[$destination->getName()])) {
  862. return null;
  863. }
  864. $destination = $this->getNamedDestination($destination->getName());
  865. if ($destination instanceof Zend_Pdf_Action) {
  866. if (!$destination instanceof Zend_Pdf_Action_GoTo) {
  867. return null;
  868. }
  869. $destination = $destination->getDestination();
  870. }
  871. if (!$destination instanceof Zend_Pdf_Destination_Explicit) {
  872. require_once 'Zend/Pdf/Exception.php';
  873. throw new Zend_Pdf_Exception('Named destination target has to be an explicit destination.');
  874. }
  875. }
  876. // Named target is an explicit destination
  877. $pageElement = $destination->getResource()->items[0];
  878. if ($pageElement->getType() == Zend_Pdf_Element::TYPE_NUMERIC) {
  879. // Page reference is a PDF number
  880. if (!isset($this->_pageNumbers[$pageElement->value])) {
  881. return null;
  882. }
  883. return $this->_pageNumbers[$pageElement->value];
  884. }
  885. // Page reference is a PDF page dictionary reference
  886. $pageDictionaryHashId = spl_object_hash($pageElement->getObject());
  887. if (!isset($this->_pageReferences[$pageDictionaryHashId])) {
  888. return null;
  889. }
  890. return $this->_pageReferences[$pageDictionaryHashId];
  891. }
  892. /**
  893. * Walk through action and its chained actions tree and remove nodes
  894. * if they are GoTo actions with an unresolved target.
  895. *
  896. * Returns null if root node is deleted or updated action overwise.
  897. *
  898. * @todo Give appropriate name and make method public
  899. *
  900. * @param $action
  901. * @param boolean $refreshPagesHash Refresh page collection hashes before processing
  902. * @return Zend_Pdf_Action|null
  903. */
  904. protected function _cleanUpAction(Zend_Pdf_Action $action, $refreshPageCollectionHashes = true)
  905. {
  906. if ($this->_pageReferences === null || $refreshPageCollectionHashes) {
  907. $this->_refreshPagesHash();
  908. }
  909. // Named target is an action
  910. if ($action instanceof Zend_Pdf_Action_GoTo &&
  911. $this->resolveDestination($action->getDestination(), false) === null) {
  912. // Action itself is a GoTo action with an unresolved destination
  913. return null;
  914. }
  915. // Walk through child actions
  916. $iterator = new RecursiveIteratorIterator($action, RecursiveIteratorIterator::SELF_FIRST);
  917. $actionsToClean = array();
  918. $deletionCandidateKeys = array();
  919. foreach ($iterator as $chainedAction) {
  920. if ($chainedAction instanceof Zend_Pdf_Action_GoTo &&
  921. $this->resolveDestination($chainedAction->getDestination(), false) === null) {
  922. // Some child action is a GoTo action with an unresolved destination
  923. // Mark it as a candidate for deletion
  924. $actionsToClean[] = $iterator->getSubIterator();
  925. $deletionCandidateKeys[] = $iterator->getSubIterator()->key();
  926. }
  927. }
  928. foreach ($actionsToClean as $id => $action) {
  929. unset($action->next[$deletionCandidateKeys[$id]]);
  930. }
  931. return $action;
  932. }
  933. /**
  934. * Extract fonts attached to the document
  935. *
  936. * returns array of Zend_Pdf_Resource_Font_Extracted objects
  937. *
  938. * @return array
  939. * @throws Zend_Pdf_Exception
  940. */
  941. public function extractFonts()
  942. {
  943. $fontResourcesUnique = array();
  944. foreach ($this->pages as $page) {
  945. $pageResources = $page->extractResources();
  946. if ($pageResources->Font === null) {
  947. // Page doesn't contain have any font reference
  948. continue;
  949. }
  950. $fontResources = $pageResources->Font;
  951. foreach ($fontResources->getKeys() as $fontResourceName) {
  952. $fontDictionary = $fontResources->$fontResourceName;
  953. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  954. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  955. require_once 'Zend/Pdf/Exception.php';
  956. throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
  957. }
  958. $fontResourcesUnique[spl_object_hash($fontDictionary->getObject())] = $fontDictionary;
  959. }
  960. }
  961. $fonts = array();
  962. require_once 'Zend/Pdf/Exception.php';
  963. foreach ($fontResourcesUnique as $resourceId => $fontDictionary) {
  964. try {
  965. // Try to extract font
  966. $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  967. $fonts[$resourceId] = $extractedFont;
  968. } catch (Zend_Pdf_Exception $e) {
  969. if ($e->getMessage() != 'Unsupported font type.') {
  970. throw $e;
  971. }
  972. }
  973. }
  974. return $fonts;
  975. }
  976. /**
  977. * Extract font attached to the page by specific font name
  978. *
  979. * $fontName should be specified in UTF-8 encoding
  980. *
  981. * @return Zend_Pdf_Resource_Font_Extracted|null
  982. * @throws Zend_Pdf_Exception
  983. */
  984. public function extractFont($fontName)
  985. {
  986. $fontResourcesUnique = array();
  987. require_once 'Zend/Pdf/Exception.php';
  988. foreach ($this->pages as $page) {
  989. $pageResources = $page->extractResources();
  990. if ($pageResources->Font === null) {
  991. // Page doesn't contain have any font reference
  992. continue;
  993. }
  994. $fontResources = $pageResources->Font;
  995. foreach ($fontResources->getKeys() as $fontResourceName) {
  996. $fontDictionary = $fontResources->$fontResourceName;
  997. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  998. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  999. require_once 'Zend/Pdf/Exception.php';
  1000. throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
  1001. }
  1002. $resourceId = spl_object_hash($fontDictionary->getObject());
  1003. if (isset($fontResourcesUnique[$resourceId])) {
  1004. continue;
  1005. } else {
  1006. // Mark resource as processed
  1007. $fontResourcesUnique[$resourceId] = 1;
  1008. }
  1009. if ($fontDictionary->BaseFont->value != $fontName) {
  1010. continue;
  1011. }
  1012. try {
  1013. // Try to extract font
  1014. return new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  1015. } catch (Zend_Pdf_Exception $e) {
  1016. if ($e->getMessage() != 'Unsupported font type.') {
  1017. throw $e;
  1018. }
  1019. // Continue searhing
  1020. }
  1021. }
  1022. }
  1023. return null;
  1024. }
  1025. /**
  1026. * Render the completed PDF to a string.
  1027. * If $newSegmentOnly is true, then only appended part of PDF is returned.
  1028. *
  1029. * @param boolean $newSegmentOnly
  1030. * @param resource $outputStream
  1031. * @return string
  1032. * @throws Zend_Pdf_Exception
  1033. */
  1034. public function render($newSegmentOnly = false, $outputStream = null)
  1035. {
  1036. // Save document properties if necessary
  1037. if ($this->properties != $this->_originalProperties) {
  1038. $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  1039. foreach ($this->properties as $key => $value) {
  1040. switch ($key) {
  1041. case 'Trapped':
  1042. switch ($value) {
  1043. case true:
  1044. $docInfo->$key = new Zend_Pdf_Element_Name('True');
  1045. break;
  1046. case false:
  1047. $docInfo->$key = new Zend_Pdf_Element_Name('False');
  1048. break;
  1049. case null:
  1050. $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');
  1051. break;
  1052. default:
  1053. require_once 'Zend/Pdf/Exception.php';
  1054. throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');
  1055. break;
  1056. }
  1057. case 'CreationDate':
  1058. // break intentionally omitted
  1059. case 'ModDate':
  1060. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  1061. break;
  1062. case 'Title':
  1063. // break intentionally omitted
  1064. case 'Author':
  1065. // break intentionally omitted
  1066. case 'Subject':
  1067. // break intentionally omitted
  1068. case 'Keywords':
  1069. // break intentionally omitted
  1070. case 'Creator':
  1071. // break intentionally omitted
  1072. case 'Producer':
  1073. if (extension_loaded('mbstring') === true) {
  1074. $detected = mb_detect_encoding($value);
  1075. if ($detected !== 'ASCII') {
  1076. $value = chr(254) . chr(255) . mb_convert_encoding($value, 'UTF-16', $detected);
  1077. }
  1078. }
  1079. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  1080. break;
  1081. default:
  1082. // Set property using PDF type based on PHP type
  1083. $docInfo->$key = Zend_Pdf_Element::phpToPdf($value);
  1084. break;
  1085. }
  1086. }
  1087. $this->_trailer->Info = $docInfo;
  1088. }
  1089. $this->_dumpPages();
  1090. $this->_dumpNamedDestinations();
  1091. $this->_dumpOutlines();
  1092. // Check, that PDF file was modified
  1093. // File is always modified by _dumpPages() now, but future implementations may eliminate this.
  1094. if (!$this->_objFactory->isModified()) {
  1095. if ($newSegmentOnly) {
  1096. // Do nothing, return
  1097. return '';
  1098. }
  1099. if ($outputStream === null) {
  1100. return $this->_trailer->getPDFString();
  1101. } else {
  1102. $pdfData = $this->_trailer->getPDFString();
  1103. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  1104. $pdfData = substr($pdfData, $byteCount);
  1105. }
  1106. return '';
  1107. }
  1108. }
  1109. // offset (from a start of PDF file) of new PDF file segment
  1110. $offset = $this->_trailer->getPDFLength();
  1111. // Last Object number in a list of free objects
  1112. $lastFreeObject = $this->_trailer->getLastFreeObject();
  1113. // Array of cross-reference table subsections
  1114. $xrefTable = array();
  1115. // Object numbers of first objects in each subsection
  1116. $xrefSectionStartNums = array();
  1117. // Last cross-reference table subsection
  1118. $xrefSection = array();
  1119. // Dummy initialization of the first element (specail case - header of linked list of free objects).
  1120. $xrefSection[] = 0;
  1121. $xrefSectionStartNums[] = 0;
  1122. // Object number of last processed PDF object.
  1123. // Used to manage cross-reference subsections.
  1124. // Initialized by zero (specail case - header of linked list of free objects).
  1125. $lastObjNum = 0;
  1126. if ($outputStream !== null) {
  1127. if (!$newSegmentOnly) {
  1128. $pdfData = $this->_trailer->getPDFString();
  1129. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  1130. $pdfData = substr($pdfData, $byteCount);
  1131. }
  1132. }
  1133. } else {
  1134. $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());
  1135. }
  1136. // Iterate objects to create new reference table
  1137. foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {
  1138. $objNum = $updateInfo->getObjNum();
  1139. if ($objNum - $lastObjNum != 1) {
  1140. // Save cross-reference table subsection and start new one
  1141. $xrefTable[] = $xrefSection;
  1142. $xrefSection = array();
  1143. $xrefSectionStartNums[] = $objNum;
  1144. }
  1145. if ($updateInfo->isFree()) {
  1146. // Free object cross-reference table entry
  1147. $xrefSection[] = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());
  1148. $lastFreeObject = $objNum;
  1149. } else {
  1150. // In-use object cross-reference table entry
  1151. $xrefSection[] = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());
  1152. $pdfBlock = $updateInfo->getObjectDump();
  1153. $offset += strlen($pdfBlock);
  1154. if ($outputStream === null) {
  1155. $pdfSegmentBlocks[] = $pdfBlock;
  1156. } else {
  1157. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  1158. $pdfBlock = substr($pdfBlock, $byteCount);
  1159. }
  1160. }
  1161. }
  1162. $lastObjNum = $objNum;
  1163. }
  1164. // Save last cross-reference table subsection
  1165. $xrefTable[] = $xrefSection;
  1166. // Modify first entry (specail case - header of linked list of free objects).
  1167. $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);
  1168. $xrefTableStr = "xref\n";
  1169. foreach ($xrefTable as $sectId => $xrefSection) {
  1170. $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));
  1171. foreach ($xrefSection as $xrefTableEntry) {
  1172. $xrefTableStr .= $xrefTableEntry;
  1173. }
  1174. }
  1175. $this->_trailer->Size->value = $this->_objFactory->getObjectCount();
  1176. $pdfBlock = $xrefTableStr
  1177. . $this->_trailer->toString()
  1178. . "startxref\n" . $offset . "\n"
  1179. . "%%EOF\n";
  1180. $this->_objFactory->cleanEnumerationShiftCache();
  1181. if ($outputStream === null) {
  1182. $pdfSegmentBlocks[] = $pdfBlock;
  1183. return implode('', $pdfSegmentBlocks);
  1184. } else {
  1185. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  1186. $pdfBlock = substr($pdfBlock, $byteCount);
  1187. }
  1188. return '';
  1189. }
  1190. }
  1191. /**
  1192. * Set the document-level JavaScript
  1193. *
  1194. * @param string $javascript
  1195. */
  1196. public function setJavaScript($javascript)
  1197. {
  1198. $this->_javaScript = $javascript;
  1199. }
  1200. /**
  1201. * Convert date to PDF format (it's close to ASN.1 (Abstract Syntax Notation
  1202. * One) defined in ISO/IEC 8824).
  1203. *
  1204. * @todo This really isn't the best location for this method. It should
  1205. * probably actually exist as Zend_Pdf_Element_Date or something like that.
  1206. *
  1207. * @todo Address the following E_STRICT issue:
  1208. * PHP Strict Standards: date(): It is not safe to rely on the system's
  1209. * timezone settings. Please use the date.timezone setting, the TZ
  1210. * environment variable or the date_default_timezone_set() function. In
  1211. * case you used any of those methods and you are still getting this
  1212. * warning, you most likely misspelled the timezone identifier.
  1213. *
  1214. * @param integer $timestamp (optional) If omitted, uses the current time.
  1215. * @return string
  1216. */
  1217. public static function pdfDate($timestamp = null)
  1218. {
  1219. if ($timestamp === null) {
  1220. $date = date('\D\:YmdHisO');
  1221. } else {
  1222. $date = date('\D\:YmdHisO', $timestamp);
  1223. }
  1224. return substr_replace($date, '\'', -2, 0) . '\'';
  1225. }
  1226. }