fpdi.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. //
  3. // FPDI - Version 1.2
  4. //
  5. // Copyright 2004-2007 Setasign - Jan Slabon
  6. //
  7. // Licensed under the Apache License, Version 2.0 (the "License");
  8. // you may not use this file except in compliance with the License.
  9. // You may obtain a copy of the License at
  10. //
  11. // http://www.apache.org/licenses/LICENSE-2.0
  12. //
  13. // Unless required by applicable law or agreed to in writing, software
  14. // distributed under the License is distributed on an "AS IS" BASIS,
  15. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. // See the License for the specific language governing permissions and
  17. // limitations under the License.
  18. //
  19. define('FPDI_VERSION','1.2');
  20. ini_set('auto_detect_line_endings',1); // Strongly required!
  21. require_once("fpdf_tpl.php");
  22. require('fpdi_pdf_parser.php');
  23. require_once("fpdi_pdf_parser.php");
  24. class FPDI extends FPDF_TPL {
  25. /**
  26. * Actual filename
  27. * @var string
  28. */
  29. var $current_filename;
  30. /**
  31. * Parser-Objects
  32. * @var array
  33. */
  34. var $parsers;
  35. /**
  36. * Current parser
  37. * @var object
  38. */
  39. var $current_parser;
  40. /**
  41. * Highest version of imported PDF
  42. * @var double
  43. */
  44. var $importVersion = 1.3;
  45. /**
  46. * object stack
  47. * @var array
  48. */
  49. var $_obj_stack;
  50. /**
  51. * done object stack
  52. * @var array
  53. */
  54. var $_don_obj_stack;
  55. /**
  56. * Current Object Id.
  57. * @var integer
  58. */
  59. var $_current_obj_id;
  60. /**
  61. * The name of the last imported page box
  62. * @var string
  63. */
  64. var $lastUsedPageBox;
  65. /**
  66. * Constructor
  67. * See FPDF-Manual
  68. */
  69. function FPDI($orientation='P',$unit='mm',$format='A4') {
  70. parent::FPDF_TPL($orientation,$unit,$format);
  71. }
  72. /**
  73. * Set a source-file
  74. *
  75. * @param string $filename a valid filename
  76. * @return int number of available pages
  77. */
  78. function setSourceFile($filename) {
  79. $this->current_filename = $filename;
  80. $fn =& $this->current_filename;
  81. if (!isset($this->parsers[$fn]))
  82. $this->parsers[$fn] =& new fpdi_pdf_parser($fn,$this);
  83. $this->current_parser =& $this->parsers[$fn];
  84. return $this->parsers[$fn]->getPageCount();
  85. }
  86. /**
  87. * Import a page
  88. *
  89. * @param int $pageno pagenumber
  90. * @return int Index of imported page - to use with fpdf_tpl::useTemplate()
  91. */
  92. function importPage($pageno, $boxName='/CropBox') {
  93. if ($this->_intpl) {
  94. return $this->error("Please import the desired pages before creating a new template.");
  95. }
  96. $fn =& $this->current_filename;
  97. $parser =& $this->parsers[$fn];
  98. $parser->setPageno($pageno);
  99. $this->tpl++;
  100. $this->tpls[$this->tpl] = array();
  101. $tpl =& $this->tpls[$this->tpl];
  102. $tpl['parser'] =& $parser;
  103. $tpl['resources'] = $parser->getPageResources();
  104. $tpl['buffer'] = $parser->getContent();
  105. if (!in_array($boxName, $parser->availableBoxes))
  106. return $this->Error(sprintf("Unknown box: %s", $boxName));
  107. $pageboxes = $parser->getPageBoxes($pageno);
  108. /**
  109. * MediaBox
  110. * CropBox: Default -> MediaBox
  111. * BleedBox: Default -> CropBox
  112. * TrimBox: Default -> CropBox
  113. * ArtBox: Default -> CropBox
  114. */
  115. if (!isset($pageboxes[$boxName]) && ($boxName == "/BleedBox" || $boxName == "/TrimBox" || $boxName == "/ArtBox"))
  116. $boxName = "/CropBox";
  117. if (!isset($pageboxes[$boxName]) && $boxName == "/CropBox")
  118. $boxName = "/MediaBox";
  119. if (!isset($pageboxes[$boxName]))
  120. return false;
  121. $this->lastUsedPageBox = $boxName;
  122. $box = $pageboxes[$boxName];
  123. $tpl['box'] = $box;
  124. // To build an array that can be used by PDF_TPL::useTemplate()
  125. $this->tpls[$this->tpl] = array_merge($this->tpls[$this->tpl],$box);
  126. // An imported page will start at 0,0 everytime. Translation will be set in _putformxobjects()
  127. $tpl['x'] = 0;
  128. $tpl['y'] = 0;
  129. $page =& $parser->pages[$parser->pageno];
  130. // fix for rotated pages
  131. $rotation = $parser->getPageRotation($pageno);
  132. if (isset($rotation[1]) && ($angle = $rotation[1] % 360) != 0) {
  133. $steps = $angle / 90;
  134. $_w = $tpl['w'];
  135. $_h = $tpl['h'];
  136. $tpl['w'] = $steps % 2 == 0 ? $_w : $_h;
  137. $tpl['h'] = $steps % 2 == 0 ? $_h : $_w;
  138. if ($steps % 2 != 0) {
  139. $x = $y = ($steps == 1 || $steps == -3) ? $tpl['h'] : $tpl['w'];
  140. } else {
  141. $x = $tpl['w'];
  142. $y = $tpl['h'];
  143. }
  144. $cx=($x/2+$tpl['box']['x'])*$this->k;
  145. $cy=($y/2+$tpl['box']['y'])*$this->k;
  146. $angle*=-1;
  147. $angle*=M_PI/180;
  148. $c=cos($angle);
  149. $s=sin($angle);
  150. $tpl['buffer'] = sprintf('q %.5f %.5f %.5f %.5f %.2f %.2f cm 1 0 0 1 %.2f %.2f cm %s Q',$c,$s,-$s,$c,$cx,$cy,-$cx,-$cy, $tpl['buffer']);
  151. }
  152. return $this->tpl;
  153. }
  154. function getLastUsedPageBox() {
  155. return $this->lastUsedPageBox;
  156. }
  157. function useTemplate($tplidx, $_x=null, $_y=null, $_w=0, $_h=0) {
  158. $this->_out('q 0 J 1 w 0 j 0 G'); // reset standard values
  159. $s = parent::useTemplate($tplidx, $_x, $_y, $_w, $_h);
  160. $this->_out('Q');
  161. return $s;
  162. }
  163. /**
  164. * Private method, that rebuilds all needed objects of source files
  165. */
  166. function _putimportedobjects() {
  167. if (is_array($this->parsers) && count($this->parsers) > 0) {
  168. foreach($this->parsers AS $filename => $p) {
  169. $this->current_parser =& $this->parsers[$filename];
  170. if (is_array($this->_obj_stack[$filename])) {
  171. while($n = key($this->_obj_stack[$filename])) {
  172. $nObj = $this->current_parser->pdf_resolve_object($this->current_parser->c,$this->_obj_stack[$filename][$n][1]);
  173. $this->_newobj($this->_obj_stack[$filename][$n][0]);
  174. if ($nObj[0] == PDF_TYPE_STREAM) {
  175. $this->pdf_write_value ($nObj);
  176. } else {
  177. $this->pdf_write_value ($nObj[1]);
  178. }
  179. $this->_out('endobj');
  180. $this->_obj_stack[$filename][$n] = null; // free memory
  181. unset($this->_obj_stack[$filename][$n]);
  182. reset($this->_obj_stack[$filename]);
  183. }
  184. }
  185. }
  186. }
  187. }
  188. /**
  189. * Sets the PDF Version to the highest of imported documents
  190. */
  191. function setVersion() {
  192. $this->PDFVersion = max($this->importVersion, $this->PDFVersion);
  193. }
  194. /**
  195. * Put resources
  196. */
  197. function _putresources() {
  198. $this->_putfonts();
  199. $this->_putimages();
  200. $this->_putformxobjects();
  201. $this->_putimportedobjects();
  202. //Resource dictionary
  203. $this->offsets[2]=strlen($this->buffer);
  204. $this->_out('2 0 obj');
  205. $this->_out('<<');
  206. $this->_putresourcedict();
  207. $this->_out('>>');
  208. $this->_out('endobj');
  209. }
  210. /**
  211. * Private Method that writes the form xobjects
  212. */
  213. function _putformxobjects() {
  214. $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
  215. reset($this->tpls);
  216. foreach($this->tpls AS $tplidx => $tpl) {
  217. $p=($this->compress) ? gzcompress($tpl['buffer']) : $tpl['buffer'];
  218. $this->_newobj();
  219. $this->tpls[$tplidx]['n'] = $this->n;
  220. $this->_out('<<'.$filter.'/Type /XObject');
  221. $this->_out('/Subtype /Form');
  222. $this->_out('/FormType 1');
  223. $this->_out(sprintf('/BBox [%.2f %.2f %.2f %.2f]',
  224. ($tpl['x'] + (isset($tpl['box']['x'])?$tpl['box']['x']:0))*$this->k,
  225. ($tpl['h'] + (isset($tpl['box']['y'])?$tpl['box']['y']:0) - $tpl['y'])*$this->k,
  226. ($tpl['w'] + (isset($tpl['box']['x'])?$tpl['box']['x']:0))*$this->k,
  227. ($tpl['h'] + (isset($tpl['box']['y'])?$tpl['box']['y']:0) - $tpl['y']-$tpl['h'])*$this->k)
  228. );
  229. if (isset($tpl['box']))
  230. $this->_out(sprintf('/Matrix [1 0 0 1 %.5f %.5f]',-$tpl['box']['x']*$this->k, -$tpl['box']['y']*$this->k));
  231. $this->_out('/Resources ');
  232. if (isset($tpl['resources'])) {
  233. $this->current_parser =& $tpl['parser'];
  234. $this->pdf_write_value($tpl['resources']);
  235. } else {
  236. $this->_out('<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  237. if (isset($this->_res['tpl'][$tplidx]['fonts']) && count($this->_res['tpl'][$tplidx]['fonts'])) {
  238. $this->_out('/Font <<');
  239. foreach($this->_res['tpl'][$tplidx]['fonts'] as $font)
  240. $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
  241. $this->_out('>>');
  242. }
  243. if(isset($this->_res['tpl'][$tplidx]['images']) && count($this->_res['tpl'][$tplidx]['images']) ||
  244. isset($this->_res['tpl'][$tplidx]['tpls']) && count($this->_res['tpl'][$tplidx]['tpls']))
  245. {
  246. $this->_out('/XObject <<');
  247. if (isset($this->_res['tpl'][$tplidx]['images']) && count($this->_res['tpl'][$tplidx]['images'])) {
  248. foreach($this->_res['tpl'][$tplidx]['images'] as $image)
  249. $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
  250. }
  251. if (isset($this->_res['tpl'][$tplidx]['tpls']) && count($this->_res['tpl'][$tplidx]['tpls'])) {
  252. foreach($this->_res['tpl'][$tplidx]['tpls'] as $i => $tpl)
  253. $this->_out($this->tplprefix.$i.' '.$tpl['n'].' 0 R');
  254. }
  255. $this->_out('>>');
  256. }
  257. $this->_out('>>');
  258. }
  259. $this->_out('/Length '.strlen($p).' >>');
  260. $this->_putstream($p);
  261. $this->_out('endobj');
  262. }
  263. }
  264. /**
  265. * Rewritten to handle existing own defined objects
  266. */
  267. function _newobj($obj_id=false,$onlynewobj=false) {
  268. if (!$obj_id) {
  269. $obj_id = ++$this->n;
  270. }
  271. //Begin a new object
  272. if (!$onlynewobj) {
  273. $this->offsets[$obj_id] = strlen($this->buffer);
  274. $this->_out($obj_id.' 0 obj');
  275. $this->_current_obj_id = $obj_id; // for later use with encryption
  276. }
  277. }
  278. /**
  279. * Writes a value
  280. * Needed to rebuild the source document
  281. *
  282. * @param mixed $value A PDF-Value. Structure of values see cases in this method
  283. */
  284. function pdf_write_value(&$value)
  285. {
  286. switch ($value[0]) {
  287. case PDF_TYPE_NUMERIC :
  288. case PDF_TYPE_TOKEN :
  289. // A numeric value or a token.
  290. // Simply output them
  291. $this->_out($value[1]." ", false);
  292. break;
  293. case PDF_TYPE_ARRAY :
  294. // An array. Output the proper
  295. // structure and move on.
  296. $this->_out("[",false);
  297. for ($i = 0; $i < count($value[1]); $i++) {
  298. $this->pdf_write_value($value[1][$i]);
  299. }
  300. $this->_out("]");
  301. break;
  302. case PDF_TYPE_DICTIONARY :
  303. // A dictionary.
  304. $this->_out("<<",false);
  305. reset ($value[1]);
  306. while (list($k, $v) = each($value[1])) {
  307. $this->_out($k . " ",false);
  308. $this->pdf_write_value($v);
  309. }
  310. $this->_out(">>");
  311. break;
  312. case PDF_TYPE_OBJREF :
  313. // An indirect object reference
  314. // Fill the object stack if needed
  315. $cpfn =& $this->current_parser->filename;
  316. if (!isset($this->_don_obj_stack[$cpfn][$value[1]])) {
  317. $this->_newobj(false,true);
  318. $this->_obj_stack[$cpfn][$value[1]] = array($this->n, $value);
  319. $this->_don_obj_stack[$cpfn][$value[1]] = array($this->n, $value);
  320. }
  321. $objid = $this->_don_obj_stack[$cpfn][$value[1]][0];
  322. $this->_out("{$objid} 0 R"); //{$value[2]}
  323. break;
  324. case PDF_TYPE_STRING :
  325. // A string.
  326. $this->_out('('.$value[1].')');
  327. break;
  328. case PDF_TYPE_STREAM :
  329. // A stream. First, output the
  330. // stream dictionary, then the
  331. // stream data itself.
  332. $this->pdf_write_value($value[1]);
  333. $this->_out("stream");
  334. $this->_out($value[2][1]);
  335. $this->_out("endstream");
  336. break;
  337. case PDF_TYPE_HEX :
  338. $this->_out("<".$value[1].">");
  339. break;
  340. case PDF_TYPE_NULL :
  341. // The null object.
  342. $this->_out("null");
  343. break;
  344. }
  345. }
  346. /**
  347. * Private Method
  348. */
  349. function _out($s,$ln=true) {
  350. //Add a line to the document
  351. if ($this->state==2) {
  352. if (!$this->_intpl)
  353. $this->pages[$this->page] .= $s.($ln == true ? "\n" : '');
  354. else
  355. $this->tpls[$this->tpl]['buffer'] .= $s.($ln == true ? "\n" : '');
  356. } else {
  357. $this->buffer.=$s.($ln == true ? "\n" : '');
  358. }
  359. }
  360. /**
  361. * rewritten to close opened parsers
  362. *
  363. */
  364. function _enddoc() {
  365. parent::_enddoc();
  366. $this->_closeParsers();
  367. }
  368. /**
  369. * close all files opened by parsers
  370. */
  371. function _closeParsers() {
  372. if ($this->state > 2 && count($this->parsers) > 0) {
  373. foreach ($this->parsers as $k => $_){
  374. $this->parsers[$k]->closeFile();
  375. $this->parsers[$k] = null;
  376. unset($this->parsers[$k]);
  377. }
  378. return true;
  379. }
  380. return false;
  381. }
  382. }
  383. // for PHP5
  384. if (!class_exists('fpdi')) {
  385. class fpdi extends FPDI {}
  386. }
  387. ?>