Pdf.php 49 KB

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