Pdf.php 55 KB

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