Pdf.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Pdf
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /** Zend_Pdf_Page */
  22. require_once 'Zend/Pdf/Page.php';
  23. /** Zend_Pdf_Cmap */
  24. require_once 'Zend/Pdf/Cmap.php';
  25. /** Zend_Pdf_Font */
  26. require_once 'Zend/Pdf/Font.php';
  27. /** Zend_Pdf_Style */
  28. require_once 'Zend/Pdf/Style.php';
  29. /** Zend_Pdf_Parser */
  30. require_once 'Zend/Pdf/Parser.php';
  31. /** Zend_Pdf_Trailer */
  32. require_once 'Zend/Pdf/Trailer.php';
  33. /** Zend_Pdf_Trailer_Generator */
  34. require_once 'Zend/Pdf/Trailer/Generator.php';
  35. /** Zend_Pdf_Color */
  36. require_once 'Zend/Pdf/Color.php';
  37. /** Zend_Pdf_Color_GrayScale */
  38. require_once 'Zend/Pdf/Color/GrayScale.php';
  39. /** Zend_Pdf_Color_Rgb */
  40. require_once 'Zend/Pdf/Color/Rgb.php';
  41. /** Zend_Pdf_Color_Cmyk */
  42. require_once 'Zend/Pdf/Color/Cmyk.php';
  43. /** Zend_Pdf_Color_Html */
  44. require_once 'Zend/Pdf/Color/Html.php';
  45. /** Zend_Pdf_Image */
  46. require_once 'Zend/Pdf/Resource/Image.php';
  47. /** Zend_Pdf_Image */
  48. require_once 'Zend/Pdf/Image.php';
  49. /** Zend_Pdf_Image_Jpeg */
  50. require_once 'Zend/Pdf/Resource/Image/Jpeg.php';
  51. /** Zend_Pdf_Image_Tiff */
  52. require_once 'Zend/Pdf/Resource/Image/Tiff.php';
  53. /** Zend_Pdf_Image_Png */
  54. require_once 'Zend/Pdf/Resource/Image/Png.php';
  55. /** Zend_Memory */
  56. require_once 'Zend/Memory.php';
  57. /**
  58. * General entity which describes PDF document.
  59. * It implements document abstraction with a document level operations.
  60. *
  61. * Class is used to create new PDF document or load existing document.
  62. * See details in a class constructor description
  63. *
  64. * Class agregates document level properties and entities (pages, bookmarks,
  65. * document level actions, attachments, form object, etc)
  66. *
  67. * @category Zend
  68. * @package Zend_Pdf
  69. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  70. * @license http://framework.zend.com/license/new-bsd New BSD License
  71. */
  72. class Zend_Pdf
  73. {
  74. /**** Class Constants ****/
  75. /**
  76. * Version number of generated PDF documents.
  77. */
  78. const PDF_VERSION = 1.4;
  79. /**
  80. * PDF file header.
  81. */
  82. const PDF_HEADER = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
  83. /**
  84. * Pages collection
  85. *
  86. * @todo implement it as a class, which supports ArrayAccess and Iterator interfaces,
  87. * to provide incremental parsing and pages tree updating.
  88. * That will give good performance and memory (PDF size) benefits.
  89. *
  90. * @var array - array of Zend_Pdf_Page object
  91. */
  92. public $pages = array();
  93. /**
  94. * Document properties
  95. *
  96. * It's an associative array with PDF meta information, values may
  97. * be string, boolean or float.
  98. * Returned array could be used directly to access, add, modify or remove
  99. * document properties.
  100. *
  101. * Standard document properties: Title (must be set for PDF/X documents), Author,
  102. * Subject, Keywords (comma separated list), Creator (the name of the application,
  103. * that created document, if it was converted from other format), Trapped (must be
  104. * true, false or null, can not be null for PDF/X documents)
  105. *
  106. * @var array
  107. */
  108. public $properties = array();
  109. /**
  110. * Original properties set.
  111. *
  112. * Used for tracking properties changes
  113. *
  114. * @var array
  115. */
  116. protected $_originalProperties = array();
  117. /**
  118. * Document level javascript
  119. *
  120. * @var string
  121. */
  122. protected $_javaScript = null;
  123. /**
  124. * Document named actions
  125. * "GoTo..." actions, used to refer document parts
  126. * from outside PDF
  127. *
  128. * @var array - array of Zend_Pdf_Action objects
  129. */
  130. protected $_namedActions = array();
  131. /**
  132. * Pdf trailer (last or just created)
  133. *
  134. * @var Zend_Pdf_Trailer
  135. */
  136. protected $_trailer = null;
  137. /**
  138. * PDF objects factory.
  139. *
  140. * @var Zend_Pdf_ElementFactory_Interface
  141. */
  142. protected $_objFactory = null;
  143. /**
  144. * Memory manager for stream objects
  145. *
  146. * @var Zend_Memory_Manager|null
  147. */
  148. protected static $_memoryManager = null;
  149. /**
  150. * Pdf file parser.
  151. * It's not used, but has to be destroyed only with Zend_Pdf object
  152. *
  153. * @var Zend_Pdf_Parser
  154. */
  155. protected $_parser;
  156. /**
  157. * List of inheritable attributesfor pages tree
  158. *
  159. * @var array
  160. */
  161. protected static $_inheritableAttributes = array('Resources', 'MediaBox', 'CropBox', 'Rotate');
  162. /**
  163. * Request used memory manager
  164. *
  165. * @return Zend_Memory_Manager
  166. */
  167. static public function getMemoryManager()
  168. {
  169. if (self::$_memoryManager === null) {
  170. self::$_memoryManager = Zend_Memory::factory('none');
  171. }
  172. return self::$_memoryManager;
  173. }
  174. /**
  175. * Set user defined memory manager
  176. *
  177. * @param Zend_Memory_Manager $memoryManager
  178. */
  179. static public function setMemoryManager(Zend_Memory_Manager $memoryManager)
  180. {
  181. self::$_memoryManager = $memoryManager;
  182. }
  183. /**
  184. * Create new PDF document from a $source string
  185. *
  186. * @param string $source
  187. * @param integer $revision
  188. * @return Zend_Pdf
  189. */
  190. public static function parse(&$source = null, $revision = null)
  191. {
  192. return new Zend_Pdf($source, $revision);
  193. }
  194. /**
  195. * Load PDF document from a file
  196. *
  197. * @param string $source
  198. * @param integer $revision
  199. * @return Zend_Pdf
  200. */
  201. public static function load($source = null, $revision = null)
  202. {
  203. return new Zend_Pdf($source, $revision, true);
  204. }
  205. /**
  206. * Render PDF document and save it.
  207. *
  208. * If $updateOnly is true, then it only appends new section to the end of file.
  209. *
  210. * @param string $filename
  211. * @param boolean $updateOnly
  212. * @throws Zend_Pdf_Exception
  213. */
  214. public function save($filename, $updateOnly = false)
  215. {
  216. if (($file = @fopen($filename, $updateOnly ? 'ab':'wb')) === false ) {
  217. require_once 'Zend/Pdf/Exception.php';
  218. throw new Zend_Pdf_Exception( "Can not open '$filename' file for writing." );
  219. }
  220. $this->render($updateOnly, $file);
  221. fclose($file);
  222. }
  223. /**
  224. * Creates or loads PDF document.
  225. *
  226. * If $source is null, then it creates a new document.
  227. *
  228. * If $source is a string and $load is false, then it loads document
  229. * from a binary string.
  230. *
  231. * If $source is a string and $load is true, then it loads document
  232. * from a file.
  233. * $revision used to roll back document to specified version
  234. * (0 - currtent version, 1 - previous version, 2 - ...)
  235. *
  236. * @param string $source - PDF file to load
  237. * @param integer $revision
  238. * @throws Zend_Pdf_Exception
  239. * @return Zend_Pdf
  240. */
  241. public function __construct($source = null, $revision = null, $load = false)
  242. {
  243. $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1);
  244. if ($source !== null) {
  245. $this->_parser = new Zend_Pdf_Parser($source, $this->_objFactory, $load);
  246. $this->_trailer = $this->_parser->getTrailer();
  247. if ($this->_trailer->Encrypt !== null) {
  248. require_once 'Zend/Pdf/Exception.php';
  249. throw new Zend_Pdf_Exception('Encrypted document modification is not supported');
  250. }
  251. if ($revision !== null) {
  252. $this->rollback($revision);
  253. } else {
  254. $this->_loadPages($this->_trailer->Root->Pages);
  255. }
  256. if ($this->_trailer->Info !== null) {
  257. $this->properties = $this->_trailer->Info->toPhp();
  258. if (isset($this->properties['Trapped'])) {
  259. switch ($this->properties['Trapped']) {
  260. case 'True':
  261. $this->properties['Trapped'] = true;
  262. break;
  263. case 'False':
  264. $this->properties['Trapped'] = false;
  265. break;
  266. case 'Unknown':
  267. $this->properties['Trapped'] = null;
  268. break;
  269. default:
  270. // Wrong property value
  271. // Do nothing
  272. break;
  273. }
  274. }
  275. $this->_originalProperties = $this->properties;
  276. }
  277. } else {
  278. $trailerDictionary = new Zend_Pdf_Element_Dictionary();
  279. /**
  280. * Document id
  281. */
  282. $docId = md5(uniqid(rand(), true)); // 32 byte (128 bit) identifier
  283. $docIdLow = substr($docId, 0, 16); // first 16 bytes
  284. $docIdHigh = substr($docId, 16, 16); // second 16 bytes
  285. $trailerDictionary->ID = new Zend_Pdf_Element_Array();
  286. $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdLow);
  287. $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdHigh);
  288. $trailerDictionary->Size = new Zend_Pdf_Element_Numeric(0);
  289. $this->_trailer = new Zend_Pdf_Trailer_Generator($trailerDictionary);
  290. /**
  291. * Document catalog indirect object.
  292. */
  293. $docCatalog = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  294. $docCatalog->Type = new Zend_Pdf_Element_Name('Catalog');
  295. $docCatalog->Version = new Zend_Pdf_Element_Name(Zend_Pdf::PDF_VERSION);
  296. $this->_trailer->Root = $docCatalog;
  297. /**
  298. * Pages container
  299. */
  300. $docPages = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  301. $docPages->Type = new Zend_Pdf_Element_Name('Pages');
  302. $docPages->Kids = new Zend_Pdf_Element_Array();
  303. $docPages->Count = new Zend_Pdf_Element_Numeric(0);
  304. $docCatalog->Pages = $docPages;
  305. }
  306. }
  307. /**
  308. * Retrive number of revisions.
  309. *
  310. * @return integer
  311. */
  312. public function revisions()
  313. {
  314. $revisions = 1;
  315. $currentTrailer = $this->_trailer;
  316. while ($currentTrailer->getPrev() !== null && $currentTrailer->getPrev()->Root !== null ) {
  317. $revisions++;
  318. $currentTrailer = $currentTrailer->getPrev();
  319. }
  320. return $revisions++;
  321. }
  322. /**
  323. * Rollback document $steps number of revisions.
  324. * This method must be invoked before any changes, applied to the document.
  325. * Otherwise behavior is undefined.
  326. *
  327. * @param integer $steps
  328. */
  329. public function rollback($steps)
  330. {
  331. for ($count = 0; $count < $steps; $count++) {
  332. if ($this->_trailer->getPrev() !== null && $this->_trailer->getPrev()->Root !== null) {
  333. $this->_trailer = $this->_trailer->getPrev();
  334. } else {
  335. break;
  336. }
  337. }
  338. $this->_objFactory->setObjectCount($this->_trailer->Size->value);
  339. // Mark content as modified to force new trailer generation at render time
  340. $this->_trailer->Root->touch();
  341. $this->pages = array();
  342. $this->_loadPages($this->_trailer->Root->Pages);
  343. }
  344. /**
  345. * Load pages recursively
  346. *
  347. * @param Zend_Pdf_Element_Reference $pages
  348. * @param array|null $attributes
  349. */
  350. protected function _loadPages(Zend_Pdf_Element_Reference $pages, $attributes = array())
  351. {
  352. if ($pages->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
  353. require_once 'Zend/Pdf/Exception.php';
  354. throw new Zend_Pdf_Exception('Wrong argument');
  355. }
  356. foreach ($pages->getKeys() as $property) {
  357. if (in_array($property, self::$_inheritableAttributes)) {
  358. $attributes[$property] = $pages->$property;
  359. $pages->$property = null;
  360. }
  361. }
  362. foreach ($pages->Kids->items as $child) {
  363. if ($child->Type->value == 'Pages') {
  364. $this->_loadPages($child, $attributes);
  365. } else if ($child->Type->value == 'Page') {
  366. foreach (self::$_inheritableAttributes as $property) {
  367. if ($child->$property === null && array_key_exists($property, $attributes)) {
  368. /**
  369. * Important note.
  370. * If any attribute or dependant object is an indirect object, then it's still
  371. * shared between pages.
  372. */
  373. if ($attributes[$property] instanceof Zend_Pdf_Element_Object) {
  374. $child->$property = $attributes[$property];
  375. } else {
  376. $child->$property = $this->_objFactory->newObject($attributes[$property]);
  377. }
  378. }
  379. }
  380. $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory);
  381. }
  382. }
  383. }
  384. /**
  385. * Orginize pages to tha pages tree structure.
  386. *
  387. * @todo atomatically attach page to the document, if it's not done yet.
  388. * @todo check, that page is attached to the current document
  389. *
  390. * @todo Dump pages as a balanced tree instead of a plain set.
  391. */
  392. protected function _dumpPages()
  393. {
  394. $pagesContainer = $this->_trailer->Root->Pages;
  395. $pagesContainer->touch();
  396. $pagesContainer->Kids->items->clear();
  397. foreach ($this->pages as $page ) {
  398. $page->render($this->_objFactory);
  399. $pageDictionary = $page->getPageDictionary();
  400. $pageDictionary->touch();
  401. $pageDictionary->Parent = $pagesContainer;
  402. $pagesContainer->Kids->items[] = $pageDictionary;
  403. }
  404. $pagesContainer->Count->touch();
  405. $pagesContainer->Count->value = count($this->pages);
  406. }
  407. /**
  408. * Create page object, attached to the PDF document.
  409. * Method signatures:
  410. *
  411. * 1. Create new page with a specified pagesize.
  412. * If $factory is null then it will be created and page must be attached to the document to be
  413. * included into output.
  414. * ---------------------------------------------------------
  415. * new Zend_Pdf_Page(string $pagesize);
  416. * ---------------------------------------------------------
  417. *
  418. * 2. Create new page with a specified pagesize (in default user space units).
  419. * If $factory is null then it will be created and page must be attached to the document to be
  420. * included into output.
  421. * ---------------------------------------------------------
  422. * new Zend_Pdf_Page(numeric $width, numeric $height);
  423. * ---------------------------------------------------------
  424. *
  425. * @param mixed $param1
  426. * @param mixed $param2
  427. * @return Zend_Pdf_Page
  428. */
  429. public function newPage($param1, $param2 = null)
  430. {
  431. if ($param2 === null) {
  432. return new Zend_Pdf_Page($param1, $this->_objFactory);
  433. } else {
  434. return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);
  435. }
  436. }
  437. /**
  438. * Return the document-level Metadata
  439. * or null Metadata stream is not presented
  440. *
  441. * @return string
  442. */
  443. public function getMetadata()
  444. {
  445. if ($this->_trailer->Root->Metadata !== null) {
  446. return $this->_trailer->Root->Metadata->value;
  447. } else {
  448. return null;
  449. }
  450. }
  451. /**
  452. * Sets the document-level Metadata (mast be valid XMP document)
  453. *
  454. * @param string $metadata
  455. */
  456. public function setMetadata($metadata)
  457. {
  458. $metadataObject = $this->_objFactory->newStreamObject($metadata);
  459. $metadataObject->dictionary->Type = new Zend_Pdf_Element_Name('Metadata');
  460. $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');
  461. $this->_trailer->Root->Metadata = $metadataObject;
  462. $this->_trailer->Root->touch();
  463. }
  464. /**
  465. * Return the document-level JavaScript
  466. * or null if there is no JavaScript for this document
  467. *
  468. * @return string
  469. */
  470. public function getJavaScript()
  471. {
  472. return $this->_javaScript;
  473. }
  474. /**
  475. * Return an associative array containing all the named actions in the PDF.
  476. * Named actions (it's always "GoTo" actions) can be used to reference from outside
  477. * the PDF, ex: 'http://www.something.com/mydocument.pdf#MyAction'
  478. *
  479. * @return array
  480. */
  481. public function getNamedActions()
  482. {
  483. return $this->_namedActions;
  484. }
  485. /**
  486. * Extract fonts attached to the document
  487. *
  488. * returns array of Zend_Pdf_Resource_Font_Extracted objects
  489. *
  490. * @return array
  491. */
  492. public function extractFonts()
  493. {
  494. $fontResourcesUnique = array();
  495. foreach ($this->pages as $page) {
  496. $pageResources = $page->extractResources();
  497. if ($pageResources->Font === null) {
  498. // Page doesn't contain have any font reference
  499. continue;
  500. }
  501. $fontResources = $pageResources->Font;
  502. foreach ($fontResources->getKeys() as $fontResourceName) {
  503. $fontDictionary = $fontResources->$fontResourceName;
  504. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  505. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  506. // Font dictionary has to be an indirect object or object reference
  507. continue;
  508. }
  509. $fontResourcesUnique[$fontDictionary->toString($this->_objFactory)] = $fontDictionary;
  510. }
  511. }
  512. $fonts = array();
  513. require_once 'Zend/Pdf/Exception.php';
  514. foreach ($fontResourcesUnique as $resourceReference => $fontDictionary) {
  515. try {
  516. // Try to extract font
  517. $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  518. $fonts[$resourceReference] = $extractedFont;
  519. } catch (Zend_Pdf_Exception $e) {
  520. if ($e->getMessage() != 'Unsupported font type.') {
  521. throw $e;
  522. }
  523. }
  524. }
  525. return $fonts;
  526. }
  527. /**
  528. * Extract font attached to the page by specific font name
  529. *
  530. * $fontName should be specified in UTF-8 encoding
  531. *
  532. * @return Zend_Pdf_Resource_Font_Extracted|null
  533. */
  534. public function extractFont($fontName)
  535. {
  536. $fontResourcesUnique = array();
  537. require_once 'Zend/Pdf/Exception.php';
  538. foreach ($this->pages as $page) {
  539. $pageResources = $page->extractResources();
  540. if ($pageResources->Font === null) {
  541. // Page doesn't contain have any font reference
  542. continue;
  543. }
  544. $fontResources = $pageResources->Font;
  545. foreach ($fontResources->getKeys() as $fontResourceName) {
  546. $fontDictionary = $fontResources->$fontResourceName;
  547. if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
  548. $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
  549. // Font dictionary has to be an indirect object or object reference
  550. continue;
  551. }
  552. $resourceReference = $fontDictionary->toString($this->_objFactory);
  553. if (isset($fontResourcesUnique[$resourceReference])) {
  554. continue;
  555. } else {
  556. // Mark resource as processed
  557. $fontResourcesUnique[$resourceReference] = 1;
  558. }
  559. if ($fontDictionary->BaseFont->value != $fontName) {
  560. continue;
  561. }
  562. try {
  563. // Try to extract font
  564. return new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
  565. } catch (Zend_Pdf_Exception $e) {
  566. if ($e->getMessage() != 'Unsupported font type.') {
  567. throw $e;
  568. }
  569. // Continue searhing
  570. }
  571. }
  572. }
  573. return null;
  574. }
  575. /**
  576. * Render the completed PDF to a string.
  577. * If $newSegmentOnly is true, then only appended part of PDF is returned.
  578. *
  579. * @param boolean $newSegmentOnly
  580. * @param resource $outputStream
  581. * @return string
  582. * @throws Zend_Pdf_Exception
  583. */
  584. public function render($newSegmentOnly = false, $outputStream = null)
  585. {
  586. // Save document properties if necessary
  587. if ($this->properties != $this->_originalProperties) {
  588. $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
  589. foreach ($this->properties as $key => $value) {
  590. switch ($key) {
  591. case 'Trapped':
  592. switch ($value) {
  593. case true:
  594. $docInfo->$key = new Zend_Pdf_Element_Name('True');
  595. break;
  596. case false:
  597. $docInfo->$key = new Zend_Pdf_Element_Name('False');
  598. break;
  599. case null:
  600. $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');
  601. break;
  602. default:
  603. require_once 'Zend/Pdf/Exception.php';
  604. throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');
  605. break;
  606. }
  607. case 'CreationDate':
  608. // break intentionally omitted
  609. case 'ModDate':
  610. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  611. break;
  612. case 'Title':
  613. // break intentionally omitted
  614. case 'Author':
  615. // break intentionally omitted
  616. case 'Subject':
  617. // break intentionally omitted
  618. case 'Keywords':
  619. // break intentionally omitted
  620. case 'Creator':
  621. // break intentionally omitted
  622. case 'Producer':
  623. if (extension_loaded('mbstring') === true) {
  624. $detected = mb_detect_encoding($value);
  625. if ($detected !== 'ASCII') {
  626. $value = chr(254) . chr(255) . mb_convert_encoding($value, 'UTF-16', $detected);
  627. }
  628. }
  629. $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
  630. break;
  631. default:
  632. // Set property using PDF type based on PHP type
  633. $docInfo->$key = Zend_Pdf_Element::phpToPdf($value);
  634. break;
  635. }
  636. }
  637. $this->_trailer->Info = $docInfo;
  638. }
  639. $this->_dumpPages();
  640. // Check, that PDF file was modified
  641. // File is always modified by _dumpPages() now, but future implementations may eliminate this.
  642. if (!$this->_objFactory->isModified()) {
  643. if ($newSegmentOnly) {
  644. // Do nothing, return
  645. return '';
  646. }
  647. if ($outputStream === null) {
  648. return $this->_trailer->getPDFString();
  649. } else {
  650. $pdfData = $this->_trailer->getPDFString();
  651. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  652. $pdfData = substr($pdfData, $byteCount);
  653. }
  654. return '';
  655. }
  656. }
  657. // offset (from a start of PDF file) of new PDF file segment
  658. $offset = $this->_trailer->getPDFLength();
  659. // Last Object number in a list of free objects
  660. $lastFreeObject = $this->_trailer->getLastFreeObject();
  661. // Array of cross-reference table subsections
  662. $xrefTable = array();
  663. // Object numbers of first objects in each subsection
  664. $xrefSectionStartNums = array();
  665. // Last cross-reference table subsection
  666. $xrefSection = array();
  667. // Dummy initialization of the first element (specail case - header of linked list of free objects).
  668. $xrefSection[] = 0;
  669. $xrefSectionStartNums[] = 0;
  670. // Object number of last processed PDF object.
  671. // Used to manage cross-reference subsections.
  672. // Initialized by zero (specail case - header of linked list of free objects).
  673. $lastObjNum = 0;
  674. if ($outputStream !== null) {
  675. if (!$newSegmentOnly) {
  676. $pdfData = $this->_trailer->getPDFString();
  677. while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
  678. $pdfData = substr($pdfData, $byteCount);
  679. }
  680. }
  681. } else {
  682. $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());
  683. }
  684. // Iterate objects to create new reference table
  685. foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {
  686. $objNum = $updateInfo->getObjNum();
  687. if ($objNum - $lastObjNum != 1) {
  688. // Save cross-reference table subsection and start new one
  689. $xrefTable[] = $xrefSection;
  690. $xrefSection = array();
  691. $xrefSectionStartNums[] = $objNum;
  692. }
  693. if ($updateInfo->isFree()) {
  694. // Free object cross-reference table entry
  695. $xrefSection[] = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());
  696. $lastFreeObject = $objNum;
  697. } else {
  698. // In-use object cross-reference table entry
  699. $xrefSection[] = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());
  700. $pdfBlock = $updateInfo->getObjectDump();
  701. $offset += strlen($pdfBlock);
  702. if ($outputStream === null) {
  703. $pdfSegmentBlocks[] = $pdfBlock;
  704. } else {
  705. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  706. $pdfBlock = substr($pdfBlock, $byteCount);
  707. }
  708. }
  709. }
  710. $lastObjNum = $objNum;
  711. }
  712. // Save last cross-reference table subsection
  713. $xrefTable[] = $xrefSection;
  714. // Modify first entry (specail case - header of linked list of free objects).
  715. $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);
  716. $xrefTableStr = "xref\n";
  717. foreach ($xrefTable as $sectId => $xrefSection) {
  718. $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));
  719. foreach ($xrefSection as $xrefTableEntry) {
  720. $xrefTableStr .= $xrefTableEntry;
  721. }
  722. }
  723. $this->_trailer->Size->value = $this->_objFactory->getObjectCount();
  724. $pdfBlock = $xrefTableStr
  725. . $this->_trailer->toString()
  726. . "startxref\n" . $offset . "\n"
  727. . "%%EOF\n";
  728. if ($outputStream === null) {
  729. $pdfSegmentBlocks[] = $pdfBlock;
  730. return implode('', $pdfSegmentBlocks);
  731. } else {
  732. while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
  733. $pdfBlock = substr($pdfBlock, $byteCount);
  734. }
  735. return '';
  736. }
  737. }
  738. /**
  739. * Set the document-level JavaScript
  740. *
  741. * @param string $javascript
  742. */
  743. public function setJavaScript($javascript)
  744. {
  745. $this->_javaScript = $javascript;
  746. }
  747. /**
  748. * Convert date to PDF format (it's close to ASN.1 (Abstract Syntax Notation
  749. * One) defined in ISO/IEC 8824).
  750. *
  751. * @todo This really isn't the best location for this method. It should
  752. * probably actually exist as Zend_Pdf_Element_Date or something like that.
  753. *
  754. * @todo Address the following E_STRICT issue:
  755. * PHP Strict Standards: date(): It is not safe to rely on the system's
  756. * timezone settings. Please use the date.timezone setting, the TZ
  757. * environment variable or the date_default_timezone_set() function. In
  758. * case you used any of those methods and you are still getting this
  759. * warning, you most likely misspelled the timezone identifier.
  760. *
  761. * @param integer $timestamp (optional) If omitted, uses the current time.
  762. * @return string
  763. */
  764. public static function pdfDate($timestamp = null)
  765. {
  766. if ($timestamp === null) {
  767. $date = date('\D\:YmdHisO');
  768. } else {
  769. $date = date('\D\:YmdHisO', $timestamp);
  770. }
  771. return substr_replace($date, '\'', -2, 0) . '\'';
  772. }
  773. }