2
0

Pdf.php 29 KB

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