Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Pdf.php
Go to the documentation of this file.
1 <?php
27 #require_once 'Zend/Pdf/Page.php';
28 
30 #require_once 'Zend/Pdf/Style.php';
31 
33 #require_once 'Zend/Pdf/Color/GrayScale.php';
34 
36 #require_once 'Zend/Pdf/Color/Rgb.php';
37 
39 #require_once 'Zend/Pdf/Color/Cmyk.php';
40 
42 #require_once 'Zend/Pdf/Color/Html.php';
43 
45 #require_once 'Zend/Pdf/Image.php';
46 
48 #require_once 'Zend/Pdf/Font.php';
49 
51 #require_once 'Zend/Pdf/Resource/Extractor.php';
52 
54 #require_once 'Zend/Pdf/Canvas.php';
55 
56 
58 #require_once 'Zend/Pdf/Element.php';
59 #require_once 'Zend/Pdf/Element/Array.php';
60 #require_once 'Zend/Pdf/Element/String/Binary.php';
61 #require_once 'Zend/Pdf/Element/Boolean.php';
62 #require_once 'Zend/Pdf/Element/Dictionary.php';
63 #require_once 'Zend/Pdf/Element/Name.php';
64 #require_once 'Zend/Pdf/Element/Null.php';
65 #require_once 'Zend/Pdf/Element/Numeric.php';
66 #require_once 'Zend/Pdf/Element/String.php';
67 
68 
84 class Zend_Pdf
85 {
86  /**** Class Constants ****/
87 
91  const PDF_VERSION = '1.4';
92 
96  const PDF_HEADER = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
97 
104 
114  public $pages = array();
115 
131  public $properties = array();
132 
140  protected $_originalProperties = array();
141 
147  protected $_javaScript = null;
148 
155  protected $_namedTargets = array();
156 
162  public $outlines = array();
163 
170  protected $_originalOutlines = array();
171 
179 
185  protected $_trailer = null;
186 
192  protected $_objFactory = null;
193 
199  protected static $_memoryManager = null;
200 
207  protected $_parser;
208 
214  protected static $_inheritableAttributes = array('Resources', 'MediaBox', 'CropBox', 'Rotate');
215 
221  protected $_formFields = array();
222 
229  protected $_isNewDocument = true;
230 
236  static public function getMemoryManager()
237  {
238  if (self::$_memoryManager === null) {
239  #require_once 'Zend/Memory.php';
240  self::$_memoryManager = Zend_Memory::factory('none');
241  }
242 
243  return self::$_memoryManager;
244  }
245 
251  static public function setMemoryManager(Zend_Memory_Manager $memoryManager)
252  {
253  self::$_memoryManager = $memoryManager;
254  }
255 
256 
264  public static function parse(&$source = null, $revision = null)
265  {
266  return new Zend_Pdf($source, $revision);
267  }
268 
276  public static function load($source = null, $revision = null)
277  {
278  return new Zend_Pdf($source, $revision, true);
279  }
280 
291  public function save($filename, $updateOnly = false)
292  {
293  if (($file = @fopen($filename, $updateOnly ? 'ab':'wb')) === false ) {
294  #require_once 'Zend/Pdf/Exception.php';
295  throw new Zend_Pdf_Exception( "Can not open '$filename' file for writing." );
296  }
297 
298  $this->render($updateOnly, $file);
299 
300  fclose($file);
301  }
302 
322  public function __construct($source = null, $revision = null, $load = false)
323  {
324  #require_once 'Zend/Pdf/ElementFactory.php';
325  $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1);
326 
327  if ($source !== null) {
328  #require_once 'Zend/Pdf/Parser.php';
329  $this->_parser = new Zend_Pdf_Parser($source, $this->_objFactory, $load);
330  $this->_pdfHeaderVersion = $this->_parser->getPDFVersion();
331  $this->_trailer = $this->_parser->getTrailer();
332  if ($this->_trailer->Encrypt !== null) {
333  #require_once 'Zend/Pdf/Exception.php';
334  throw new Zend_Pdf_Exception('Encrypted document modification is not supported');
335  }
336  if ($revision !== null) {
337  $this->rollback($revision);
338  } else {
339  $this->_loadPages($this->_trailer->Root->Pages);
340  }
341 
342  $this->_loadNamedDestinations($this->_trailer->Root, $this->_parser->getPDFVersion());
343  $this->_loadOutlines($this->_trailer->Root);
344  $this->_loadJavaScript($this->_trailer->Root);
345  $this->_loadFormFields($this->_trailer->Root);
346 
347  if ($this->_trailer->Info !== null) {
348  $this->properties = $this->_trailer->Info->toPhp();
349 
350  if (isset($this->properties['Trapped'])) {
351  switch ($this->properties['Trapped']) {
352  case 'True':
353  $this->properties['Trapped'] = true;
354  break;
355 
356  case 'False':
357  $this->properties['Trapped'] = false;
358  break;
359 
360  case 'Unknown':
361  $this->properties['Trapped'] = null;
362  break;
363 
364  default:
365  // Wrong property value
366  // Do nothing
367  break;
368  }
369  }
370 
371  $this->_originalProperties = $this->properties;
372  }
373 
374  $this->_isNewDocument = false;
375  } else {
376  $this->_pdfHeaderVersion = Zend_Pdf::PDF_VERSION;
377 
378  $trailerDictionary = new Zend_Pdf_Element_Dictionary();
379 
383  $docId = md5(uniqid(rand(), true)); // 32 byte (128 bit) identifier
384  $docIdLow = substr($docId, 0, 16); // first 16 bytes
385  $docIdHigh = substr($docId, 16, 16); // second 16 bytes
386 
387  $trailerDictionary->ID = new Zend_Pdf_Element_Array();
388  $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdLow);
389  $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdHigh);
390 
391  $trailerDictionary->Size = new Zend_Pdf_Element_Numeric(0);
392 
393  #require_once 'Zend/Pdf/Trailer/Generator.php';
394  $this->_trailer = new Zend_Pdf_Trailer_Generator($trailerDictionary);
395 
399  $docCatalog = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
400  $docCatalog->Type = new Zend_Pdf_Element_Name('Catalog');
401  $docCatalog->Version = new Zend_Pdf_Element_Name(Zend_Pdf::PDF_VERSION);
402  $this->_trailer->Root = $docCatalog;
403 
407  $docPages = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
408  $docPages->Type = new Zend_Pdf_Element_Name('Pages');
409  $docPages->Kids = new Zend_Pdf_Element_Array();
410  $docPages->Count = new Zend_Pdf_Element_Numeric(0);
411  $docCatalog->Pages = $docPages;
412  }
413  }
414 
420  public function revisions()
421  {
422  $revisions = 1;
423  $currentTrailer = $this->_trailer;
424 
425  while ($currentTrailer->getPrev() !== null && $currentTrailer->getPrev()->Root !== null ) {
426  $revisions++;
427  $currentTrailer = $currentTrailer->getPrev();
428  }
429 
430  return $revisions++;
431  }
432 
440  public function rollback($steps)
441  {
442  for ($count = 0; $count < $steps; $count++) {
443  if ($this->_trailer->getPrev() !== null && $this->_trailer->getPrev()->Root !== null) {
444  $this->_trailer = $this->_trailer->getPrev();
445  } else {
446  break;
447  }
448  }
449  $this->_objFactory->setObjectCount($this->_trailer->Size->value);
450 
451  // Mark content as modified to force new trailer generation at render time
452  $this->_trailer->Root->touch();
453 
454  $this->pages = array();
455  $this->_loadPages($this->_trailer->Root->Pages);
456  }
457 
466  {
467  if ($pages->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
468  #require_once 'Zend/Pdf/Exception.php';
469  throw new Zend_Pdf_Exception('Wrong argument');
470  }
471 
472  foreach ($pages->getKeys() as $property) {
473  if (in_array($property, self::$_inheritableAttributes)) {
474  $attributes[$property] = $pages->$property;
475  $pages->$property = null;
476  }
477  }
478 
479 
480  foreach ($pages->Kids->items as $child) {
481  if ($child->Type->value == 'Pages') {
482  $this->_loadPages($child, $attributes);
483  } else if ($child->Type->value == 'Page') {
484  foreach (self::$_inheritableAttributes as $property) {
485  if ($child->$property === null && array_key_exists($property, $attributes)) {
491  if ($attributes[$property] instanceof Zend_Pdf_Element_Object ||
492  $attributes[$property] instanceof Zend_Pdf_Element_Reference) {
493  $child->$property = $attributes[$property];
494  } else {
495  $child->$property = $this->_objFactory->newObject($attributes[$property]);
496  }
497  }
498  }
499 
500  #require_once 'Zend/Pdf/Page.php';
501  $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory);
502  }
503  }
504  }
505 
513  protected function _loadNamedDestinations(Zend_Pdf_Element_Reference $root, $pdfHeaderVersion)
514  {
515  if ($root->Version !== null && version_compare($root->Version->value, $pdfHeaderVersion, '>')) {
516  $versionIs_1_2_plus = version_compare($root->Version->value, '1.1', '>');
517  } else {
518  $versionIs_1_2_plus = version_compare($pdfHeaderVersion, '1.1', '>');
519  }
520 
521  if ($versionIs_1_2_plus) {
522  // PDF version is 1.2+
523  // Look for Destinations structure at Name dictionary
524  if ($root->Names !== null && $root->Names->Dests !== null) {
525  #require_once 'Zend/Pdf/NameTree.php';
526  #require_once 'Zend/Pdf/Target.php';
527  foreach (new Zend_Pdf_NameTree($root->Names->Dests) as $name => $destination) {
528  $this->_namedTargets[$name] = Zend_Pdf_Target::load($destination);
529  }
530  }
531  } else {
532  // PDF version is 1.1 (or earlier)
533  // Look for Destinations sructure at Dest entry of document catalog
534  if ($root->Dests !== null) {
535  if ($root->Dests->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
536  #require_once 'Zend/Pdf/Exception.php';
537  throw new Zend_Pdf_Exception('Document catalog Dests entry must be a dictionary.');
538  }
539 
540  #require_once 'Zend/Pdf/Target.php';
541  foreach ($root->Dests->getKeys() as $destKey) {
542  $this->_namedTargets[$destKey] = Zend_Pdf_Target::load($root->Dests->$destKey);
543  }
544  }
545  }
546  }
547 
554  protected function _loadOutlines(Zend_Pdf_Element_Reference $root)
555  {
556  if ($root->Outlines === null) {
557  return;
558  }
559 
560  if ($root->Outlines->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
561  #require_once 'Zend/Pdf/Exception.php';
562  throw new Zend_Pdf_Exception('Document catalog Outlines entry must be a dictionary.');
563  }
564 
565  if ($root->Outlines->Type !== null && $root->Outlines->Type->value != 'Outlines') {
566  #require_once 'Zend/Pdf/Exception.php';
567  throw new Zend_Pdf_Exception('Outlines Type entry must be an \'Outlines\' string.');
568  }
569 
570  if ($root->Outlines->First === null) {
571  return;
572  }
573 
574  $outlineDictionary = $root->Outlines->First;
575  $processedDictionaries = new SplObjectStorage();
576  while ($outlineDictionary !== null && !$processedDictionaries->contains($outlineDictionary)) {
577  $processedDictionaries->attach($outlineDictionary);
578 
579  #require_once 'Zend/Pdf/Outline/Loaded.php';
580  $this->outlines[] = new Zend_Pdf_Outline_Loaded($outlineDictionary);
581 
582  $outlineDictionary = $outlineDictionary->Next;
583  }
584 
585  $this->_originalOutlines = $this->outlines;
586 
587  if ($root->Outlines->Count !== null) {
588  $this->_originalOpenOutlinesCount = $root->Outlines->Count->value;
589  }
590  }
591 
599  protected function _loadJavaScript(Zend_Pdf_Element_Reference $root)
600  {
601  if (null === $root->Names || null === $root->Names->JavaScript
602  || null === $root->Names->JavaScript->Names
603  ) {
604  return;
605  }
606 
607  foreach ($root->Names->JavaScript->Names->items as $item) {
608  if ($item instanceof Zend_Pdf_Element_Reference
609  && $item->S->value === 'JavaScript'
610  ) {
611  $this->_javaScript[] = $item->JS->value;
612  }
613  }
614  }
615 
623  protected function _loadFormFields(Zend_Pdf_Element_Reference $root)
624  {
625  if ($root->AcroForm === null || $root->AcroForm->Fields === null) {
626  return;
627  }
628 
629  foreach ($root->AcroForm->Fields->items as $field) {
630  /* We only support fields that are textfields and have a name */
631  if ($field->FT && $field->FT->value == 'Tx' && $field->T
632  && $field->T !== null
633  ) {
634  $this->_formFields[$field->T->value] = $field;
635  }
636  }
637 
638  if (!$root->AcroForm->NeedAppearances
639  || !$root->AcroForm->NeedAppearances->value
640  ) {
641  /* Ask the .pdf viewer to generate its own appearance data, so we do not have to */
642  $root->AcroForm->add(
643  new Zend_Pdf_Element_Name('NeedAppearances'),
644  new Zend_Pdf_Element_Boolean(true)
645  );
646  $root->AcroForm->touch();
647  }
648  }
649 
655  public function getTextFieldNames()
656  {
657  return array_keys($this->_formFields);
658  }
659 
667  public function setTextField($name, $value)
668  {
669  if (!isset($this->_formFields[$name])) {
670  throw new Zend_Pdf_Exception(
671  "Field '$name' does not exist or is not a textfield"
672  );
673  }
674 
676  $field = $this->_formFields[$name];
677  $field->add(
679  );
680  $field->touch();
681  }
682 
690  public function setTextFieldProperties($name, $bitmask)
691  {
692  if (!isset($this->_formFields[$name])) {
693  throw new Zend_Pdf_Exception(
694  "Field '$name' does not exist or is not a textfield"
695  );
696  }
697 
698  $field = $this->_formFields[$name];
699  $field->add(
700  new Zend_Pdf_Element_Name('Ff'),
701  new Zend_Pdf_Element_Numeric($bitmask)
702  );
703  $field->touch();
704  }
705 
712  {
713  $this->setTextFieldProperties($name, self::PDF_FORM_FIELD_READONLY);
714  }
715 
724  protected function _dumpPages()
725  {
726  $root = $this->_trailer->Root;
727  $pagesContainer = $root->Pages;
728 
729  $pagesContainer->touch();
730  $pagesContainer->Kids->items = array();
731 
732  foreach ($this->pages as $page ) {
733  $page->render($this->_objFactory);
734 
735  $pageDictionary = $page->getPageDictionary();
736  $pageDictionary->touch();
737  $pageDictionary->Parent = $pagesContainer;
738 
739  $pagesContainer->Kids->items[] = $pageDictionary;
740  }
741 
742  $this->_refreshPagesHash();
743 
744  $pagesContainer->Count->touch();
745  $pagesContainer->Count->value = count($this->pages);
746 
747 
748  // Refresh named destinations list
749  foreach ($this->_namedTargets as $name => $namedTarget) {
750  if ($namedTarget instanceof Zend_Pdf_Destination_Explicit) {
751  // Named target is an explicit destination
752  if ($this->resolveDestination($namedTarget, false) === null) {
753  unset($this->_namedTargets[$name]);
754  }
755  } else if ($namedTarget instanceof Zend_Pdf_Action) {
756  // Named target is an action
757  if ($this->_cleanUpAction($namedTarget, false) === null) {
758  // Action is a GoTo action with an unresolved destination
759  unset($this->_namedTargets[$name]);
760  }
761  } else {
762  #require_once 'Zend/Pdf/Exception.php';
763  throw new Zend_Pdf_Exception('Wrong type of named targed (\'' . get_class($namedTarget) . '\').');
764  }
765  }
766 
767  // Refresh outlines
768  #require_once 'Zend/Pdf/RecursivelyIteratableObjectsContainer.php';
769  $iterator = new RecursiveIteratorIterator(new Zend_Pdf_RecursivelyIteratableObjectsContainer($this->outlines), RecursiveIteratorIterator::SELF_FIRST);
770  foreach ($iterator as $outline) {
771  $target = $outline->getTarget();
772 
773  if ($target !== null) {
774  if ($target instanceof Zend_Pdf_Destination) {
775  // Outline target is a destination
776  if ($this->resolveDestination($target, false) === null) {
777  $outline->setTarget(null);
778  }
779  } else if ($target instanceof Zend_Pdf_Action) {
780  // Outline target is an action
781  if ($this->_cleanUpAction($target, false) === null) {
782  // Action is a GoTo action with an unresolved destination
783  $outline->setTarget(null);
784  }
785  } else {
786  #require_once 'Zend/Pdf/Exception.php';
787  throw new Zend_Pdf_Exception('Wrong outline target.');
788  }
789  }
790  }
791 
792  $openAction = $this->getOpenAction();
793  if ($openAction !== null) {
794  if ($openAction instanceof Zend_Pdf_Action) {
795  // OpenAction is an action
796  if ($this->_cleanUpAction($openAction, false) === null) {
797  // Action is a GoTo action with an unresolved destination
798  $this->setOpenAction(null);
799  }
800  } else if ($openAction instanceof Zend_Pdf_Destination) {
801  // OpenAction target is a destination
802  if ($this->resolveDestination($openAction, false) === null) {
803  $this->setOpenAction(null);
804  }
805  } else {
806  #require_once 'Zend/Pdf/Exception.php';
807  throw new Zend_Pdf_Exception('OpenAction has to be either PDF Action or Destination.');
808  }
809  }
810  }
811 
817  protected function _dumpNamedDestinations()
818  {
819  ksort($this->_namedTargets, SORT_STRING);
820 
821  $destArrayItems = array();
822  foreach ($this->_namedTargets as $name => $destination) {
823  $destArrayItems[] = new Zend_Pdf_Element_String($name);
824 
825  if ($destination instanceof Zend_Pdf_Target) {
826  $destArrayItems[] = $destination->getResource();
827  } else {
828  #require_once 'Zend/Pdf/Exception.php';
829  throw new Zend_Pdf_Exception('PDF named destinations must be a Zend_Pdf_Target object.');
830  }
831  }
832  $destArray = $this->_objFactory->newObject(new Zend_Pdf_Element_Array($destArrayItems));
833 
834  $DestTree = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
835  $DestTree->Names = $destArray;
836 
837  $root = $this->_trailer->Root;
838 
839  if ($root->Names === null) {
840  $root->touch();
841  $root->Names = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
842  } else {
843  $root->Names->touch();
844  }
845  $root->Names->Dests = $DestTree;
846  }
847 
851  protected function _dumpOutlines()
852  {
853  $root = $this->_trailer->Root;
854 
855  if ($root->Outlines === null) {
856  if (count($this->outlines) == 0) {
857  return;
858  } else {
859  $root->Outlines = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
860  $root->Outlines->Type = new Zend_Pdf_Element_Name('Outlines');
861  $updateOutlinesNavigation = true;
862  }
863  } else {
864  $updateOutlinesNavigation = false;
865  if (count($this->_originalOutlines) != count($this->outlines)) {
866  // If original and current outlines arrays have different size then outlines list was updated
867  $updateOutlinesNavigation = true;
868  } else if ( !(array_keys($this->_originalOutlines) === array_keys($this->outlines)) ) {
869  // If original and current outlines arrays have different keys (with a glance to an order) then outlines list was updated
870  $updateOutlinesNavigation = true;
871  } else {
872  foreach ($this->outlines as $key => $outline) {
873  if ($this->_originalOutlines[$key] !== $outline) {
874  $updateOutlinesNavigation = true;
875  }
876  }
877  }
878  }
879 
880  $lastOutline = null;
881  $openOutlinesCount = 0;
882  if ($updateOutlinesNavigation) {
883  $root->Outlines->touch();
884  $root->Outlines->First = null;
885 
886  foreach ($this->outlines as $outline) {
887  if ($lastOutline === null) {
888  // First pass. Update Outlines dictionary First entry using corresponding value
889  $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines);
890  $root->Outlines->First = $lastOutline;
891  } else {
892  // Update previous outline dictionary Next entry (Prev is updated within dumpOutline() method)
893  $currentOutlineDictionary = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
894  $lastOutline->Next = $currentOutlineDictionary;
895  $lastOutline = $currentOutlineDictionary;
896  }
897  $openOutlinesCount += $outline->openOutlinesCount();
898  }
899 
900  $root->Outlines->Last = $lastOutline;
901  } else {
902  foreach ($this->outlines as $outline) {
903  $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
904  $openOutlinesCount += $outline->openOutlinesCount();
905  }
906  }
907 
908  if ($openOutlinesCount != $this->_originalOpenOutlinesCount) {
909  $root->Outlines->touch;
910  $root->Outlines->Count = new Zend_Pdf_Element_Numeric($openOutlinesCount);
911  }
912  }
913 
936  public function newPage($param1, $param2 = null)
937  {
938  #require_once 'Zend/Pdf/Page.php';
939  if ($param2 === null) {
940  return new Zend_Pdf_Page($param1, $this->_objFactory);
941  } else {
942  return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);
943  }
944  }
945 
952  public function getMetadata()
953  {
954  if ($this->_trailer->Root->Metadata !== null) {
955  return $this->_trailer->Root->Metadata->value;
956  } else {
957  return null;
958  }
959  }
960 
966  public function setMetadata($metadata)
967  {
968  $metadataObject = $this->_objFactory->newStreamObject($metadata);
969  $metadataObject->dictionary->Type = new Zend_Pdf_Element_Name('Metadata');
970  $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');
971 
972  $this->_trailer->Root->Metadata = $metadataObject;
973  $this->_trailer->Root->touch();
974  }
975 
982  public function getJavaScript()
983  {
984  return $this->_javaScript;
985  }
986 
993  public function getOpenAction()
994  {
995  if ($this->_trailer->Root->OpenAction !== null) {
996  #require_once 'Zend/Pdf/Target.php';
997  return Zend_Pdf_Target::load($this->_trailer->Root->OpenAction);
998  } else {
999  return null;
1000  }
1001  }
1002 
1009  public function setOpenAction(Zend_Pdf_Target $openAction = null)
1010  {
1011  $root = $this->_trailer->Root;
1012  $root->touch();
1013 
1014  if ($openAction === null) {
1015  $root->OpenAction = null;
1016  } else {
1017  $root->OpenAction = $openAction->getResource();
1018 
1019  if ($openAction instanceof Zend_Pdf_Action) {
1020  $openAction->dumpAction($this->_objFactory);
1021  }
1022  }
1023 
1024  return $this;
1025  }
1026 
1034  public function getNamedDestinations()
1035  {
1036  return $this->_namedTargets;
1037  }
1038 
1045  public function getNamedDestination($name)
1046  {
1047  if (isset($this->_namedTargets[$name])) {
1048  return $this->_namedTargets[$name];
1049  } else {
1050  return null;
1051  }
1052  }
1053 
1061  public function setNamedDestination($name, $destination = null)
1062  {
1063  if ($destination !== null &&
1064  !$destination instanceof Zend_Pdf_Action_GoTo &&
1065  !$destination instanceof Zend_Pdf_Destination_Explicit) {
1066  #require_once 'Zend/Pdf/Exception.php';
1067  throw new Zend_Pdf_Exception('PDF named destination must refer an explicit destination or a GoTo PDF action.');
1068  }
1069 
1070  if ($destination !== null) {
1071  $this->_namedTargets[$name] = $destination;
1072  } else {
1073  unset($this->_namedTargets[$name]);
1074  }
1075  }
1076 
1083  protected $_pageReferences = null;
1084 
1091  protected $_pageNumbers = null;
1092 
1098  protected function _refreshPagesHash()
1099  {
1100  $this->_pageReferences = array();
1101  $this->_pageNumbers = array();
1102  $count = 1;
1103  foreach ($this->pages as $page) {
1104  $pageDictionaryHashId = spl_object_hash($page->getPageDictionary()->getObject());
1105  $this->_pageReferences[$pageDictionaryHashId] = $page;
1106  $this->_pageNumbers[$count++] = $page;
1107  }
1108 
1109  return $this;
1110  }
1111 
1122  public function resolveDestination(Zend_Pdf_Destination $destination, $refreshPageCollectionHashes = true)
1123  {
1124  if ($this->_pageReferences === null || $refreshPageCollectionHashes) {
1125  $this->_refreshPagesHash();
1126  }
1127 
1128  if ($destination instanceof Zend_Pdf_Destination_Named) {
1129  if (!isset($this->_namedTargets[$destination->getName()])) {
1130  return null;
1131  }
1132  $destination = $this->getNamedDestination($destination->getName());
1133 
1134  if ($destination instanceof Zend_Pdf_Action) {
1135  if (!$destination instanceof Zend_Pdf_Action_GoTo) {
1136  return null;
1137  }
1138  $destination = $destination->getDestination();
1139  }
1140 
1141  if (!$destination instanceof Zend_Pdf_Destination_Explicit) {
1142  #require_once 'Zend/Pdf/Exception.php';
1143  throw new Zend_Pdf_Exception('Named destination target has to be an explicit destination.');
1144  }
1145  }
1146 
1147  // Named target is an explicit destination
1148  $pageElement = $destination->getResource()->items[0];
1149 
1150  if ($pageElement->getType() == Zend_Pdf_Element::TYPE_NUMERIC) {
1151  // Page reference is a PDF number
1152  if (!isset($this->_pageNumbers[$pageElement->value])) {
1153  return null;
1154  }
1155 
1156  return $this->_pageNumbers[$pageElement->value];
1157  }
1158 
1159  // Page reference is a PDF page dictionary reference
1160  $pageDictionaryHashId = spl_object_hash($pageElement->getObject());
1161  if (!isset($this->_pageReferences[$pageDictionaryHashId])) {
1162  return null;
1163  }
1164  return $this->_pageReferences[$pageDictionaryHashId];
1165  }
1166 
1179  protected function _cleanUpAction(Zend_Pdf_Action $action, $refreshPageCollectionHashes = true)
1180  {
1181  if ($this->_pageReferences === null || $refreshPageCollectionHashes) {
1182  $this->_refreshPagesHash();
1183  }
1184 
1185  // Named target is an action
1186  if ($action instanceof Zend_Pdf_Action_GoTo &&
1187  $this->resolveDestination($action->getDestination(), false) === null) {
1188  // Action itself is a GoTo action with an unresolved destination
1189  return null;
1190  }
1191 
1192  // Walk through child actions
1193  $iterator = new RecursiveIteratorIterator($action, RecursiveIteratorIterator::SELF_FIRST);
1194 
1195  $actionsToClean = array();
1196  $deletionCandidateKeys = array();
1197  foreach ($iterator as $chainedAction) {
1198  if ($chainedAction instanceof Zend_Pdf_Action_GoTo &&
1199  $this->resolveDestination($chainedAction->getDestination(), false) === null) {
1200  // Some child action is a GoTo action with an unresolved destination
1201  // Mark it as a candidate for deletion
1202  $actionsToClean[] = $iterator->getSubIterator();
1203  $deletionCandidateKeys[] = $iterator->getSubIterator()->key();
1204  }
1205  }
1206  foreach ($actionsToClean as $id => $action) {
1207  unset($action->next[$deletionCandidateKeys[$id]]);
1208  }
1209 
1210  return $action;
1211  }
1212 
1221  public function extractFonts()
1222  {
1223  $fontResourcesUnique = array();
1224  foreach ($this->pages as $page) {
1225  $pageResources = $page->extractResources();
1226 
1227  if ($pageResources->Font === null) {
1228  // Page doesn't contain have any font reference
1229  continue;
1230  }
1231 
1232  $fontResources = $pageResources->Font;
1233 
1234  foreach ($fontResources->getKeys() as $fontResourceName) {
1235  $fontDictionary = $fontResources->$fontResourceName;
1236 
1237  if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
1238  $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
1239  #require_once 'Zend/Pdf/Exception.php';
1240  throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
1241  }
1242 
1243  $fontResourcesUnique[spl_object_hash($fontDictionary->getObject())] = $fontDictionary;
1244  }
1245  }
1246 
1247  $fonts = array();
1248  #require_once 'Zend/Pdf/Exception.php';
1249  foreach ($fontResourcesUnique as $resourceId => $fontDictionary) {
1250  try {
1251  // Try to extract font
1252  #require_once 'Zend/Pdf/Resource/Font/Extracted.php';
1253  $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
1254 
1255  $fonts[$resourceId] = $extractedFont;
1256  } catch (Zend_Pdf_Exception $e) {
1257  if ($e->getMessage() != 'Unsupported font type.') {
1258  throw $e;
1259  }
1260  }
1261  }
1262 
1263  return $fonts;
1264  }
1265 
1275  public function extractFont($fontName)
1276  {
1277  $fontResourcesUnique = array();
1278  #require_once 'Zend/Pdf/Exception.php';
1279  foreach ($this->pages as $page) {
1280  $pageResources = $page->extractResources();
1281 
1282  if ($pageResources->Font === null) {
1283  // Page doesn't contain have any font reference
1284  continue;
1285  }
1286 
1287  $fontResources = $pageResources->Font;
1288 
1289  foreach ($fontResources->getKeys() as $fontResourceName) {
1290  $fontDictionary = $fontResources->$fontResourceName;
1291 
1292  if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference ||
1293  $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
1294  #require_once 'Zend/Pdf/Exception.php';
1295  throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
1296  }
1297 
1298  $resourceId = spl_object_hash($fontDictionary->getObject());
1299  if (isset($fontResourcesUnique[$resourceId])) {
1300  continue;
1301  } else {
1302  // Mark resource as processed
1303  $fontResourcesUnique[$resourceId] = 1;
1304  }
1305 
1306  if ($fontDictionary->BaseFont->value != $fontName) {
1307  continue;
1308  }
1309 
1310  try {
1311  // Try to extract font
1312  #require_once 'Zend/Pdf/Resource/Font/Extracted.php';
1313  return new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
1314  } catch (Zend_Pdf_Exception $e) {
1315  if ($e->getMessage() != 'Unsupported font type.') {
1316  throw $e;
1317  }
1318  // Continue searhing
1319  }
1320  }
1321  }
1322 
1323  return null;
1324  }
1325 
1336  public function render($newSegmentOnly = false, $outputStream = null)
1337  {
1338  if ($this->_isNewDocument) {
1339  // Drop full document first time even $newSegmentOnly is set to true
1340  $newSegmentOnly = false;
1341  $this->_isNewDocument = false;
1342  }
1343 
1344  // Save document properties if necessary
1345  if ($this->properties != $this->_originalProperties) {
1346  $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
1347 
1348  foreach ($this->properties as $key => $value) {
1349  switch ($key) {
1350  case 'Trapped':
1351  switch ($value) {
1352  case true:
1353  $docInfo->$key = new Zend_Pdf_Element_Name('True');
1354  break;
1355 
1356  case false:
1357  $docInfo->$key = new Zend_Pdf_Element_Name('False');
1358  break;
1359 
1360  case null:
1361  $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');
1362  break;
1363 
1364  default:
1365  #require_once 'Zend/Pdf/Exception.php';
1366  throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');
1367  break;
1368  }
1369 
1370  case 'CreationDate':
1371  // break intentionally omitted
1372  case 'ModDate':
1373  $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
1374  break;
1375 
1376  case 'Title':
1377  // break intentionally omitted
1378  case 'Author':
1379  // break intentionally omitted
1380  case 'Subject':
1381  // break intentionally omitted
1382  case 'Keywords':
1383  // break intentionally omitted
1384  case 'Creator':
1385  // break intentionally omitted
1386  case 'Producer':
1387  if (extension_loaded('mbstring') === true) {
1388  $detected = mb_detect_encoding($value);
1389  if ($detected !== 'ASCII') {
1390  $value = "\xfe\xff" . mb_convert_encoding($value, 'UTF-16', $detected);
1391  }
1392  }
1393  $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
1394  break;
1395 
1396  default:
1397  // Set property using PDF type based on PHP type
1398  $docInfo->$key = Zend_Pdf_Element::phpToPdf($value);
1399  break;
1400  }
1401  }
1402 
1403  $this->_trailer->Info = $docInfo;
1404  }
1405 
1406  $this->_dumpPages();
1407  $this->_dumpNamedDestinations();
1408  $this->_dumpOutlines();
1409 
1410  // Check, that PDF file was modified
1411  // File is always modified by _dumpPages() now, but future implementations may eliminate this.
1412  if (!$this->_objFactory->isModified()) {
1413  if ($newSegmentOnly) {
1414  // Do nothing, return
1415  return '';
1416  }
1417 
1418  if ($outputStream === null) {
1419  return $this->_trailer->getPDFString();
1420  } else {
1421  $pdfData = $this->_trailer->getPDFString();
1422  while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
1423  $pdfData = substr($pdfData, $byteCount);
1424  }
1425 
1426  return '';
1427  }
1428  }
1429 
1430  // offset (from a start of PDF file) of new PDF file segment
1431  $offset = $this->_trailer->getPDFLength();
1432  // Last Object number in a list of free objects
1433  $lastFreeObject = $this->_trailer->getLastFreeObject();
1434 
1435  // Array of cross-reference table subsections
1436  $xrefTable = array();
1437  // Object numbers of first objects in each subsection
1438  $xrefSectionStartNums = array();
1439 
1440  // Last cross-reference table subsection
1441  $xrefSection = array();
1442  // Dummy initialization of the first element (specail case - header of linked list of free objects).
1443  $xrefSection[] = 0;
1444  $xrefSectionStartNums[] = 0;
1445  // Object number of last processed PDF object.
1446  // Used to manage cross-reference subsections.
1447  // Initialized by zero (specail case - header of linked list of free objects).
1448  $lastObjNum = 0;
1449 
1450  if ($outputStream !== null) {
1451  if (!$newSegmentOnly) {
1452  $pdfData = $this->_trailer->getPDFString();
1453  while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
1454  $pdfData = substr($pdfData, $byteCount);
1455  }
1456  }
1457  } else {
1458  $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());
1459  }
1460 
1461  // Iterate objects to create new reference table
1462  foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {
1463  $objNum = $updateInfo->getObjNum();
1464 
1465  if ($objNum - $lastObjNum != 1) {
1466  // Save cross-reference table subsection and start new one
1467  $xrefTable[] = $xrefSection;
1468  $xrefSection = array();
1469  $xrefSectionStartNums[] = $objNum;
1470  }
1471 
1472  if ($updateInfo->isFree()) {
1473  // Free object cross-reference table entry
1474  $xrefSection[] = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());
1475  $lastFreeObject = $objNum;
1476  } else {
1477  // In-use object cross-reference table entry
1478  $xrefSection[] = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());
1479 
1480  $pdfBlock = $updateInfo->getObjectDump();
1481  $offset += strlen($pdfBlock);
1482 
1483  if ($outputStream === null) {
1484  $pdfSegmentBlocks[] = $pdfBlock;
1485  } else {
1486  while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
1487  $pdfBlock = substr($pdfBlock, $byteCount);
1488  }
1489  }
1490  }
1491  $lastObjNum = $objNum;
1492  }
1493  // Save last cross-reference table subsection
1494  $xrefTable[] = $xrefSection;
1495 
1496  // Modify first entry (specail case - header of linked list of free objects).
1497  $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);
1498 
1499  $xrefTableStr = "xref\n";
1500  foreach ($xrefTable as $sectId => $xrefSection) {
1501  $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));
1502  foreach ($xrefSection as $xrefTableEntry) {
1503  $xrefTableStr .= $xrefTableEntry;
1504  }
1505  }
1506 
1507  $this->_trailer->Size->value = $this->_objFactory->getObjectCount();
1508 
1509  $pdfBlock = $xrefTableStr
1510  . $this->_trailer->toString()
1511  . "startxref\n" . $offset . "\n"
1512  . "%%EOF\n";
1513 
1514  $this->_objFactory->cleanEnumerationShiftCache();
1515 
1516  if ($outputStream === null) {
1517  $pdfSegmentBlocks[] = $pdfBlock;
1518 
1519  return implode('', $pdfSegmentBlocks);
1520  } else {
1521  while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
1522  $pdfBlock = substr($pdfBlock, $byteCount);
1523  }
1524 
1525  return '';
1526  }
1527  }
1528 
1536  public function setJavaScript($javaScript)
1537  {
1538  $this->resetJavaScript();
1539 
1540  $this->addJavaScript($javaScript);
1541  }
1542 
1546  public function resetJavaScript()
1547  {
1548  $this->_javaScript = null;
1549 
1550  $root = $this->_trailer->Root;
1551  if (null === $root->Names || null === $root->Names->JavaScript) {
1552  return;
1553  }
1554  $root->Names->JavaScript = null;
1555  }
1556 
1563  public function addJavaScript($javaScript)
1564  {
1565  if (empty($javaScript)) {
1566  throw new Zend_Pdf_Exception(
1567  'JavaScript must be a non empty string or array of strings'
1568  );
1569  }
1570 
1571  if (!is_array($javaScript)) {
1572  $javaScript = array($javaScript);
1573  }
1574 
1575  if (null === $this->_javaScript) {
1576  $this->_javaScript = $javaScript;
1577  } else {
1578  $this->_javaScript = array_merge($this->_javaScript, $javaScript);
1579  }
1580 
1581  if (!empty($this->_javaScript)) {
1582  $items = array();
1583 
1584  foreach ($this->_javaScript as $javaScript) {
1585  $jsCode = array(
1586  'S' => new Zend_Pdf_Element_Name('JavaScript'),
1587  'JS' => new Zend_Pdf_Element_String($javaScript)
1588  );
1589  $items[] = new Zend_Pdf_Element_String('EmbeddedJS');
1590  $items[] = $this->_objFactory->newObject(
1591  new Zend_Pdf_Element_Dictionary($jsCode)
1592  );
1593  }
1594 
1595  $jsRef = $this->_objFactory->newObject(
1596  new Zend_Pdf_Element_Dictionary(
1597  array('Names' => new Zend_Pdf_Element_Array($items))
1598  )
1599  );
1600 
1601  if (null === $this->_trailer->Root->Names) {
1602  $this->_trailer->Root->Names = new Zend_Pdf_Element_Dictionary();
1603  }
1604  $this->_trailer->Root->Names->JavaScript = $jsRef;
1605  }
1606  }
1607 
1625  public static function pdfDate($timestamp = null)
1626  {
1627  if ($timestamp === null) {
1628  $date = date('\D\:YmdHisO');
1629  } else {
1630  $date = date('\D\:YmdHisO', $timestamp);
1631  }
1632  return substr_replace($date, '\'', -2, 0) . '\'';
1633  }
1634 
1635 }
_loadPages(Zend_Pdf_Element_Reference $pages, $attributes=array())
Definition: Pdf.php:465
__construct($source=null, $revision=null, $load=false)
Definition: Pdf.php:322
const PDF_HEADER
Definition: Pdf.php:96
render($newSegmentOnly=false, $outputStream=null)
Definition: Pdf.php:1336
revisions()
Definition: Pdf.php:420
$outlines
Definition: Pdf.php:162
markTextFieldAsReadOnly($name)
Definition: Pdf.php:711
$_isNewDocument
Definition: Pdf.php:229
$source
Definition: source.php:23
_loadFormFields(Zend_Pdf_Element_Reference $root)
Definition: Pdf.php:623
$_originalOpenOutlinesCount
Definition: Pdf.php:178
const PDF_VERSION
Definition: Pdf.php:91
$count
Definition: recent.phtml:13
setTextFieldProperties($name, $bitmask)
Definition: Pdf.php:690
static parse(&$source=null, $revision=null)
Definition: Pdf.php:264
static factory($backend, $backendOptions=array())
Definition: Memory.php:50
const TYPE_DICTIONARY
Definition: Element.php:37
_cleanUpAction(Zend_Pdf_Action $action, $refreshPageCollectionHashes=true)
Definition: Pdf.php:1179
extractFont($fontName)
Definition: Pdf.php:1275
_dumpPages()
Definition: Pdf.php:724
$_originalProperties
Definition: Pdf.php:140
save($filename, $updateOnly=false)
Definition: Pdf.php:291
$_trailer
Definition: Pdf.php:185
static $_inheritableAttributes
Definition: Pdf.php:214
$value
Definition: gender.phtml:16
const PDF_FORM_FIELD_READONLY
Definition: Pdf.php:101
$page
Definition: pages.php:8
static setMemoryManager(Zend_Memory_Manager $memoryManager)
Definition: Pdf.php:251
const PDF_FORM_FIELD_REQUIRED
Definition: Pdf.php:102
$properties
Definition: Pdf.php:131
$_parser
Definition: Pdf.php:207
const PDF_FORM_FIELD_NOEXPORT
Definition: Pdf.php:103
static $_memoryManager
Definition: Pdf.php:199
static getMemoryManager()
Definition: Pdf.php:236
$attributes
Definition: matrix.phtml:13
_loadNamedDestinations(Zend_Pdf_Element_Reference $root, $pdfHeaderVersion)
Definition: Pdf.php:513
_refreshPagesHash()
Definition: Pdf.php:1098
$_formFields
Definition: Pdf.php:221
_loadJavaScript(Zend_Pdf_Element_Reference $root)
Definition: Pdf.php:599
static load(Zend_Pdf_Element $resource)
Definition: Target.php:41
$_namedTargets
Definition: Pdf.php:155
getTextFieldNames()
Definition: Pdf.php:655
static createFactory($objCount)
resolveDestination(Zend_Pdf_Destination $destination, $refreshPageCollectionHashes=true)
Definition: Pdf.php:1122
_loadOutlines(Zend_Pdf_Element_Reference $root)
Definition: Pdf.php:554
$pages
Definition: Pdf.php:114
rollback($steps)
Definition: Pdf.php:440
static load($source=null, $revision=null)
Definition: Pdf.php:276
$_originalOutlines
Definition: Pdf.php:170
$_javaScript
Definition: Pdf.php:147
$_objFactory
Definition: Pdf.php:192
if(!isset($_GET['name'])) $name
Definition: log.php:14