tcpdi_parser.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. <?php
  2. //============================================================+
  3. // File name : tcpdi_parser.php
  4. // Version : 1.0
  5. // Begin : 2013-09-25
  6. // Last Update : 2013-09-25
  7. // Author : Paul Nicholls - https://github.com/pauln
  8. // License : GNU-LGPL v3 (https://www.gnu.org/copyleft/lesser.html)
  9. //
  10. // Based on : tcpdf_parser.php
  11. // Version : 1.0.003
  12. // Begin : 2011-05-23
  13. // Last Update : 2013-03-17
  14. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  15. // License : GNU-LGPL v3 (https://www.gnu.org/copyleft/lesser.html)
  16. // -------------------------------------------------------------------
  17. // Copyright (C) 2011-2013 Nicola Asuni - Tecnick.com LTD
  18. //
  19. // This file is for use with the TCPDF software library.
  20. //
  21. // tcpdi_parser is free software: you can redistribute it and/or modify it
  22. // under the terms of the GNU Lesser General Public License as
  23. // published by the Free Software Foundation, either version 3 of the
  24. // License, or (at your option) any later version.
  25. //
  26. // tcpdi_parser is distributed in the hope that it will be useful, but
  27. // WITHOUT ANY WARRANTY; without even the implied warranty of
  28. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  29. // See the GNU Lesser General Public License for more details.
  30. //
  31. // You should have received a copy of the License
  32. // along with tcpdi_parser. If not, see
  33. // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
  34. //
  35. // See LICENSE file for more information.
  36. // -------------------------------------------------------------------
  37. //
  38. // Description : This is a PHP class for parsing PDF documents.
  39. //
  40. //============================================================+
  41. /**
  42. * @file
  43. * This is a PHP class for parsing PDF documents.<br>
  44. * @author Paul Nicholls
  45. * @author Nicola Asuni
  46. * @version 1.0
  47. */
  48. // include class for decoding filters
  49. if (defined('TCPDF_PATH')) require_once(constant('TCPDF_PATH').'/include/tcpdf_filters.php');
  50. else require_once(dirname(__FILE__).'/../tecnickcom/tcpdf/include/tcpdf_filters.php');
  51. if (!defined ('PDF_TYPE_NULL'))
  52. define ('PDF_TYPE_NULL', 0);
  53. if (!defined ('PDF_TYPE_NUMERIC'))
  54. define ('PDF_TYPE_NUMERIC', 1);
  55. if (!defined ('PDF_TYPE_TOKEN'))
  56. define ('PDF_TYPE_TOKEN', 2);
  57. if (!defined ('PDF_TYPE_HEX'))
  58. define ('PDF_TYPE_HEX', 3);
  59. if (!defined ('PDF_TYPE_STRING'))
  60. define ('PDF_TYPE_STRING', 4);
  61. if (!defined ('PDF_TYPE_DICTIONARY'))
  62. define ('PDF_TYPE_DICTIONARY', 5);
  63. if (!defined ('PDF_TYPE_ARRAY'))
  64. define ('PDF_TYPE_ARRAY', 6);
  65. if (!defined ('PDF_TYPE_OBJDEC'))
  66. define ('PDF_TYPE_OBJDEC', 7);
  67. if (!defined ('PDF_TYPE_OBJREF'))
  68. define ('PDF_TYPE_OBJREF', 8);
  69. if (!defined ('PDF_TYPE_OBJECT'))
  70. define ('PDF_TYPE_OBJECT', 9);
  71. if (!defined ('PDF_TYPE_STREAM'))
  72. define ('PDF_TYPE_STREAM', 10);
  73. if (!defined ('PDF_TYPE_BOOLEAN'))
  74. define ('PDF_TYPE_BOOLEAN', 11);
  75. if (!defined ('PDF_TYPE_REAL'))
  76. define ('PDF_TYPE_REAL', 12);
  77. /**
  78. * @class tcpdi_parser
  79. * This is a PHP class for parsing PDF documents.<br>
  80. * Based on TCPDF_PARSER, part of the TCPDF project by Nicola Asuni.
  81. * @brief This is a PHP class for parsing PDF documents..
  82. * @version 1.0
  83. * @author Paul Nicholls - github.com/pauln
  84. * @author Nicola Asuni - info@tecnick.com
  85. */
  86. class tcpdi_parser {
  87. /**
  88. * Unique parser ID
  89. * @public
  90. */
  91. public $uniqueid = '';
  92. /**
  93. * Raw content of the PDF document.
  94. * @private
  95. */
  96. private $pdfdata = '';
  97. /**
  98. * XREF data.
  99. * @protected
  100. */
  101. public $xref = array();
  102. /**
  103. * Object streams.
  104. * @protected
  105. */
  106. protected $objstreams = array();
  107. /**
  108. * Objects in objstreams.
  109. * @protected
  110. */
  111. protected $objstreamobjs = array();
  112. /**
  113. * List of seen XREF data locations.
  114. * @protected
  115. */
  116. protected $xref_seen_offsets = array();
  117. /**
  118. * Array of PDF objects.
  119. * @protected
  120. */
  121. protected $objects = array();
  122. /**
  123. * Array of object offsets.
  124. * @private
  125. */
  126. private $objoffsets = array();
  127. /**
  128. * Class object for decoding filters.
  129. * @private
  130. */
  131. private $FilterDecoders;
  132. /**
  133. * Pages
  134. *
  135. * @private array
  136. */
  137. public $pages;
  138. /**
  139. * Page count
  140. * @private integer
  141. */
  142. private $page_count;
  143. /**
  144. * actual page number
  145. * @private integer
  146. */
  147. private $pageno;
  148. /**
  149. * PDF version of the loaded document
  150. * @private string
  151. */
  152. private $pdfVersion;
  153. /**
  154. * Available BoxTypes
  155. *
  156. * @public array
  157. */
  158. public $availableBoxes = array('/MediaBox', '/CropBox', '/BleedBox', '/TrimBox', '/ArtBox');
  159. // -----------------------------------------------------------------------------
  160. /**
  161. * Parse a PDF document an return an array of objects.
  162. * @param $data (string) PDF data to parse.
  163. * @public
  164. * @since 1.0.000 (2011-05-24)
  165. */
  166. public function __construct($data, $uniqueid) {
  167. if (empty($data)) {
  168. $this->Error('Empty PDF data.');
  169. }
  170. $this->uniqueid = $uniqueid;
  171. $this->pdfdata = $data;
  172. // get length
  173. $pdflen = strlen($this->pdfdata);
  174. // initialize class for decoding filters
  175. $this->FilterDecoders = new TCPDF_FILTERS();
  176. // get xref and trailer data
  177. $this->xref = $this->getXrefData();
  178. $this->findObjectOffsets();
  179. // parse all document objects
  180. $this->objects = array();
  181. /*foreach ($this->xref['xref'] as $obj => $offset) {
  182. if (!isset($this->objects[$obj]) AND ($offset > 0)) {
  183. // decode only objects with positive offset
  184. //$this->objects[$obj] = $this->getIndirectObject($obj, $offset, true);
  185. }
  186. }*/
  187. $this->getPDFVersion();
  188. $this->readPages();
  189. }
  190. /**
  191. * Clean up when done, to free memory etc
  192. */
  193. public function cleanUp() {
  194. unset($this->pdfdata);
  195. $this->pdfdata = '';
  196. unset($this->objstreams);
  197. $this->objstreams = array();
  198. unset($this->objects);
  199. $this->objects = array();
  200. unset($this->objstreamobjs);
  201. $this->objstreamobjs = array();
  202. unset($this->xref);
  203. $this->xref = array();
  204. unset($this->objoffsets);
  205. $this->objoffsets = array();
  206. unset($this->pages);
  207. $this->pages = array();
  208. }
  209. /**
  210. * Return an array of parsed PDF document objects.
  211. * @return (array) Array of parsed PDF document objects.
  212. * @public
  213. * @since 1.0.000 (2011-06-26)
  214. */
  215. public function getParsedData() {
  216. return array($this->xref, $this->objects, $this->pages);
  217. }
  218. /**
  219. * Get PDF-Version
  220. *
  221. * And reset the PDF Version used in FPDI if needed
  222. * @public
  223. */
  224. public function getPDFVersion() {
  225. preg_match('/\d\.\d/', substr($this->pdfdata, 0, 16), $m);
  226. if (isset($m[0]))
  227. $this->pdfVersion = $m[0];
  228. return $this->pdfVersion;
  229. }
  230. /**
  231. * Read all /Page(es)
  232. *
  233. */
  234. function readPages() {
  235. $params = $this->getObjectVal($this->xref['trailer'][1]['/Root']);
  236. $objref = null;
  237. foreach ($params[1][1] as $k=>$v) {
  238. if ($k == '/Pages') {
  239. $objref = $v;
  240. break;
  241. }
  242. }
  243. if ($objref == null || $objref[0] !== PDF_TYPE_OBJREF) {
  244. // Offset not found.
  245. return;
  246. }
  247. $dict = $this->getObjectVal($objref);
  248. if ($dict[0] == PDF_TYPE_OBJECT && $dict[1][0] == PDF_TYPE_DICTIONARY) {
  249. // Dict wrapped in an object
  250. $dict = $dict[1];
  251. }
  252. if ($dict[0] !== PDF_TYPE_DICTIONARY) {
  253. return;
  254. }
  255. $this->pages = array();
  256. if (isset($dict[1]['/Kids'])) {
  257. $v = $dict[1]['/Kids'];
  258. if ($v[0] == PDF_TYPE_ARRAY) {
  259. foreach ($v[1] as $ref) {
  260. $page = $this->getObjectVal($ref);
  261. $this->readPage($page);
  262. }
  263. }
  264. }
  265. $this->page_count = count($this->pages);
  266. }
  267. /**
  268. * Read a single /Page element, recursing through /Kids if necessary
  269. *
  270. */
  271. private function readPage($page) {
  272. if (isset($page[1][1]['/Kids'])) {
  273. // Nested pages!
  274. foreach ($page[1][1]['/Kids'][1] as $subref) {
  275. $subpage = $this->getObjectVal($subref);
  276. $this->readPage($subpage);
  277. }
  278. } else {
  279. $this->pages[] = $page;
  280. }
  281. }
  282. /**
  283. * Get pagecount from sourcefile
  284. *
  285. * @return int
  286. */
  287. function getPageCount() {
  288. return $this->page_count;
  289. }
  290. /**
  291. * Get Cross-Reference (xref) table and trailer data from PDF document data.
  292. * @param $offset (int) xref offset (if know).
  293. * @param $xref (array) previous xref array (if any).
  294. * @return Array containing xref and trailer data.
  295. * @protected
  296. * @since 1.0.000 (2011-05-24)
  297. */
  298. protected function getXrefData($offset=0, $xref=array()) {
  299. if ($offset == 0) {
  300. // find last startxref
  301. if (preg_match('/.*[\r\n]startxref[\s]*[\r\n]+([0-9]+)[\s]*[\r\n]+%%EOF/is', $this->pdfdata, $matches) == 0) {
  302. $this->Error('Unable to find startxref');
  303. }
  304. $startxref = $matches[1];
  305. } else {
  306. if (preg_match('/([0-9]+[\s][0-9]+[\s]obj)/i', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  307. // Cross-Reference Stream object
  308. $startxref = $offset;
  309. } elseif (preg_match('/[\r\n]startxref[\s]*[\r\n]+([0-9]+)[\s]*[\r\n]+%%EOF/i', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  310. // startxref found
  311. $startxref = $matches[1][0];
  312. } else {
  313. $this->Error('Unable to find startxref');
  314. }
  315. }
  316. unset($matches);
  317. // DOMPDF gets the startxref wrong, giving us the linebreak before the xref starts.
  318. $startxref += strspn($this->pdfdata, "\r\n", $startxref);
  319. // check xref position
  320. if (strpos($this->pdfdata, 'xref', $startxref) == $startxref) {
  321. // Cross-Reference
  322. $xref = $this->decodeXref($startxref, $xref);
  323. } else {
  324. // Cross-Reference Stream
  325. $xref = $this->decodeXrefStream($startxref, $xref);
  326. }
  327. if (empty($xref)) {
  328. $this->Error('Unable to find xref');
  329. }
  330. return $xref;
  331. }
  332. /**
  333. * Decode the Cross-Reference section
  334. * @param $startxref (int) Offset at which the xref section starts.
  335. * @param $xref (array) Previous xref array (if any).
  336. * @return Array containing xref and trailer data.
  337. * @protected
  338. * @since 1.0.000 (2011-06-20)
  339. */
  340. protected function decodeXref($startxref, $xref=array()) {
  341. $this->xref_seen_offsets[] = $startxref;
  342. if (!isset($xref['xref_location'])) {
  343. $xref['xref_location'] = $startxref;
  344. $xref['max_object'] = 0;
  345. }
  346. // extract xref data (object indexes and offsets)
  347. $xoffset = $startxref + 5;
  348. // initialize object number
  349. $obj_num = 0;
  350. $offset = $xoffset;
  351. while (preg_match('/^([0-9]+)[\s]([0-9]+)[\s]?([nf]?)/im', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
  352. $offset = (strlen($matches[0][0]) + $matches[0][1]);
  353. if ($matches[3][0] == 'n') {
  354. // create unique object index: [object number]_[generation number]
  355. $gen_num = intval($matches[2][0]);
  356. $index = $obj_num.'_'.$gen_num;
  357. // check if object already exist
  358. if (!isset($xref['xref'][$obj_num][$gen_num])) {
  359. // store object offset position
  360. $xref['xref'][$obj_num][$gen_num] = intval($matches[1][0]);
  361. }
  362. ++$obj_num;
  363. $offset += 2;
  364. } elseif ($matches[3][0] == 'f') {
  365. ++$obj_num;
  366. $offset += 2;
  367. } else {
  368. // object number (index)
  369. $obj_num = intval($matches[1][0]);
  370. }
  371. }
  372. unset($matches);
  373. $xref['max_object'] = max($xref['max_object'], $obj_num);
  374. // get trailer data
  375. if (preg_match('/trailer[\s]*<<(.*)>>[\s]*[\r\n]+startxref[\s]*[\r\n]+/isU', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $xoffset) > 0) {
  376. $trailer_data = $matches[1][0];
  377. if (!isset($xref['trailer']) OR empty($xref['trailer'])) {
  378. // get only the last updated version
  379. $xref['trailer'] = array();
  380. $xref['trailer'][0] = PDF_TYPE_DICTIONARY;
  381. $xref['trailer'][1] = array();
  382. // parse trailer_data
  383. if (preg_match('/Size[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) {
  384. $xref['trailer'][1]['/Size'] = array(PDF_TYPE_NUMERIC, intval($matches[1]));
  385. }
  386. if (preg_match('/Root[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
  387. $xref['trailer'][1]['/Root'] = array(PDF_TYPE_OBJREF, intval($matches[1]), intval($matches[2]));
  388. }
  389. if (preg_match('/Encrypt[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
  390. $xref['trailer'][1]['/Encrypt'] = array(PDF_TYPE_OBJREF, intval($matches[1]), intval($matches[2]));
  391. }
  392. if (preg_match('/Info[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
  393. $xref['trailer'][1]['/Info'] = array(PDF_TYPE_OBJREF, intval($matches[1]), intval($matches[2]));
  394. }
  395. if (preg_match('/ID[\s]*[\[][\s]*[<]([^>]*)[>][\s]*[<]([^>]*)[>]/i', $trailer_data, $matches) > 0) {
  396. $xref['trailer'][1]['/ID'] = array(PDF_TYPE_ARRAY, array());
  397. $xref['trailer'][1]['/ID'][1][0] = array(PDF_TYPE_HEX, $matches[1]);
  398. $xref['trailer'][1]['/ID'][1][1] = array(PDF_TYPE_HEX, $matches[2]);
  399. }
  400. }
  401. if (preg_match('/Prev[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) {
  402. // get previous xref
  403. $prevoffset = intval($matches[1]);
  404. if (!in_array($prevoffset, $this->xref_seen_offsets)) {
  405. $this->xref_seen_offsets[] = $prevoffset;
  406. $xref = $this->getXrefData($prevoffset, $xref);
  407. }
  408. }
  409. unset($matches);
  410. } else {
  411. $this->Error('Unable to find trailer');
  412. }
  413. return $xref;
  414. }
  415. /**
  416. * Decode the Cross-Reference Stream section
  417. * @param $startxref (int) Offset at which the xref section starts.
  418. * @param $xref (array) Previous xref array (if any).
  419. * @return Array containing xref and trailer data.
  420. * @protected
  421. * @since 1.0.003 (2013-03-16)
  422. */
  423. protected function decodeXrefStream($startxref, $xref=array()) {
  424. // try to read Cross-Reference Stream
  425. list($xrefobj, $unused) = $this->getRawObject($startxref);
  426. $xrefcrs = $this->getIndirectObject($xrefobj[1], $startxref, true);
  427. if (!isset($xref['xref_location'])) {
  428. $xref['xref_location'] = $startxref;
  429. $xref['max_object'] = 0;
  430. }
  431. if (!isset($xref['xref'])) {
  432. $xref['xref'] = array();
  433. }
  434. if (!isset($xref['trailer']) OR empty($xref['trailer'])) {
  435. // get only the last updated version
  436. $xref['trailer'] = array();
  437. $xref['trailer'][0] = PDF_TYPE_DICTIONARY;
  438. $xref['trailer'][1] = array();
  439. $filltrailer = true;
  440. } else {
  441. $filltrailer = false;
  442. }
  443. $valid_crs = false;
  444. $sarr = $xrefcrs[0][1];
  445. $keys = array_keys($sarr);
  446. $columns = 1; // Default as per PDF 32000-1:2008.
  447. $predictor = 1; // Default as per PDF 32000-1:2008.
  448. foreach ($keys as $k=>$key) {
  449. $v = $sarr[$key];
  450. if (($key == '/Type') AND ($v[0] == PDF_TYPE_TOKEN AND ($v[1] == 'XRef'))) {
  451. $valid_crs = true;
  452. } elseif (($key == '/Index') AND ($v[0] == PDF_TYPE_ARRAY AND count($v[1]) >= 2)) {
  453. // first object number in the subsection
  454. $index_first = intval($v[1][0][1]);
  455. // number of entries in the subsection
  456. $index_entries = intval($v[1][1][1]);
  457. } elseif (($key == '/Prev') AND ($v[0] == PDF_TYPE_NUMERIC)) {
  458. // get previous xref offset
  459. $prevxref = intval($v[1]);
  460. } elseif (($key == '/W') AND ($v[0] == PDF_TYPE_ARRAY)) {
  461. // number of bytes (in the decoded stream) of the corresponding field
  462. $wb = array();
  463. $wb[0] = intval($v[1][0][1]);
  464. $wb[1] = intval($v[1][1][1]);
  465. $wb[2] = intval($v[1][2][1]);
  466. } elseif (($key == '/DecodeParms') AND ($v[0] == PDF_TYPE_DICTIONARY)) {
  467. $decpar = $v[1];
  468. foreach ($decpar as $kdc => $vdc) {
  469. if (($kdc == '/Columns') AND ($vdc[0] == PDF_TYPE_NUMERIC)) {
  470. $columns = intval($vdc[1]);
  471. } elseif (($kdc == '/Predictor') AND ($vdc[0] == PDF_TYPE_NUMERIC)) {
  472. $predictor = intval($vdc[1]);
  473. }
  474. }
  475. } elseif ($filltrailer) {
  476. switch($key) {
  477. case '/Size':
  478. case '/Root':
  479. case '/Info':
  480. case '/ID':
  481. $xref['trailer'][1][$key] = $v;
  482. break;
  483. default:
  484. break;
  485. }
  486. }
  487. }
  488. // decode data
  489. $obj_num = 0;
  490. if ($valid_crs AND isset($xrefcrs[1][3][0])) {
  491. // number of bytes in a row
  492. $rowlen = ($columns + 1);
  493. // convert the stream into an array of integers
  494. $sdata = unpack('C*', $xrefcrs[1][3][0]);
  495. // split the rows
  496. $sdata = array_chunk($sdata, $rowlen);
  497. // initialize decoded array
  498. $ddata = array();
  499. // initialize first row with zeros
  500. $prev_row = array_fill (0, $rowlen, 0);
  501. // for each row apply PNG unpredictor
  502. foreach ($sdata as $k => $row) {
  503. // initialize new row
  504. $ddata[$k] = array();
  505. // get PNG predictor value
  506. if (empty($predictor)) {
  507. $predictor = (10 + $row[0]);
  508. }
  509. // for each byte on the row
  510. for ($i=1; $i<=$columns; ++$i) {
  511. // new index
  512. $j = ($i - 1);
  513. $row_up = $prev_row[$j];
  514. if ($i == 1) {
  515. $row_left = 0;
  516. $row_upleft = 0;
  517. } else {
  518. $row_left = $row[($i - 1)];
  519. $row_upleft = $prev_row[($j - 1)];
  520. }
  521. switch ($predictor) {
  522. case 1: // No prediction (equivalent to PNG None)
  523. case 10: { // PNG prediction (on encoding, PNG None on all rows)
  524. $ddata[$k][$j] = $row[$i];
  525. break;
  526. }
  527. case 11: { // PNG prediction (on encoding, PNG Sub on all rows)
  528. $ddata[$k][$j] = (($row[$i] + $row_left) & 0xff);
  529. break;
  530. }
  531. case 12: { // PNG prediction (on encoding, PNG Up on all rows)
  532. $ddata[$k][$j] = (($row[$i] + $row_up) & 0xff);
  533. break;
  534. }
  535. case 13: { // PNG prediction (on encoding, PNG Average on all rows)
  536. $ddata[$k][$j] = (($row[$i] + (($row_left + $row_up) / 2)) & 0xff);
  537. break;
  538. }
  539. case 14: { // PNG prediction (on encoding, PNG Paeth on all rows)
  540. // initial estimate
  541. $p = ($row_left + $row_up - $row_upleft);
  542. // distances
  543. $pa = abs($p - $row_left);
  544. $pb = abs($p - $row_up);
  545. $pc = abs($p - $row_upleft);
  546. $pmin = min($pa, $pb, $pc);
  547. // return minumum distance
  548. switch ($pmin) {
  549. case $pa: {
  550. $ddata[$k][$j] = (($row[$i] + $row_left) & 0xff);
  551. break;
  552. }
  553. case $pb: {
  554. $ddata[$k][$j] = (($row[$i] + $row_up) & 0xff);
  555. break;
  556. }
  557. case $pc: {
  558. $ddata[$k][$j] = (($row[$i] + $row_upleft) & 0xff);
  559. break;
  560. }
  561. }
  562. break;
  563. }
  564. default: { // PNG prediction (on encoding, PNG optimum)
  565. $this->Error("Unknown PNG predictor $predictor");
  566. break;
  567. }
  568. }
  569. }
  570. $prev_row = $ddata[$k];
  571. } // end for each row
  572. // complete decoding
  573. unset($sdata);
  574. $sdata = array();
  575. // for every row
  576. foreach ($ddata as $k => $row) {
  577. // initialize new row
  578. $sdata[$k] = array(0, 0, 0);
  579. if ($wb[0] == 0) {
  580. // default type field
  581. $sdata[$k][0] = 1;
  582. }
  583. $i = 0; // count bytes on the row
  584. // for every column
  585. for ($c = 0; $c < 3; ++$c) {
  586. // for every byte on the column
  587. for ($b = 0; $b < $wb[$c]; ++$b) {
  588. $sdata[$k][$c] += ($row[$i] << (($wb[$c] - 1 - $b) * 8));
  589. ++$i;
  590. }
  591. }
  592. }
  593. unset($ddata);
  594. // fill xref
  595. if (isset($index_first)) {
  596. $obj_num = $index_first;
  597. } else {
  598. $obj_num = 0;
  599. }
  600. foreach ($sdata as $k => $row) {
  601. switch ($row[0]) {
  602. case 0: { // (f) linked list of free objects
  603. ++$obj_num;
  604. break;
  605. }
  606. case 1: { // (n) objects that are in use but are not compressed
  607. // create unique object index: [object number]_[generation number]
  608. $index = $obj_num.'_'.$row[2];
  609. // check if object already exist
  610. if (!isset($xref['xref'][$obj_num][$row[2]])) {
  611. // store object offset position
  612. $xref['xref'][$obj_num][$row[2]] = $row[1];
  613. }
  614. ++$obj_num;
  615. break;
  616. }
  617. case 2: { // compressed objects
  618. // $row[1] = object number of the object stream in which this object is stored
  619. // $row[2] = index of this object within the object stream
  620. /*$index = $row[1].'_0_'.$row[2];
  621. $xref['xref'][$row[1]][0][$row[2]] = -1;*/
  622. break;
  623. }
  624. default: { // null objects
  625. break;
  626. }
  627. }
  628. }
  629. } // end decoding data
  630. $xref['max_object'] = max($xref['max_object'], $obj_num);
  631. if (isset($prevxref)) {
  632. // get previous xref
  633. $xref = $this->getXrefData($prevxref, $xref);
  634. }
  635. return $xref;
  636. }
  637. /**
  638. * Get raw stream data
  639. * @param $offset (int) Stream offset.
  640. * @param $length (int) Stream length.
  641. * @return string Steam content
  642. * @protected
  643. */
  644. protected function getRawStream($offset, $length) {
  645. $offset += strspn($this->pdfdata, "\x00\x09\x0a\x0c\x0d\x20", $offset);
  646. $offset += 6; // "stream"
  647. $offset += strspn($this->pdfdata, "\r\n", $offset);
  648. $obj = array();
  649. $obj[] = PDF_TYPE_STREAM;
  650. $obj[] = substr($this->pdfdata, $offset, $length);
  651. return array($obj, $offset+$length);
  652. }
  653. /**
  654. * Get object type, raw value and offset to next object
  655. * @param $offset (int) Object offset.
  656. * @return array containing object type, raw value and offset to next object
  657. * @protected
  658. * @since 1.0.000 (2011-06-20)
  659. */
  660. protected function getRawObject($offset=0, $data=null) {
  661. if ($data == null) {
  662. $data =& $this->pdfdata;
  663. }
  664. $objtype = ''; // object type to be returned
  665. $objval = ''; // object value to be returned
  666. // skip initial white space chars: \x00 null (NUL), \x09 horizontal tab (HT), \x0A line feed (LF), \x0C form feed (FF), \x0D carriage return (CR), \x20 space (SP)
  667. while (strspn($data[$offset], "\x00\x09\x0a\x0c\x0d\x20") == 1) {
  668. $offset++;
  669. }
  670. // get first char
  671. $char = $data[$offset];
  672. // get object type
  673. switch ($char) {
  674. case '%': { // \x25 PERCENT SIGN
  675. // skip comment and search for next token
  676. $next = strcspn($data, "\r\n", $offset);
  677. if ($next > 0) {
  678. $offset += $next;
  679. return $this->getRawObject($offset, $data);
  680. }
  681. break;
  682. }
  683. case '/': { // \x2F SOLIDUS
  684. // name object
  685. $objtype = PDF_TYPE_TOKEN;
  686. ++$offset;
  687. $length = strcspn($data, "\x00\x09\x0a\x0c\x0d\x20\x28\x29\x3c\x3e\x5b\x5d\x7b\x7d\x2f\x25", $offset);
  688. $objval = substr($data, $offset, $length);
  689. $offset += $length;
  690. break;
  691. }
  692. case '(': // \x28 LEFT PARENTHESIS
  693. case ')': { // \x29 RIGHT PARENTHESIS
  694. // literal string object
  695. $objtype = PDF_TYPE_STRING;
  696. ++$offset;
  697. $strpos = $offset;
  698. if ($char == '(') {
  699. $open_bracket = 1;
  700. while ($open_bracket > 0) {
  701. if (!isset($data[$strpos])) {
  702. break;
  703. }
  704. $ch = $data[$strpos];
  705. switch ($ch) {
  706. case '\\': { // REVERSE SOLIDUS (5Ch) (Backslash)
  707. // skip next character
  708. ++$strpos;
  709. break;
  710. }
  711. case '(': { // LEFT PARENHESIS (28h)
  712. ++$open_bracket;
  713. break;
  714. }
  715. case ')': { // RIGHT PARENTHESIS (29h)
  716. --$open_bracket;
  717. break;
  718. }
  719. }
  720. ++$strpos;
  721. }
  722. $objval = substr($data, $offset, ($strpos - $offset - 1));
  723. $offset = $strpos;
  724. }
  725. break;
  726. }
  727. case '[': // \x5B LEFT SQUARE BRACKET
  728. case ']': { // \x5D RIGHT SQUARE BRACKET
  729. // array object
  730. $objtype = PDF_TYPE_ARRAY;
  731. ++$offset;
  732. if ($char == '[') {
  733. // get array content
  734. $objval = array();
  735. do {
  736. // get element
  737. list($element, $offset) = $this->getRawObject($offset, $data);
  738. $objval[] = $element;
  739. } while ($element[0] !== ']');
  740. // remove closing delimiter
  741. array_pop($objval);
  742. } else {
  743. $objtype = ']';
  744. }
  745. break;
  746. }
  747. case '<': // \x3C LESS-THAN SIGN
  748. case '>': { // \x3E GREATER-THAN SIGN
  749. if (isset($data[($offset + 1)]) AND ($data[($offset + 1)] == $char)) {
  750. // dictionary object
  751. $objtype = PDF_TYPE_DICTIONARY;
  752. if ($char == '<') {
  753. list ($objval, $offset) = $this->getDictValue($offset, $data);
  754. } else {
  755. $objtype = '>>';
  756. $offset += 2;
  757. }
  758. } else {
  759. // hexadecimal string object
  760. $objtype = PDF_TYPE_HEX;
  761. ++$offset;
  762. // The "Panose" entry in the FontDescriptor Style dict seems to have hex bytes separated by spaces.
  763. if (($char == '<') AND (preg_match('/^([0-9A-Fa-f ]+)[>]/iU', substr($data, $offset), $matches) == 1)) {
  764. $objval = $matches[1];
  765. $offset += strlen($matches[0]);
  766. unset($matches);
  767. }
  768. }
  769. break;
  770. }
  771. default: {
  772. $frag = $data[$offset] . @$data[$offset+1] . @$data[$offset+2] . @$data[$offset+3];
  773. switch ($frag) {
  774. case 'endo':
  775. // indirect object
  776. $objtype = 'endobj';
  777. $offset += 6;
  778. break;
  779. case 'stre':
  780. // Streams should always be indirect objects, and thus processed by getRawStream().
  781. // If we get here, treat it as a null object as something has gone wrong.
  782. case 'null':
  783. // null object
  784. $objtype = PDF_TYPE_NULL;
  785. $offset += 4;
  786. $objval = 'null';
  787. break;
  788. case 'true':
  789. // boolean true object
  790. $objtype = PDF_TYPE_BOOLEAN;
  791. $offset += 4;
  792. $objval = true;
  793. break;
  794. case 'fals':
  795. // boolean false object
  796. $objtype = PDF_TYPE_BOOLEAN;
  797. $offset += 5;
  798. $objval = false;
  799. break;
  800. case 'ends':
  801. // end stream object
  802. $objtype = 'endstream';
  803. $offset += 9;
  804. break;
  805. default:
  806. if (preg_match('/^([0-9]+)[\s]+([0-9]+)[\s]+([Robj]{1,3})/i', substr($data, $offset, 33), $matches) == 1) {
  807. if ($matches[3] == 'R') {
  808. // indirect object reference
  809. $objtype = PDF_TYPE_OBJREF;
  810. $offset += strlen($matches[0]);
  811. $objval = array(intval($matches[1]), intval($matches[2]));
  812. } elseif ($matches[3] == 'obj') {
  813. // object start
  814. $objtype = PDF_TYPE_OBJECT;
  815. $objval = intval($matches[1]).'_'.intval($matches[2]);
  816. $offset += strlen ($matches[0]);
  817. }
  818. } elseif (($numlen = strspn($data, '+-.0123456789', $offset)) > 0) {
  819. // numeric object
  820. $objval = substr($data, $offset, $numlen);
  821. $objtype = (intval($objval) != $objval) ? PDF_TYPE_REAL : PDF_TYPE_NUMERIC;
  822. $offset += $numlen;
  823. }
  824. unset($matches);
  825. break;
  826. }
  827. break;
  828. }
  829. }
  830. $obj = array();
  831. $obj[] = $objtype;
  832. if ($objtype == PDF_TYPE_OBJREF && is_array($objval)) {
  833. foreach ($objval as $val) {
  834. $obj[] = $val;
  835. }
  836. } else {
  837. $obj[] = $objval;
  838. }
  839. return array($obj, $offset);
  840. }
  841. private function getDictValue($offset, &$data) {
  842. $objval = array();
  843. // Extract dict from data.
  844. $i=1;
  845. $dict = '';
  846. $offset += 2;
  847. do {
  848. if ($data[$offset] == '>' && $data[$offset+1] == '>') {
  849. $i--;
  850. $dict .= '>>';
  851. $offset += 2;
  852. } else if ($data[$offset] == '<' && $data[$offset+1] == '<') {
  853. $i++;
  854. $dict .= '<<';
  855. $offset += 2;
  856. } else {
  857. $dict .= $data[$offset];
  858. $offset++;
  859. }
  860. } while ($i>0);
  861. // Now that we have just the dict, parse it.
  862. $dictoffset = 0;
  863. do {
  864. // Get dict element.
  865. list($key, $eloffset) = $this->getRawObject($dictoffset, $dict);
  866. if ($key[0] == '>>') {
  867. break;
  868. }
  869. list($element, $dictoffset) = $this->getRawObject($eloffset, $dict);
  870. $objval['/'.$key[1]] = $element;
  871. unset($key);
  872. unset($element);
  873. } while (true);
  874. return array($objval, $offset);
  875. }
  876. /**
  877. * Get content of indirect object.
  878. * @param $obj_ref (string) Object number and generation number separated by underscore character.
  879. * @param $offset (int) Object offset.
  880. * @param $decoding (boolean) If true decode streams.
  881. * @return array containing object data.
  882. * @protected
  883. * @since 1.0.000 (2011-05-24)
  884. */
  885. protected function getIndirectObject($obj_ref, $offset=0, $decoding=true) {
  886. $obj = explode('_', $obj_ref);
  887. if (($obj === false) OR (count($obj) != 2)) {
  888. $this->Error('Invalid object reference: '.$obj);
  889. return;
  890. }
  891. $objref = $obj[0].' '.$obj[1].' obj';
  892. if (strpos($this->pdfdata, $objref, $offset) != $offset) {
  893. // an indirect reference to an undefined object shall be considered a reference to the null object
  894. return array('null', 'null', $offset);
  895. }
  896. // starting position of object content
  897. $offset += strlen($objref);
  898. // get array of object content
  899. $objdata = array();
  900. $i = 0; // object main index
  901. do {
  902. if (($i > 0) AND (isset($objdata[($i - 1)][0])) AND ($objdata[($i - 1)][0] == PDF_TYPE_DICTIONARY) AND array_key_exists('/Length', $objdata[($i - 1)][1])) {
  903. // Stream - get using /Length in stream's dict
  904. $lengthobj = $objdata[($i-1)][1]['/Length'];
  905. if ($lengthobj[0] === PDF_TYPE_OBJREF) {
  906. $lengthobj = $this->getObjectVal($lengthobj);
  907. if ($lengthobj[0] === PDF_TYPE_OBJECT) {
  908. $lengthobj = $lengthobj[1];
  909. }
  910. }
  911. $streamlength = $lengthobj[1];
  912. list($element, $offset) = $this->getRawStream($offset, $streamlength);
  913. } else {
  914. // get element
  915. list($element, $offset) = $this->getRawObject($offset);
  916. }
  917. // decode stream using stream's dictionary information
  918. if ($decoding AND ($element[0] == PDF_TYPE_STREAM) AND (isset($objdata[($i - 1)][0])) AND ($objdata[($i - 1)][0] == PDF_TYPE_DICTIONARY)) {
  919. $element[3] = $this->decodeStream($objdata[($i - 1)][1], $element[1]);
  920. }
  921. $objdata[$i] = $element;
  922. ++$i;
  923. } while ($element[0] != 'endobj');
  924. // remove closing delimiter
  925. array_pop($objdata);
  926. // return raw object content
  927. return $objdata;
  928. }
  929. /**
  930. * Get the content of object, resolving indect object reference if necessary.
  931. * @param $obj (string) Object value.
  932. * @return array containing object data.
  933. * @public
  934. * @since 1.0.000 (2011-06-26)
  935. */
  936. public function getObjectVal($obj) {
  937. if ($obj[0] == PDF_TYPE_OBJREF) {
  938. if (strpos($obj[1], '_') !== false) {
  939. $key = explode('_', $obj[1]);
  940. } else {
  941. $key = array($obj[1], $obj[2]);
  942. }
  943. $ret = array(0=>PDF_TYPE_OBJECT, 'obj'=>$key[0], 'gen'=>$key[1]);
  944. // reference to indirect object
  945. $object = null;
  946. if (isset($this->objects[$key[0]][$key[1]])) {
  947. // this object has been already parsed
  948. $object = $this->objects[$key[0]][$key[1]];
  949. } elseif (($offset = $this->findObjectOffset($key)) !== false) {
  950. // parse new object
  951. $this->objects[$key[0]][$key[1]] = $this->getIndirectObject($key[0].'_'.$key[1], $offset, false);
  952. $object = $this->objects[$key[0]][$key[1]];
  953. } elseif (($key[1] == 0) && isset($this->objstreamobjs[$key[0]])) {
  954. // Object is in an object stream
  955. $streaminfo = $this->objstreamobjs[$key[0]];
  956. $objs = $streaminfo[0];
  957. if (!isset($this->objstreams[$objs[0]][$objs[1]])) {
  958. // Fetch and decode object stream
  959. $offset = $this->findObjectOffset($objs);;
  960. $objstream = $this->getObjectVal(array(PDF_TYPE_OBJREF, $objs[0], $objs[1]));
  961. $decoded = $this->decodeStream($objstream[1][1], $objstream[2][1]);
  962. $this->objstreams[$objs[0]][$objs[1]] = $decoded[0]; // Store just the data, in case we need more from this objstream
  963. // Free memory
  964. unset($objstream);
  965. unset($decoded);
  966. }
  967. $this->objects[$key[0]][$key[1]] = $this->getRawObject($streaminfo[1], $this->objstreams[$objs[0]][$objs[1]]);
  968. $object = $this->objects[$key[0]][$key[1]];
  969. }
  970. if (!is_null($object)) {
  971. $ret[1] = $object[0];
  972. if (isset($object[1][0]) && $object[1][0] == PDF_TYPE_STREAM) {
  973. $ret[0] = PDF_TYPE_STREAM;
  974. $ret[2] = $object[1];
  975. }
  976. return $ret;
  977. }
  978. }
  979. return $obj;
  980. }
  981. /**
  982. * Extract object stream to find out what it contains.
  983. *
  984. */
  985. function extractObjectStream($key) {
  986. $objref = array(PDF_TYPE_OBJREF, $key[0], $key[1]);
  987. $obj = $this->getObjectVal($objref);
  988. if ($obj[0] !== PDF_TYPE_STREAM || !isset($obj[1][1]['/First'][1])) {
  989. // Not a valid object stream dictionary - skip it.
  990. return;
  991. }
  992. $stream = $this->decodeStream($obj[1][1], $obj[2][1]);// Decode object stream, as we need the first bit
  993. $first = intval($obj[1][1]['/First'][1]);
  994. $ints = explode(' ', substr($stream[0], 0, $first)); // Get list of object / offset pairs
  995. for ($j=1; $j<count($ints); $j++) {
  996. if (($j % 2) == 1) {
  997. $this->objstreamobjs[$ints[$j-1]] = array($key, $ints[$j]+$first);
  998. }
  999. }
  1000. // Free memory - we may not need this at all.
  1001. unset($obj);
  1002. unset($stream);
  1003. }
  1004. /**
  1005. * Find all object offsets. Saves having to scour the file multiple times.
  1006. * @private
  1007. */
  1008. private function findObjectOffsets() {
  1009. $this->objoffsets = array();
  1010. if (preg_match_all('/(*ANYCRLF)^[\s]*([0-9]+)[\s]+([0-9]+)[\s]+obj/im', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE) >= 1) {
  1011. $i = 0;
  1012. foreach($matches[0] as $match) {
  1013. $offset = $match[1] + strspn($match[0], "\x00\x09\x0a\x0c\x0d\x20");
  1014. $this->objoffsets[trim($match[0])] = $offset;
  1015. $dictoffset = $match[1] + strlen($match[0]);
  1016. if (preg_match('|^\s+<<[^>]+/ObjStm|', substr($this->pdfdata, $dictoffset, 256), $objstm) == 1) {
  1017. $this->extractObjectStream(array($matches[1][$i][0], $matches[2][$i][0]));
  1018. }
  1019. $i++;
  1020. }
  1021. }
  1022. unset($matches);
  1023. }
  1024. /**
  1025. * Get offset of an object. Checks xref first, then offsets found by scouring the file.
  1026. * @param $key (array) Object key to find (obj, gen).
  1027. * @return int Offset of the object in $this->pdfdata.
  1028. * @private
  1029. */
  1030. private function findObjectOffset($key) {
  1031. $objref = $key[0].' '.$key[1].' obj';
  1032. if (isset($this->xref['xref'][$key[0]][$key[1]])) {
  1033. $offset = $this->xref['xref'][$key[0]][$key[1]];
  1034. if (strpos($this->pdfdata, $objref, $offset) === $offset) {
  1035. // Offset is in xref table and matches actual position in file
  1036. //echo "Offset in XREF is correct, returning<br>";
  1037. return $this->xref['xref'][$key[0]][$key[1]];
  1038. }
  1039. }
  1040. if (array_key_exists($objref, $this->objoffsets)) {
  1041. //echo "Offset found in internal reftable<br>";
  1042. return $this->objoffsets[$objref];
  1043. }
  1044. return false;
  1045. }
  1046. /**
  1047. * Decode the specified stream.
  1048. * @param $sdic (array) Stream's dictionary array.
  1049. * @param $stream (string) Stream to decode.
  1050. * @return array containing decoded stream data and remaining filters.
  1051. * @protected
  1052. * @since 1.0.000 (2011-06-22)
  1053. */
  1054. protected function decodeStream($sdic, $stream) {
  1055. // get stream lenght and filters
  1056. $slength = strlen($stream);
  1057. if ($slength <= 0) {
  1058. return array('', array());
  1059. }
  1060. $filters = array();
  1061. foreach ($sdic as $k => $v) {
  1062. if ($v[0] == PDF_TYPE_TOKEN) {
  1063. if (($k == '/Length') AND ($v[0] == PDF_TYPE_NUMERIC)) {
  1064. // get declared stream lenght
  1065. $declength = intval($v[1]);
  1066. if ($declength < $slength) {
  1067. $stream = substr($stream, 0, $declength);
  1068. $slength = $declength;
  1069. }
  1070. } elseif ($k == '/Filter') {
  1071. if ($v[0] == PDF_TYPE_TOKEN) {
  1072. // single filter
  1073. $filters[] = $v[1];
  1074. } elseif ($v[0] == PDF_TYPE_ARRAY) {
  1075. // array of filters
  1076. foreach ($v[1] as $flt) {
  1077. if ($flt[0] == PDF_TYPE_TOKEN) {
  1078. $filters[] = $flt[1];
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. }
  1085. // decode the stream
  1086. $remaining_filters = array();
  1087. foreach ($filters as $filter) {
  1088. if (in_array($filter, $this->FilterDecoders->getAvailableFilters())) {
  1089. $stream = $this->FilterDecoders->decodeFilter($filter, $stream);
  1090. } else {
  1091. // add missing filter to array
  1092. $remaining_filters[] = $filter;
  1093. }
  1094. }
  1095. return array($stream, $remaining_filters);
  1096. }
  1097. /**
  1098. * Set pageno
  1099. *
  1100. * @param int $pageno Pagenumber to use
  1101. */
  1102. public function setPageno($pageno) {
  1103. $pageno = ((int) $pageno) - 1;
  1104. if ($pageno < 0 || $pageno >= $this->getPageCount()) {
  1105. $this->error("Pagenumber is wrong! (Requested $pageno, max ".$this->getPageCount().")");
  1106. }
  1107. $this->pageno = $pageno;
  1108. }
  1109. /**
  1110. * Get page-resources from current page
  1111. *
  1112. * @return array
  1113. */
  1114. public function getPageResources() {
  1115. return $this->_getPageResources($this->pages[$this->pageno]);
  1116. }
  1117. /**
  1118. * Get page-resources from /Page
  1119. *
  1120. * @param array $obj Array of pdf-data
  1121. */
  1122. private function _getPageResources ($obj) { // $obj = /Page
  1123. $obj = $this->getObjectVal($obj);
  1124. // If the current object has a resources
  1125. // dictionary associated with it, we use
  1126. // it. Otherwise, we move back to its
  1127. // parent object.
  1128. if (isset ($obj[1][1]['/Resources'])) {
  1129. $res = $obj[1][1]['/Resources'];
  1130. if ($res[0] == PDF_TYPE_OBJECT)
  1131. return $res[1];
  1132. return $res;
  1133. } else {
  1134. if (!isset ($obj[1][1]['/Parent'])) {
  1135. return false;
  1136. } else {
  1137. $res = $this->_getPageResources($obj[1][1]['/Parent']);
  1138. if ($res[0] == PDF_TYPE_OBJECT)
  1139. return $res[1];
  1140. return $res;
  1141. }
  1142. }
  1143. }
  1144. /**
  1145. * Get content of current page
  1146. *
  1147. * If more /Contents is an array, the streams are concated
  1148. *
  1149. * @return string
  1150. */
  1151. public function getContent() {
  1152. $buffer = '';
  1153. if (isset($this->pages[$this->pageno][1][1]['/Contents'])) {
  1154. $contents = $this->_getPageContent($this->pages[$this->pageno][1][1]['/Contents']);
  1155. foreach($contents AS $tmp_content) {
  1156. $buffer .= $this->_rebuildContentStream($tmp_content) . ' ';
  1157. }
  1158. }
  1159. return $buffer;
  1160. }
  1161. /**
  1162. * Resolve all content-objects
  1163. *
  1164. * @param array $content_ref
  1165. * @return array
  1166. */
  1167. private function _getPageContent($content_ref) {
  1168. $contents = array();
  1169. if ($content_ref[0] == PDF_TYPE_OBJREF) {
  1170. $content = $this->getObjectVal($content_ref);
  1171. if ($content[1][0] == PDF_TYPE_ARRAY) {
  1172. $contents = $this->_getPageContent($content[1]);
  1173. } else {
  1174. $contents[] = $content;
  1175. }
  1176. } elseif ($content_ref[0] == PDF_TYPE_ARRAY) {
  1177. foreach ($content_ref[1] AS $tmp_content_ref) {
  1178. $contents = array_merge($contents,$this->_getPageContent($tmp_content_ref));
  1179. }
  1180. }
  1181. return $contents;
  1182. }
  1183. /**
  1184. * Rebuild content-streams
  1185. *
  1186. * @param array $obj
  1187. * @return string
  1188. */
  1189. private function _rebuildContentStream($obj) {
  1190. $filters = array();
  1191. if (isset($obj[1][1]['/Filter'])) {
  1192. $_filter = $obj[1][1]['/Filter'];
  1193. if ($_filter[0] == PDF_TYPE_OBJREF) {
  1194. $tmpFilter = $this->getObjectVal($_filter);
  1195. $_filter = $tmpFilter[1];
  1196. }
  1197. if ($_filter[0] == PDF_TYPE_TOKEN) {
  1198. $filters[] = $_filter;
  1199. } elseif ($_filter[0] == PDF_TYPE_ARRAY) {
  1200. $filters = $_filter[1];
  1201. }
  1202. }
  1203. $stream = $obj[2][1];
  1204. foreach ($filters AS $_filter) {
  1205. $stream = $this->FilterDecoders->decodeFilter($_filter[1], $stream);
  1206. }
  1207. return $stream;
  1208. }
  1209. /**
  1210. * Get a Box from a page
  1211. * Arrayformat is same as used by fpdf_tpl
  1212. *
  1213. * @param array $page a /Page
  1214. * @param string $box_index Type of Box @see $availableBoxes
  1215. * @param float Scale factor from user space units to points
  1216. * @return array
  1217. */
  1218. public function getPageBox($page, $box_index, $k) {
  1219. $page = $this->getObjectVal($page);
  1220. $box = null;
  1221. if (isset($page[1][1][$box_index]))
  1222. $box =& $page[1][1][$box_index];
  1223. if (!is_null($box) && $box[0] == PDF_TYPE_OBJREF) {
  1224. $tmp_box = $this->getObjectVal($box);
  1225. $box = $tmp_box[1];
  1226. }
  1227. if (!is_null($box) && $box[0] == PDF_TYPE_ARRAY) {
  1228. $b =& $box[1];
  1229. return array('x' => $b[0][1] / $k,
  1230. 'y' => $b[1][1] / $k,
  1231. 'w' => abs($b[0][1] - $b[2][1]) / $k,
  1232. 'h' => abs($b[1][1] - $b[3][1]) / $k,
  1233. 'llx' => min($b[0][1], $b[2][1]) / $k,
  1234. 'lly' => min($b[1][1], $b[3][1]) / $k,
  1235. 'urx' => max($b[0][1], $b[2][1]) / $k,
  1236. 'ury' => max($b[1][1], $b[3][1]) / $k,
  1237. );
  1238. } elseif (!isset ($page[1][1]['/Parent'])) {
  1239. return false;
  1240. } else {
  1241. return $this->getPageBox($this->getObjectVal($page[1][1]['/Parent']), $box_index, $k);
  1242. }
  1243. }
  1244. /**
  1245. * Get all page boxes by page no
  1246. *
  1247. * @param int The page number
  1248. * @param float Scale factor from user space units to points
  1249. * @return array
  1250. */
  1251. public function getPageBoxes($pageno, $k) {
  1252. return $this->_getPageBoxes($this->pages[$pageno - 1], $k);
  1253. }
  1254. /**
  1255. * Get all boxes from /Page
  1256. *
  1257. * @param array a /Page
  1258. * @return array
  1259. */
  1260. private function _getPageBoxes($page, $k) {
  1261. $boxes = array();
  1262. foreach($this->availableBoxes AS $box) {
  1263. if ($_box = $this->getPageBox($page, $box, $k)) {
  1264. $boxes[$box] = $_box;
  1265. }
  1266. }
  1267. return $boxes;
  1268. }
  1269. /**
  1270. * Get the page rotation by pageno
  1271. *
  1272. * @param integer $pageno
  1273. * @return array
  1274. */
  1275. public function getPageRotation($pageno) {
  1276. return $this->_getPageRotation($this->pages[$pageno - 1]);
  1277. }
  1278. private function _getPageRotation($obj) { // $obj = /Page
  1279. $obj = $this->getObjectVal($obj);
  1280. if (isset ($obj[1][1]['/Rotate'])) {
  1281. $res = $this->getObjectVal($obj[1][1]['/Rotate']);
  1282. if (isset($res[0]) && $res[0] == PDF_TYPE_OBJECT)
  1283. return $res[1];
  1284. return $res;
  1285. } else {
  1286. if (!isset ($obj[1][1]['/Parent'])) {
  1287. return false;
  1288. } else {
  1289. $res = $this->_getPageRotation($obj[1][1]['/Parent']);
  1290. if (isset($res[0]) && $res[0] == PDF_TYPE_OBJECT)
  1291. return $res[1];
  1292. return $res;
  1293. }
  1294. }
  1295. }
  1296. /**
  1297. * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution.
  1298. * @param $msg (string) The error message
  1299. * @public
  1300. * @since 1.0.000 (2011-05-23)
  1301. */
  1302. public function Error($msg) {
  1303. // exit program and print error
  1304. die('<strong>TCPDF_PARSER ERROR: </strong>'.$msg);
  1305. }
  1306. } // END OF TCPDF_PARSER CLASS
  1307. //============================================================+
  1308. // END OF FILE
  1309. //============================================================+