Pdf.php 52 KB

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