Pdf.php 48 KB

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