Pdf.php 52 KB

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