3 * This file is part of FPDI
6 * @copyright Copyright (c) 2017 Setasign - Jan Slabon (https://www.setasign.com)
7 * @license http://opensource.org/licenses/mit-license The MIT License
28 const TYPE_NUMERIC
= 1;
49 const TYPE_STRING
= 4;
56 const TYPE_DICTIONARY
= 5;
70 const TYPE_OBJDEC
= 7;
77 const TYPE_OBJREF
= 8;
84 const TYPE_OBJECT
= 9;
91 const TYPE_STREAM
= 10;
98 const TYPE_BOOLEAN
= 11;
105 const TYPE_REAL
= 12;
108 * Define the amount of byte in which the initial keyword of a PDF document should be searched.
112 static public $searchForStartxrefLength = 5500;
143 * Data of the Root object
150 * PDF version of the loaded document
154 protected $_pdfVersion;
157 * For reading encrypted documents and xref/object streams are in use
161 protected $_readPlain = true;
164 * The current read object
168 protected $_currentObj;
173 * @param string $filename Source filename
174 * @throws InvalidArgumentException
176 public function __construct($filename)
178 $this->filename
= $filename;
180 $this->_f
= @fopen
($this->filename
, 'rb');
183 throw new InvalidArgumentException(sprintf('Cannot open %s !', $filename));
186 $this->getPdfVersion();
188 if (!class_exists('pdf_context')) {
189 require_once('pdf_context.php');
191 $this->_c
= new pdf_context($this->_f
);
194 $this->_xref
= array();
195 $this->_readXref($this->_xref
, $this->_findXref());
197 // Check for Encryption
198 $this->getEncryption();
207 public function __destruct()
213 * Close the opened file
215 public function closeFile()
217 if (isset($this->_f
) && is_resource($this->_f
)) {
224 * Check Trailer for Encryption
228 public function getEncryption()
230 if (isset($this->_xref
['trailer'][1]['/Encrypt'])) {
231 throw new Exception('File is encrypted!');
240 public function getPdfVersion()
242 if ($this->_pdfVersion
=== null) {
244 preg_match('/\d\.\d/', fread($this->_f
, 16), $m);
246 $this->_pdfVersion
= $m[0];
249 return $this->_pdfVersion
;
253 * Read the /Root dictionary
255 protected function _readRoot()
257 if ($this->_xref
['trailer'][1]['/Root'][0] != self
::TYPE_OBJREF
) {
258 throw new Exception('Wrong Type of Root-Element! Must be an indirect reference');
261 $this->_root
= $this->resolveObject($this->_xref
['trailer'][1]['/Root']);
265 * Find the xref table
270 protected function _findXref()
272 $toRead = self
::$searchForStartxrefLength;
274 $stat = fseek($this->_f
, -$toRead, SEEK_END
);
279 $data = fread($this->_f
, $toRead);
281 $keywordPos = strpos(strrev($data), strrev('startxref'));
282 if (false === $keywordPos) {
283 $keywordPos = strpos(strrev($data), strrev('startref'));
286 if (false === $keywordPos) {
287 throw new Exception('Unable to find "startxref" keyword.');
290 $pos = strlen($data) - $keywordPos;
291 $data = substr($data, $pos);
293 if (!preg_match('/\s*(\d+).*$/s', $data, $matches)) {
294 throw new Exception('Unable to find pointer to xref table.');
297 return (int) $matches[1];
301 * Read the xref table
303 * @param array $result Array of xref table entries
304 * @param integer $offset of xref table
308 protected function _readXref(&$result, $offset)
310 $tempPos = $offset - min(20, $offset);
311 fseek($this->_f
, $tempPos); // set some bytes backwards to fetch corrupted docs
313 $data = fread($this->_f
, 100);
315 $xrefPos = strrpos($data, 'xref');
317 if ($xrefPos === false) {
318 $this->_c
->reset($offset);
319 $xrefStreamObjDec = $this->_readValue($this->_c
);
321 if (is_array($xrefStreamObjDec) && isset($xrefStreamObjDec[0]) && $xrefStreamObjDec[0] == self
::TYPE_OBJDEC
) {
324 'This document (%s) probably uses a compression technique which is not supported by the ' .
325 'free parser shipped with FPDI. (See https://www.setasign.com/fpdi-pdf-parser for more details)',
330 throw new Exception('Unable to find xref table.');
334 if (!isset($result['xrefLocation'])) {
335 $result['xrefLocation'] = $tempPos +
$xrefPos;
336 $result['maxObject'] = 0;
340 $bytesPerCycle = 100;
342 fseek($this->_f
, $tempPos = $tempPos +
$xrefPos +
4); // set the handle directly after the "xref"-keyword
343 $data = fread($this->_f
, $bytesPerCycle);
345 while (($trailerPos = strpos($data, 'trailer', max($bytesPerCycle * $cycles++
, 0))) === false && !feof($this->_f
)) {
346 $data .= fread($this->_f
, $bytesPerCycle);
349 if ($trailerPos === false) {
350 throw new Exception('Trailer keyword not found after xref table');
353 $data = ltrim(substr($data, 0, $trailerPos));
356 $found = preg_match_all("/(\r\n|\n|\r)/", substr($data, 0, 100), $m); // check the first 100 bytes for line breaks
358 throw new Exception('Xref table seems to be corrupted.');
360 $differentLineEndings = count(array_unique($m[0]));
361 if ($differentLineEndings > 1) {
362 $lines = preg_split("/(\r\n|\n|\r)/", $data, -1, PREG_SPLIT_NO_EMPTY
);
364 $lines = explode($m[0][0], $data);
367 $data = $differentLineEndings = $m = null;
368 unset($data, $differentLineEndings, $m);
370 $linesCount = count($lines);
374 for ($i = 0; $i < $linesCount; $i++
) {
375 $line = trim($lines[$i]);
377 $pieces = explode(' ', $line);
381 $start = (int)$pieces[0];
382 $end = $start +
(int)$pieces[1];
383 if ($end > $result['maxObject'])
384 $result['maxObject'] = $end;
387 if (!isset($result['xref'][$start]))
388 $result['xref'][$start] = array();
390 if (!array_key_exists($gen = (int) $pieces[1], $result['xref'][$start])) {
391 $result['xref'][$start][$gen] = $pieces[2] == 'n' ?
(int) $pieces[0] : null;
396 throw new Exception('Unexpected data in xref table');
401 $lines = $pieces = $line = $start = $end = $gen = null;
402 unset($lines, $pieces, $line, $start, $end, $gen);
404 $this->_c
->reset($tempPos +
$trailerPos +
7);
405 $trailer = $this->_readValue($this->_c
);
407 if (!isset($result['trailer'])) {
408 $result['trailer'] = $trailer;
411 if (isset($trailer[1]['/Prev'])) {
412 $this->_readXref($result, $trailer[1]['/Prev'][1]);
424 * @param pdf_context $c
425 * @param string $token A token
429 protected function _readValue(&$c, $token = null)
431 if (is_null($token)) {
432 $token = $this->_readToken($c);
435 if ($token === false) {
441 // This is a hex string.
442 // Read the value, then the terminator
448 $match = strpos($c->buffer
, '>', $pos);
450 // If you can't find it, try
451 // reading more data from the stream
453 if ($match === false) {
454 if (!$c->increaseLength()) {
461 $result = substr($c->buffer
, $c->offset
, $match - $c->offset
);
462 $c->offset
= $match +
1;
464 return array (self
::TYPE_HEX
, $result);
469 // This is a dictionary.
473 // Recurse into this function until we reach
474 // the end of the dictionary.
475 while (($key = $this->_readToken($c)) !== '>>') {
476 if ($key === false) {
480 if (($value = $this->_readValue($c)) === false) {
484 // Catch missing value
485 if ($value[0] == self
::TYPE_TOKEN
&& $value[1] == '>>') {
486 $result[$key] = array(self
::TYPE_NULL
);
490 $result[$key] = $value;
493 return array (self
::TYPE_DICTIONARY
, $result);
500 // Recurse into this function until we reach
501 // the end of the array.
502 while (($token = $this->_readToken($c)) !== ']') {
503 if ($token === false) {
507 if (($value = $this->_readValue($c, $token)) === false) {
514 return array (self
::TYPE_ARRAY
, $result);
522 for (; $openBrackets != 0 && $pos < $c->length
; $pos++
) {
523 switch (ord($c->buffer
[$pos])) {
530 case 0x5C: // backslash
534 } while($openBrackets != 0 && $c->increaseLength());
536 $result = substr($c->buffer
, $c->offset
, $pos - $c->offset
- 1);
539 return array (self
::TYPE_STRING
, $result);
542 $tempPos = $c->getPos() - strlen($c->buffer
);
543 $tempOffset = $c->offset
;
545 $c->reset($startPos = $tempPos +
$tempOffset);
547 // Find the first "newline"
548 while ($c->buffer
[0] !== chr(10) && $c->buffer
[0] !== chr(13)) {
549 $c->reset(++
$startPos);
550 if ($c->ensureContent() === false) {
552 'Unable to parse stream data. No newline followed the stream keyword.'
557 $e = 0; // ensure line breaks in front of the stream
558 if ($c->buffer
[0] == chr(10) ||
$c->buffer
[0] == chr(13))
560 if ($c->buffer
[1] == chr(10) && $c->buffer
[0] != chr(10))
563 if ($this->_currentObj
[1][1]['/Length'][0] == self
::TYPE_OBJREF
) {
564 $tmpLength = $this->resolveObject($this->_currentObj
[1][1]['/Length']);
565 $length = $tmpLength[1][1];
567 $length = $this->_currentObj
[1][1]['/Length'][1];
571 $c->reset($startPos +
$e, $length);
577 $c->reset($startPos +
$e +
$length);
578 $endstream = $this->_readToken($c);
580 if ($endstream != 'endstream') {
581 $c->reset($startPos +
$e +
$length +
9); // 9 = strlen("endstream")
582 // We don't throw an error here because the next
583 // round trip will start at a new offset
586 return array(self
::TYPE_STREAM
, $v);
589 if (is_numeric($token)) {
590 // A numeric token. Make sure that
591 // it is not part of something else.
592 if (($tok2 = $this->_readToken($c)) !== false) {
593 if (is_numeric($tok2)) {
595 // Two numeric tokens in a row.
596 // In this case, we're probably in
597 // front of either an object reference
598 // or an object specification.
599 // Determine the case and return the data
600 if (($tok3 = $this->_readToken($c)) !== false) {
603 return array(self
::TYPE_OBJDEC
, (int)$token, (int)$tok2);
605 return array(self
::TYPE_OBJREF
, (int)$token, (int)$tok2);
607 // If we get to this point, that numeric value up
608 // there was just a numeric value. Push the extra
609 // tokens back into the stack and return the value.
610 array_push($c->stack
, $tok3);
614 array_push($c->stack
, $tok2);
617 if ($token === (string)((int)$token))
618 return array(self
::TYPE_NUMERIC
, (int)$token);
620 return array(self
::TYPE_REAL
, (float)$token);
621 } else if ($token == 'true' ||
$token == 'false') {
622 return array(self
::TYPE_BOOLEAN
, $token == 'true');
623 } else if ($token == 'null') {
624 return array(self
::TYPE_NULL
);
626 // Just a token. Return it.
627 return array(self
::TYPE_TOKEN
, $token);
635 * @param array $objSpec The object-data
636 * @return array|boolean
639 public function resolveObject($objSpec)
643 // Exit if we get invalid data
644 if (!is_array($objSpec)) {
648 if ($objSpec[0] == self
::TYPE_OBJREF
) {
650 // This is a reference, resolve it
651 if (isset($this->_xref
['xref'][$objSpec[1]][$objSpec[2]])) {
653 // Save current file position
654 // This is needed if you want to resolve
655 // references while you're reading another object
656 // (e.g.: if you need to determine the length
659 $oldPos = $c->getPos();
661 // Reposition the file pointer and
662 // load the object header.
664 $c->reset($this->_xref
['xref'][$objSpec[1]][$objSpec[2]]);
666 $header = $this->_readValue($c);
668 if ($header[0] != self
::TYPE_OBJDEC ||
$header[1] != $objSpec[1] ||
$header[2] != $objSpec[2]) {
669 $toSearchFor = $objSpec[1] . ' ' . $objSpec[2] . ' obj';
670 if (preg_match('/' . $toSearchFor . '/', $c->buffer
)) {
671 $c->offset
= strpos($c->buffer
, $toSearchFor) +
strlen($toSearchFor);
676 sprintf("Unable to find object (%s, %s) at expected location.", $objSpec[1], $objSpec[2])
681 // If we're being asked to store all the information
682 // about the object, we add the object ID and generation
683 // number for later use
686 'obj' => $objSpec[1],
690 $this->_currentObj
=& $result;
692 // Now simply read the object data until
693 // we encounter an end-of-object marker
695 $value = $this->_readValue($c);
696 if ($value === false ||
count($result) > 4) {
697 // in this case the parser couldn't find an "endobj" so we break here
701 if ($value[0] == self
::TYPE_TOKEN
&& $value[1] === 'endobj') {
710 if (isset($result[2][0]) && $result[2][0] == self
::TYPE_STREAM
) {
711 $result[0] = self
::TYPE_STREAM
;
716 sprintf("Unable to find object (%s, %s) at expected location.", $objSpec[1], $objSpec[2])
727 * Reads a token from the context
729 * @param pdf_context $c
732 protected function _readToken($c)
734 // If there is a token available
735 // on the stack, pop it out and
738 if (count($c->stack
)) {
739 return array_pop($c->stack
);
742 // Strip away any whitespace
745 if (!$c->ensureContent()) {
748 $c->offset +
= strspn($c->buffer
, "\x20\x0A\x0C\x0D\x09\x00", $c->offset
);
749 } while ($c->offset
>= $c->length
- 1);
751 // Get the first character in the stream
753 $char = $c->buffer
[$c->offset++
];
762 // This is either an array or literal string
763 // delimiter, Return it
770 // This could either be a hex string or
771 // dictionary delimiter. Determine the
772 // appropriate case and return the token
774 if ($c->buffer
[$c->offset
] == $char) {
775 if (!$c->ensureContent()) {
779 return $char . $char;
786 // This is a comment - jump over it!
790 $match = preg_match("/(\r\n|\r|\n)/", $c->buffer
, $m, PREG_OFFSET_CAPTURE
, $pos);
792 if (!$c->increaseLength()) {
799 $c->offset
= $m[0][1] +
strlen($m[0][0]);
801 return $this->_readToken($c);
806 // This is "another" type of token (probably
807 // a dictionary entry or a numeric value)
808 // Find the end and return it.
810 if (!$c->ensureContent()) {
816 // Determine the length of the token
818 $pos = strcspn($c->buffer
, "\x20%[]<>()/\x0A\x0C\x0D\x09\x00", $c->offset
);
820 if ($c->offset +
$pos <= $c->length
- 1) {
823 // If the script reaches this point,
824 // the token may span beyond the end
825 // of the current buffer. Therefore,
826 // we increase the size of the buffer
827 // and try again--just to be safe.
829 $c->increaseLength();
833 $result = substr($c->buffer
, $c->offset
- 1, $pos +
1);
842 * Un-filter a stream object
848 protected function _unFilterStream($obj)
852 if (isset($obj[1][1]['/Filter'])) {
853 $filter = $obj[1][1]['/Filter'];
855 if ($filter[0] == pdf_parser
::TYPE_OBJREF
) {
856 $tmpFilter = $this->resolveObject($filter);
857 $filter = $tmpFilter[1];
860 if ($filter[0] == pdf_parser
::TYPE_TOKEN
) {
861 $filters[] = $filter;
862 } else if ($filter[0] == pdf_parser
::TYPE_ARRAY
) {
863 $filters = $filter[1];
867 $stream = $obj[2][1];
869 foreach ($filters AS $filter) {
870 switch ($filter[1]) {
873 if (function_exists('gzuncompress')) {
875 $stream = (strlen($stream) > 0) ? @gzuncompress
($stream) : '';
878 sprintf('To handle %s filter, please compile php with zlib support.', $filter[1])
882 if ($stream === false) {
884 while ($tries < 8 && ($stream === false ||
strlen($stream) < strlen($oStream))) {
885 $oStream = substr($oStream, 1);
886 $stream = @gzinflate
($oStream);
890 if ($stream === false) {
891 throw new Exception('Error while decompressing stream.');
896 if (!class_exists('FilterLZW')) {
897 require_once('filters/FilterLZW.php');
899 $decoder = new FilterLZW();
900 $stream = $decoder->decode($stream);
902 case '/ASCII85Decode':
903 if (!class_exists('FilterASCII85')) {
904 require_once('filters/FilterASCII85.php');
906 $decoder = new FilterASCII85();
907 $stream = $decoder->decode($stream);
909 case '/ASCIIHexDecode':
910 if (!class_exists('FilterASCIIHexDecode')) {
911 require_once('filters/FilterASCIIHexDecode.php');
913 $decoder = new FilterASCIIHexDecode();
914 $stream = $decoder->decode($stream);
919 throw new Exception(sprintf('Unsupported Filter: %s', $filter[1]));