Pdf.php 48 KB

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