Pdf.php 50 KB

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