Pdf.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  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. if ( $field->FT->value == 'Tx' && $field->T !== null ) /* We only support fields that are textfields and have a name */
  544. {
  545. $this->_formFields[$field->T->value] = $field;
  546. }
  547. }
  548. if ( !$root->AcroForm->NeedAppearances || !$root->AcroForm->NeedAppearances->value )
  549. {
  550. /* Ask the .pdf viewer to generate its own appearance data, so we do not have to */
  551. $root->AcroForm->add(new Zend_Pdf_Element_Name('NeedAppearances'), new Zend_Pdf_Element_Boolean(true) );
  552. $root->AcroForm->touch();
  553. }
  554. }
  555. /**
  556. * Retrieves a list with the names of the AcroForm textfields in the PDF
  557. *
  558. * @return array of strings
  559. */
  560. public function getTextFieldNames()
  561. {
  562. return array_keys($this->_formFields);
  563. }
  564. /**
  565. * Sets the value of an AcroForm text field
  566. *
  567. * @param string $name Name of textfield
  568. * @param string $value Value
  569. * @throws Zend_Pdf_Exception if the textfield does not exist in the pdf
  570. */
  571. public function setTextField($name, $value)
  572. {
  573. if ( !isset($this->_formFields[$name]))
  574. throw new Zend_Pdf_Exception("Field '$name' does not exist or is not a textfield");
  575. $field = $this->_formFields[$name];
  576. $field->add(new Zend_Pdf_Element_Name('V'), new Zend_Pdf_Element_String($value) );
  577. $field->touch();
  578. }
  579. public function setTextFieldProperties($name, $bitmask)
  580. {
  581. if ( !isset($this->_formFields[$name]))
  582. throw new Zend_Pdf_Exception("Field '$name' does not exist or is not a textfield");
  583. $field = $this->_formFields[$name];
  584. $field->add(new Zend_Pdf_Element_Name('Ff'), new Zend_Pdf_Element_Numeric($bitmask));
  585. $field->touch();
  586. }
  587. public function markTextFieldAsReadOnly($name)
  588. {
  589. $this->setTextFieldProperties($name, self::PDF_FORM_FIELD_READONLY);
  590. }
  591. /**
  592. * Orginize pages to tha pages tree structure.
  593. *
  594. * @todo atomatically attach page to the document, if it's not done yet.
  595. * @todo check, that page is attached to the current document
  596. *
  597. * @todo Dump pages as a balanced tree instead of a plain set.
  598. */
  599. protected function _dumpPages()
  600. {
  601. $root = $this->_trailer->Root;
  602. $pagesContainer = $root->Pages;
  603. $pagesContainer->touch();
  604. $pagesContainer->Kids->items = array();
  605. foreach ($this->pages as $page ) {
  606. $page->render($this->_objFactory);
  607. $pageDictionary = $page->getPageDictionary();
  608. $pageDictionary->touch();
  609. $pageDictionary->Parent = $pagesContainer;
  610. $pagesContainer->Kids->items[] = $pageDictionary;
  611. }
  612. $this->_refreshPagesHash();
  613. $pagesContainer->Count->touch();
  614. $pagesContainer->Count->value = count($this->pages);
  615. // Refresh named destinations list
  616. foreach ($this->_namedTargets as $name => $namedTarget) {
  617. if ($namedTarget instanceof Zend_Pdf_Destination_Explicit) {
  618. // Named target is an explicit destination
  619. if ($this->resolveDestination($namedTarget, false) === null) {
  620. unset($this->_namedTargets[$name]);
  621. }
  622. } else if ($namedTarget instanceof Zend_Pdf_Action) {
  623. // Named target is an action
  624. if ($this->_cleanUpAction($namedTarget, false) === null) {
  625. // Action is a GoTo action with an unresolved destination
  626. unset($this->_namedTargets[$name]);
  627. }
  628. } else {
  629. require_once 'Zend/Pdf/Exception.php';
  630. throw new Zend_Pdf_Exception('Wrong type of named targed (\'' . get_class($namedTarget) . '\').');
  631. }
  632. }
  633. // Refresh outlines
  634. require_once 'Zend/Pdf/RecursivelyIteratableObjectsContainer.php';
  635. $iterator = new RecursiveIteratorIterator(new Zend_Pdf_RecursivelyIteratableObjectsContainer($this->outlines), RecursiveIteratorIterator::SELF_FIRST);
  636. foreach ($iterator as $outline) {
  637. $target = $outline->getTarget();
  638. if ($target !== null) {
  639. if ($target instanceof Zend_Pdf_Destination) {
  640. // Outline target is a destination
  641. if ($this->resolveDestination($target, false) === null) {
  642. $outline->setTarget(null);
  643. }
  644. } else if ($target instanceof Zend_Pdf_Action) {
  645. // Outline target is an action
  646. if ($this->_cleanUpAction($target, false) === null) {
  647. // Action is a GoTo action with an unresolved destination
  648. $outline->setTarget(null);
  649. }
  650. } else {
  651. require_once 'Zend/Pdf/Exception.php';
  652. throw new Zend_Pdf_Exception('Wrong outline target.');
  653. }
  654. }
  655. }
  656. $openAction = $this->getOpenAction();
  657. if ($openAction !== null) {
  658. if ($openAction instanceof Zend_Pdf_Action) {
  659. // OpenAction is an action
  660. if ($this->_cleanUpAction($openAction, false) === null) {
  661. // Action is a GoTo action with an unresolved destination
  662. $this->setOpenAction(null);
  663. }
  664. } else if ($openAction instanceof Zend_Pdf_Destination) {
  665. // OpenAction target is a destination
  666. if ($this->resolveDestination($openAction, false) === null) {
  667. $this->setOpenAction(null);
  668. }
  669. } else {
  670. require_once 'Zend/Pdf/Exception.php';
  671. throw new Zend_Pdf_Exception('OpenAction has to be either PDF Action or Destination.');
  672. }
  673. }
  674. }
  675. /**
  676. * Dump named destinations
  677. *
  678. * @todo Create a balanced tree instead of plain structure.
  679. */
  680. protected function _dumpNamedDestinations()
  681. {
  682. ksort($this->_namedTargets, SORT_STRING);
  683. $destArrayItems = array();
  684. foreach ($this->_namedTargets as $name => $destination) {
  685. $destArrayItems[] = new Zend_Pdf_Element_String($name);
  686. if ($destination instanceof Zend_Pdf_Target) {
  687. $destArrayItems[] = $destination->getResource();
  688. } else {
  689. require_once 'Zend/Pdf/Exception.php';
  690. throw new Zend_Pdf_Exception('PDF named destinations must be a Zend_Pdf_Target object.');
  691. }
  692. }
  693. $destArray = $this->_objFactory->newObject(new Zend_Pdf_Element_Array($destArrayItems));
  694. $DestTree = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  695. $DestTree->Names = $destArray;
  696. $root = $this->_trailer->Root;
  697. if ($root->Names === null) {
  698. $root->touch();
  699. $root->Names = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  700. } else {
  701. $root->Names->touch();
  702. }
  703. $root->Names->Dests = $DestTree;
  704. }
  705. /**
  706. * Dump outlines recursively
  707. */
  708. protected function _dumpOutlines()
  709. {
  710. $root = $this->_trailer->Root;
  711. if ($root->Outlines === null) {
  712. if (count($this->outlines) == 0) {
  713. return;
  714. } else {
  715. $root->Outlines = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  716. $root->Outlines->Type = new Zend_Pdf_Element_Name('Outlines');
  717. $updateOutlinesNavigation = true;
  718. }
  719. } else {
  720. $updateOutlinesNavigation = false;
  721. if (count($this->_originalOutlines) != count($this->outlines)) {
  722. // If original and current outlines arrays have different size then outlines list was updated
  723. $updateOutlinesNavigation = true;
  724. } else if ( !(array_keys($this->_originalOutlines) === array_keys($this->outlines)) ) {
  725. // If original and current outlines arrays have different keys (with a glance to an order) then outlines list was updated
  726. $updateOutlinesNavigation = true;
  727. } else {
  728. foreach ($this->outlines as $key => $outline) {
  729. if ($this->_originalOutlines[$key] !== $outline) {
  730. $updateOutlinesNavigation = true;
  731. }
  732. }
  733. }
  734. }
  735. $lastOutline = null;
  736. $openOutlinesCount = 0;
  737. if ($updateOutlinesNavigation) {
  738. $root->Outlines->touch();
  739. $root->Outlines->First = null;
  740. foreach ($this->outlines as $outline) {
  741. if ($lastOutline === null) {
  742. // First pass. Update Outlines dictionary First entry using corresponding value
  743. $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines);
  744. $root->Outlines->First = $lastOutline;
  745. } else {
  746. // Update previous outline dictionary Next entry (Prev is updated within dumpOutline() method)
  747. $currentOutlineDictionary = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
  748. $lastOutline->Next = $currentOutlineDictionary;
  749. $lastOutline = $currentOutlineDictionary;
  750. }
  751. $openOutlinesCount += $outline->openOutlinesCount();
  752. }
  753. $root->Outlines->Last = $lastOutline;
  754. } else {
  755. foreach ($this->outlines as $outline) {
  756. $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
  757. $openOutlinesCount += $outline->openOutlinesCount();
  758. }
  759. }
  760. if ($openOutlinesCount != $this->_originalOpenOutlinesCount) {
  761. $root->Outlines->touch;
  762. $root->Outlines->Count = new Zend_Pdf_Element_Numeric($openOutlinesCount);
  763. }
  764. }
  765. /**
  766. * Create page object, attached to the PDF document.
  767. * Method signatures:
  768. *
  769. * 1. Create new page with a specified pagesize.
  770. * If $factory is null then it will be created and page must be attached to the document to be
  771. * included into output.
  772. * ---------------------------------------------------------
  773. * new Zend_Pdf_Page(string $pagesize);
  774. * ---------------------------------------------------------
  775. *
  776. * 2. Create new page with a specified pagesize (in default user space units).
  777. * If $factory is null then it will be created and page must be attached to the document to be
  778. * included into output.
  779. * ---------------------------------------------------------
  780. * new Zend_Pdf_Page(numeric $width, numeric $height);
  781. * ---------------------------------------------------------
  782. *
  783. * @param mixed $param1
  784. * @param mixed $param2
  785. * @return Zend_Pdf_Page
  786. */
  787. public function newPage($param1, $param2 = null)
  788. {
  789. require_once 'Zend/Pdf/Page.php';
  790. if ($param2 === null) {
  791. return new Zend_Pdf_Page($param1, $this->_objFactory);
  792. } else {
  793. return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);
  794. }
  795. }
  796. /**
  797. * Return the document-level Metadata
  798. * or null Metadata stream is not presented
  799. *
  800. * @return string
  801. */
  802. public function getMetadata()
  803. {
  804. if ($this->_trailer->Root->Metadata !== null) {
  805. return $this->_trailer->Root->Metadata->value;
  806. } else {
  807. return null;
  808. }
  809. }
  810. /**
  811. * Sets the document-level Metadata (mast be valid XMP document)
  812. *
  813. * @param string $metadata
  814. */
  815. public function setMetadata($metadata)
  816. {
  817. $metadataObject = $this->_objFactory->newStreamObject($metadata);
  818. $metadataObject->dictionary->Type = new Zend_Pdf_Element_Name('Metadata');
  819. $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');
  820. $this->_trailer->Root->Metadata = $metadataObject;
  821. $this->_trailer->Root->touch();
  822. }
  823. /**
  824. * Return the document-level JavaScript
  825. * or null if there is no JavaScript for this document
  826. *
  827. * @return string
  828. */
  829. public function getJavaScript()
  830. {
  831. return $this->_javaScript;
  832. }
  833. /**
  834. * Get open Action
  835. * Returns Zend_Pdf_Target (Zend_Pdf_Destination or Zend_Pdf_Action object)
  836. *
  837. * @return Zend_Pdf_Target
  838. */
  839. public function getOpenAction()
  840. {
  841. if ($this->_trailer->Root->OpenAction !== null) {
  842. require_once 'Zend/Pdf/Target.php';
  843. return Zend_Pdf_Target::load($this->_trailer->Root->OpenAction);
  844. } else {
  845. return null;
  846. }
  847. }
  848. /**
  849. * Set open Action which is actually Zend_Pdf_Destination or Zend_Pdf_Action object
  850. *
  851. * @param Zend_Pdf_Target $openAction
  852. * @returns Zend_Pdf
  853. */
  854. public function setOpenAction(Zend_Pdf_Target $openAction = null)
  855. {
  856. $root = $this->_trailer->Root;
  857. $root->touch();
  858. if ($openAction === null) {
  859. $root->OpenAction = null;
  860. } else {
  861. $root->OpenAction = $openAction->getResource();
  862. if ($openAction instanceof Zend_Pdf_Action) {
  863. $openAction->dumpAction($this->_objFactory);
  864. }
  865. }
  866. return $this;
  867. }
  868. /**
  869. * Return an associative array containing all the named destinations (or GoTo actions) in the PDF.
  870. * Named targets can be used to reference from outside
  871. * the PDF, ex: 'http://www.something.com/mydocument.pdf#MyAction'
  872. *
  873. * @return array
  874. */
  875. public function getNamedDestinations()
  876. {
  877. return $this->_namedTargets;
  878. }
  879. /**
  880. * Return specified named destination
  881. *
  882. * @param string $name
  883. * @return Zend_Pdf_Destination_Explicit|Zend_Pdf_Action_GoTo
  884. */
  885. public function getNamedDestination($name)
  886. {
  887. if (isset($this->_namedTargets[$name])) {
  888. return $this->_namedTargets[$name];
  889. } else {
  890. return null;
  891. }
  892. }
  893. /**
  894. * Set specified named destination
  895. *
  896. * @param string $name
  897. * @param Zend_Pdf_Destination_Explicit|Zend_Pdf_Action_GoTo $destination
  898. * @throws Zend_Pdf_Exception
  899. */
  900. public function setNamedDestination($name, $destination = null)
  901. {
  902. if ($destination !== null &&
  903. !$destination instanceof Zend_Pdf_Action_GoTo &&
  904. !$destination instanceof Zend_Pdf_Destination_Explicit) {
  905. require_once 'Zend/Pdf/Exception.php';
  906. throw new Zend_Pdf_Exception('PDF named destination must refer an explicit destination or a GoTo PDF action.');
  907. }
  908. if ($destination !== null) {
  909. $this->_namedTargets[$name] = $destination;
  910. } else {
  911. unset($this->_namedTargets[$name]);
  912. }
  913. }
  914. /**
  915. * Pages collection hash:
  916. * <page dictionary object hash id> => Zend_Pdf_Page
  917. *
  918. * @var SplObjectStorage
  919. */
  920. protected $_pageReferences = null;
  921. /**
  922. * Pages collection hash:
  923. * <page number> => Zend_Pdf_Page
  924. *
  925. * @var array
  926. */
  927. protected $_pageNumbers = null;
  928. /**
  929. * Refresh page collection hashes
  930. *
  931. * @return Zend_Pdf
  932. */
  933. protected function _refreshPagesHash()
  934. {
  935. $this->_pageReferences = array();
  936. $this->_pageNumbers = array();
  937. $count = 1;
  938. foreach ($this->pages as $page) {
  939. $pageDictionaryHashId = spl_object_hash($page->getPageDictionary()->getObject());
  940. $this->_pageReferences[$pageDictionaryHashId] = $page;
  941. $this->_pageNumbers[$count++] = $page;
  942. }
  943. return $this;
  944. }
  945. /**
  946. * Resolve destination.
  947. *
  948. * Returns Zend_Pdf_Page page object or null if destination is not found within PDF document.
  949. *
  950. * @param Zend_Pdf_Destination $destination Destination to resolve
  951. * @param bool $refreshPageCollectionHashes Refresh page collection hashes before processing
  952. * @return Zend_Pdf_Page|null
  953. * @throws Zend_Pdf_Exception
  954. */
  955. public function resolveDestination(Zend_Pdf_Destination $destination, $refreshPageCollectionHashes = true)
  956. {
  957. if ($this->_pageReferences === null || $refreshPageCollectionHashes) {
  958. $this->_refreshPagesHash();
  959. }
  960. if ($destination instanceof Zend_Pdf_Destination_Named) {
  961. if (!isset($this->_namedTargets[$destination->getName()])) {
  962. return null;
  963. }
  964. $destination = $this->getNamedDestination($destination->getName());
  965. if ($destination instanceof Zend_Pdf_Action) {
  966. if (!$destination instanceof Zend_Pdf_Action_GoTo) {
  967. return null;
  968. }
  969. $destination = $destination->getDestination();
  970. }
  971. if (!$destination instanceof Zend_Pdf_Destination_Explicit) {
  972. require_once 'Zend/Pdf/Exception.php';
  973. throw new Zend_Pdf_Exception('Named destination target has to be an explicit destination.');
  974. }
  975. }
  976. // Named target is an explicit destination
  977. $pageElement = $destination->getResource()->items[0];
  978. if ($pageElement->getType() == Zend_Pdf_Element::TYPE_NUMERIC) {
  979. // Page reference is a PDF number
  980. if (!isset($this->_pageNumbers[$pageElement->value])) {
  981. return null;
  982. }
  983. return $this->_pageNumbers[$pageElement->value];
  984. }
  985. // Page reference is a PDF page dictionary reference
  986. $pageDictionaryHashId = spl_object_hash($pageElement->getObject());
  987. if (!isset($this->_pageReferences[$pageDictionaryHashId])) {
  988. return null;
  989. }
  990. return $this->_pageReferences[$pageDictionaryHashId];
  991. }
  992. /**
  993. * Walk through action and its chained actions tree and remove nodes
  994. * if they are GoTo actions with an unresolved target.
  995. *
  996. * Returns null if root node is deleted or updated action overwise.
  997. *
  998. * @todo Give appropriate name and make method public
  999. *
  1000. * @param Zend_Pdf_Action $action
  1001. * @param bool $refreshPageCollectionHashes Refresh page collection hashes before processing
  1002. * @return Zend_Pdf_Action|null
  1003. */
  1004. protected function _cleanUpAction(Zend_Pdf_Action $action, $refreshPageCollectionHashes = true)
  1005. {
  1006. if ($this->_pageReferences === null || $refreshPageCollectionHashes) {
  1007. $this->_refreshPagesHash();
  1008. }
  1009. // Named target is an action
  1010. if ($action instanceof Zend_Pdf_Action_GoTo &&
  1011. $this->resolveDestination($action->getDestination(), false) === null) {
  1012. // Action itself is a GoTo action with an unresolved destination
  1013. return null;
  1014. }
  1015. // Walk through child actions
  1016. $iterator = new RecursiveIteratorIterator($action, RecursiveIteratorIterator::SELF_FIRST);
  1017. $actionsToClean = array();
  1018. $deletionCandidateKeys = array();
  1019. foreach ($iterator as $chainedAction) {
  1020. if ($chainedAction instanceof Zend_Pdf_Action_GoTo &&
  1021. $this->resolveDestination($chainedAction->getDestination(), false) === null) {
  1022. // Some child action is a GoTo action with an unresolved destination
  1023. // Mark it as a candidate for deletion
  1024. $actionsToClean[] = $iterator->getSubIterator();
  1025. $deletionCandidateKeys[] = $iterator->getSubIterator()->key();
  1026. }
  1027. }
  1028. foreach ($actionsToClean as $id => $action) {
  1029. unset($action->next[$deletionCandidateKeys[$id]]);
  1030. }
  1031. return $action;
  1032. }
  1033. /**
  1034. * Extract fonts attached to the document
  1035. *
  1036. * returns array of Zend_Pdf_Resource_Font_Extracted objects
  1037. *
  1038. * @return array
  1039. * @throws Zend_Pdf_Exception
  1040. */
  1041. public function extractFonts()
  1042. {
  1043. $fontResourcesUnique = array();
  1044. foreach ($this->pages as $page) {
  1045. $pageResources = $page->extractResources();
  1046. if ($pageResources->Font === null) {
  1047. // Page doesn't contain have any font reference
  1048. continue;
  1049. }
  1050. $fontResources = $pageResources->Font;
  1051. foreach ($fontResources->getKeys() as $fontResourceName) {
  1052. $fontDictionary = $fontResources->$fontResourceName;
  1053. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  1054. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  1055. require_once 'Zend/Pdf/Exception.php';
  1056. throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
  1057. }
  1058. $fontResourcesUnique[spl_object_hash($fontDictionary->getObject())] = $fontDictionary;
  1059. }
  1060. }
  1061. $fonts = array();
  1062. require_once 'Zend/Pdf/Exception.php';
  1063. foreach ($fontResourcesUnique as $resourceId => $fontDictionary) {
  1064. try {
  1065. // Try to extract font
  1066. require_once 'Zend/Pdf/Resource/Font/Extracted.php';
  1067. $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  1068. $fonts[$resourceId] = $extractedFont;
  1069. } catch (Zend_Pdf_Exception $e) {
  1070. if ($e->getMessage() != 'Unsupported font type.') {
  1071. throw $e;
  1072. }
  1073. }
  1074. }
  1075. return $fonts;
  1076. }
  1077. /**
  1078. * Extract font attached to the page by specific font name
  1079. *
  1080. * $fontName should be specified in UTF-8 encoding
  1081. *
  1082. * @param string $fontName
  1083. * @return Zend_Pdf_Resource_Font_Extracted|null
  1084. * @throws Zend_Pdf_Exception
  1085. */
  1086. public function extractFont($fontName)
  1087. {
  1088. $fontResourcesUnique = array();
  1089. require_once 'Zend/Pdf/Exception.php';
  1090. foreach ($this->pages as $page) {
  1091. $pageResources = $page->extractResources();
  1092. if ($pageResources->Font === null) {
  1093. // Page doesn't contain have any font reference
  1094. continue;
  1095. }
  1096. $fontResources = $pageResources->Font;
  1097. foreach ($fontResources->getKeys() as $fontResourceName) {
  1098. $fontDictionary = $fontResources->$fontResourceName;
  1099. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  1100. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  1101. require_once 'Zend/Pdf/Exception.php';
  1102. throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
  1103. }
  1104. $resourceId = spl_object_hash($fontDictionary->getObject());
  1105. if (isset($fontResourcesUnique[$resourceId])) {
  1106. continue;
  1107. } else {
  1108. // Mark resource as processed
  1109. $fontResourcesUnique[$resourceId] = 1;
  1110. }
  1111. if ($fontDictionary->BaseFont->value != $fontName) {
  1112. continue;
  1113. }
  1114. try {
  1115. // Try to extract font
  1116. require_once 'Zend/Pdf/Resource/Font/Extracted.php';
  1117. return new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  1118. } catch (Zend_Pdf_Exception $e) {
  1119. if ($e->getMessage() != 'Unsupported font type.') {
  1120. throw $e;
  1121. }
  1122. // Continue searhing
  1123. }
  1124. }
  1125. }
  1126. return null;
  1127. }
  1128. /**
  1129. * Render the completed PDF to a string.
  1130. * If $newSegmentOnly is true and it's not a new document,
  1131. * then only appended part of PDF is returned.
  1132. *
  1133. * @param boolean $newSegmentOnly
  1134. * @param resource $outputStream
  1135. * @return string
  1136. * @throws Zend_Pdf_Exception
  1137. */
  1138. public function render($newSegmentOnly = false, $outputStream = null)
  1139. {
  1140. if ($this->_isNewDocument) {
  1141. // Drop full document first time even $newSegmentOnly is set to true
  1142. $newSegmentOnly = false;
  1143. $this->_isNewDocument = false;
  1144. }
  1145. // Save document properties if necessary
  1146. if ($this->properties != $this->_originalProperties) {
  1147. $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  1148. foreach ($this->properties as $key => $value) {
  1149. switch ($key) {
  1150. case 'Trapped':
  1151. switch ($value) {
  1152. case true:
  1153. $docInfo->$key = new Zend_Pdf_Element_Name('True');
  1154. break;
  1155. case false:
  1156. $docInfo->$key = new Zend_Pdf_Element_Name('False');
  1157. break;
  1158. case null:
  1159. $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');
  1160. break;
  1161. default:
  1162. require_once 'Zend/Pdf/Exception.php';
  1163. throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');
  1164. break;
  1165. }
  1166. case 'CreationDate':
  1167. // break intentionally omitted
  1168. case 'ModDate':
  1169. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  1170. break;
  1171. case 'Title':
  1172. // break intentionally omitted
  1173. case 'Author':
  1174. // break intentionally omitted
  1175. case 'Subject':
  1176. // break intentionally omitted
  1177. case 'Keywords':
  1178. // break intentionally omitted
  1179. case 'Creator':
  1180. // break intentionally omitted
  1181. case 'Producer':
  1182. if (extension_loaded('mbstring') === true) {
  1183. $detected = mb_detect_encoding($value);
  1184. if ($detected !== 'ASCII') {
  1185. $value = "\xfe\xff" . mb_convert_encoding($value, 'UTF-16', $detected);
  1186. }
  1187. }
  1188. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  1189. break;
  1190. default:
  1191. // Set property using PDF type based on PHP type
  1192. $docInfo->$key = Zend_Pdf_Element::phpToPdf($value);
  1193. break;
  1194. }
  1195. }
  1196. $this->_trailer->Info = $docInfo;
  1197. }
  1198. $this->_dumpPages();
  1199. $this->_dumpNamedDestinations();
  1200. $this->_dumpOutlines();
  1201. // Check, that PDF file was modified
  1202. // File is always modified by _dumpPages() now, but future implementations may eliminate this.
  1203. if (!$this->_objFactory->isModified()) {
  1204. if ($newSegmentOnly) {
  1205. // Do nothing, return
  1206. return '';
  1207. }
  1208. if ($outputStream === null) {
  1209. return $this->_trailer->getPDFString();
  1210. } else {
  1211. $pdfData = $this->_trailer->getPDFString();
  1212. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  1213. $pdfData = substr($pdfData, $byteCount);
  1214. }
  1215. return '';
  1216. }
  1217. }
  1218. // offset (from a start of PDF file) of new PDF file segment
  1219. $offset = $this->_trailer->getPDFLength();
  1220. // Last Object number in a list of free objects
  1221. $lastFreeObject = $this->_trailer->getLastFreeObject();
  1222. // Array of cross-reference table subsections
  1223. $xrefTable = array();
  1224. // Object numbers of first objects in each subsection
  1225. $xrefSectionStartNums = array();
  1226. // Last cross-reference table subsection
  1227. $xrefSection = array();
  1228. // Dummy initialization of the first element (specail case - header of linked list of free objects).
  1229. $xrefSection[] = 0;
  1230. $xrefSectionStartNums[] = 0;
  1231. // Object number of last processed PDF object.
  1232. // Used to manage cross-reference subsections.
  1233. // Initialized by zero (specail case - header of linked list of free objects).
  1234. $lastObjNum = 0;
  1235. if ($outputStream !== null) {
  1236. if (!$newSegmentOnly) {
  1237. $pdfData = $this->_trailer->getPDFString();
  1238. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  1239. $pdfData = substr($pdfData, $byteCount);
  1240. }
  1241. }
  1242. } else {
  1243. $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());
  1244. }
  1245. // Iterate objects to create new reference table
  1246. foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {
  1247. $objNum = $updateInfo->getObjNum();
  1248. if ($objNum - $lastObjNum != 1) {
  1249. // Save cross-reference table subsection and start new one
  1250. $xrefTable[] = $xrefSection;
  1251. $xrefSection = array();
  1252. $xrefSectionStartNums[] = $objNum;
  1253. }
  1254. if ($updateInfo->isFree()) {
  1255. // Free object cross-reference table entry
  1256. $xrefSection[] = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());
  1257. $lastFreeObject = $objNum;
  1258. } else {
  1259. // In-use object cross-reference table entry
  1260. $xrefSection[] = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());
  1261. $pdfBlock = $updateInfo->getObjectDump();
  1262. $offset += strlen($pdfBlock);
  1263. if ($outputStream === null) {
  1264. $pdfSegmentBlocks[] = $pdfBlock;
  1265. } else {
  1266. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  1267. $pdfBlock = substr($pdfBlock, $byteCount);
  1268. }
  1269. }
  1270. }
  1271. $lastObjNum = $objNum;
  1272. }
  1273. // Save last cross-reference table subsection
  1274. $xrefTable[] = $xrefSection;
  1275. // Modify first entry (specail case - header of linked list of free objects).
  1276. $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);
  1277. $xrefTableStr = "xref\n";
  1278. foreach ($xrefTable as $sectId => $xrefSection) {
  1279. $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));
  1280. foreach ($xrefSection as $xrefTableEntry) {
  1281. $xrefTableStr .= $xrefTableEntry;
  1282. }
  1283. }
  1284. $this->_trailer->Size->value = $this->_objFactory->getObjectCount();
  1285. $pdfBlock = $xrefTableStr
  1286. . $this->_trailer->toString()
  1287. . "startxref\n" . $offset . "\n"
  1288. . "%%EOF\n";
  1289. $this->_objFactory->cleanEnumerationShiftCache();
  1290. if ($outputStream === null) {
  1291. $pdfSegmentBlocks[] = $pdfBlock;
  1292. return implode('', $pdfSegmentBlocks);
  1293. } else {
  1294. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  1295. $pdfBlock = substr($pdfBlock, $byteCount);
  1296. }
  1297. return '';
  1298. }
  1299. }
  1300. /**
  1301. * Sets the document-level JavaScript
  1302. *
  1303. * Resets and appends
  1304. *
  1305. * @param string|array $javaScript
  1306. */
  1307. public function setJavaScript($javaScript)
  1308. {
  1309. $this->resetJavaScript();
  1310. $this->addJavaScript($javaScript);
  1311. }
  1312. /**
  1313. * Resets the document-level JavaScript
  1314. */
  1315. public function resetJavaScript()
  1316. {
  1317. $this->_javaScript = null;
  1318. $root = $this->_trailer->Root;
  1319. if (null === $root->Names || null === $root->Names->JavaScript) {
  1320. return;
  1321. }
  1322. $root->Names->JavaScript = null;
  1323. }
  1324. /**
  1325. * Appends JavaScript to the document-level JavaScript
  1326. *
  1327. * @param string|array $javaScript
  1328. * @throws Zend_Pdf_Exception
  1329. */
  1330. public function addJavaScript($javaScript)
  1331. {
  1332. if (empty($javaScript)) {
  1333. throw new Zend_Pdf_Exception(
  1334. 'JavaScript must be a non empty string or array of strings'
  1335. );
  1336. }
  1337. if (!is_array($javaScript)) {
  1338. $javaScript = array($javaScript);
  1339. }
  1340. if (null === $this->_javaScript) {
  1341. $this->_javaScript = $javaScript;
  1342. } else {
  1343. $this->_javaScript = array_merge($this->_javaScript, $javaScript);
  1344. }
  1345. if (!empty($this->_javaScript)) {
  1346. $items = array();
  1347. foreach ($this->_javaScript as $javaScript) {
  1348. $jsCode = array(
  1349. 'S' => new Zend_Pdf_Element_Name('JavaScript'),
  1350. 'JS' => new Zend_Pdf_Element_String($javaScript)
  1351. );
  1352. $items[] = new Zend_Pdf_Element_String('EmbeddedJS');
  1353. $items[] = $this->_objFactory->newObject(
  1354. new Zend_Pdf_Element_Dictionary($jsCode)
  1355. );
  1356. }
  1357. $jsRef = $this->_objFactory->newObject(
  1358. new Zend_Pdf_Element_Dictionary(
  1359. array('Names' => new Zend_Pdf_Element_Array($items))
  1360. )
  1361. );
  1362. if (null === $this->_trailer->Root->Names) {
  1363. $this->_trailer->Root->Names = new Zend_Pdf_Element_Dictionary();
  1364. }
  1365. $this->_trailer->Root->Names->JavaScript = $jsRef;
  1366. }
  1367. }
  1368. /**
  1369. * Convert date to PDF format (it's close to ASN.1 (Abstract Syntax Notation
  1370. * One) defined in ISO/IEC 8824).
  1371. *
  1372. * @todo This really isn't the best location for this method. It should
  1373. * probably actually exist as Zend_Pdf_Element_Date or something like that.
  1374. *
  1375. * @todo Address the following E_STRICT issue:
  1376. * PHP Strict Standards: date(): It is not safe to rely on the system's
  1377. * timezone settings. Please use the date.timezone setting, the TZ
  1378. * environment variable or the date_default_timezone_set() function. In
  1379. * case you used any of those methods and you are still getting this
  1380. * warning, you most likely misspelled the timezone identifier.
  1381. *
  1382. * @param integer $timestamp (optional) If omitted, uses the current time.
  1383. * @return string
  1384. */
  1385. public static function pdfDate($timestamp = null)
  1386. {
  1387. if ($timestamp === null) {
  1388. $date = date('\D\:YmdHisO');
  1389. } else {
  1390. $date = date('\D\:YmdHisO', $timestamp);
  1391. }
  1392. return substr_replace($date, '\'', -2, 0) . '\'';
  1393. }
  1394. }