FpdfTplTrait.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. /**
  3. * This file is part of FPDI
  4. *
  5. * @package Fpdi
  6. * @copyright Copyright (c) 2020 Setasign GmbH & Co. KG (https://www.setasign.com)
  7. * @license http://opensource.org/licenses/mit-license The MIT License
  8. */
  9. namespace Fpdi;
  10. /**
  11. * Trait FpdfTplTrait
  12. *
  13. * This class adds a templating feature to tFPDF.
  14. */
  15. trait FpdfTplTrait
  16. {
  17. /**
  18. * Data of all created templates.
  19. *
  20. * @var array
  21. */
  22. protected $templates = [];
  23. /**
  24. * The template id for the currently created template.
  25. *
  26. * @var null|int
  27. */
  28. protected $currentTemplateId;
  29. /**
  30. * A counter for template ids.
  31. *
  32. * @var int
  33. */
  34. protected $templateId = 0;
  35. /**
  36. * Set the page format of the current page.
  37. *
  38. * @param array $size An array with two values defining the size.
  39. * @param string $orientation "L" for landscape, "P" for portrait.
  40. * @throws \BadMethodCallException
  41. */
  42. public function setPageFormat($size, $orientation)
  43. {
  44. if ($this->currentTemplateId !== null) {
  45. throw new \BadMethodCallException('The page format cannot be changed when writing to a template.');
  46. }
  47. if (!\in_array($orientation, ['P', 'L'], true)) {
  48. throw new \InvalidArgumentException(\sprintf(
  49. 'Invalid page orientation "%s"! Only "P" and "L" are allowed!',
  50. $orientation
  51. ));
  52. }
  53. $size = $this->_getpagesize($size);
  54. if (
  55. $orientation != $this->CurOrientation
  56. || $size[0] != $this->CurPageSize[0]
  57. || $size[1] != $this->CurPageSize[1]
  58. ) {
  59. // New size or orientation
  60. if ($orientation === 'P') {
  61. $this->w = $size[0];
  62. $this->h = $size[1];
  63. } else {
  64. $this->w = $size[1];
  65. $this->h = $size[0];
  66. }
  67. $this->wPt = $this->w * $this->k;
  68. $this->hPt = $this->h * $this->k;
  69. $this->PageBreakTrigger = $this->h - $this->bMargin;
  70. $this->CurOrientation = $orientation;
  71. $this->CurPageSize = $size;
  72. $this->PageInfo[$this->page]['size'] = array($this->wPt, $this->hPt);
  73. }
  74. }
  75. /**
  76. * Draws a template onto the page or another template.
  77. *
  78. * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the
  79. * aspect ratio.
  80. *
  81. * @param mixed $tpl The template id
  82. * @param array|float|int $x The abscissa of upper-left corner. Alternatively you could use an assoc array
  83. * with the keys "x", "y", "width", "height", "adjustPageSize".
  84. * @param float|int $y The ordinate of upper-left corner.
  85. * @param float|int|null $width The width.
  86. * @param float|int|null $height The height.
  87. * @param bool $adjustPageSize
  88. * @return array The size
  89. * @see FpdfTplTrait::getTemplateSize()
  90. */
  91. public function useTemplate($tpl, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false)
  92. {
  93. if (!isset($this->templates[$tpl])) {
  94. throw new \InvalidArgumentException('Template does not exist!');
  95. }
  96. if (\is_array($x)) {
  97. unset($x['tpl']);
  98. \extract($x, EXTR_IF_EXISTS);
  99. /** @noinspection NotOptimalIfConditionsInspection */
  100. /** @noinspection PhpConditionAlreadyCheckedInspection */
  101. if (\is_array($x)) {
  102. $x = 0;
  103. }
  104. }
  105. $template = $this->templates[$tpl];
  106. $originalSize = $this->getTemplateSize($tpl);
  107. $newSize = $this->getTemplateSize($tpl, $width, $height);
  108. if ($adjustPageSize) {
  109. $this->setPageFormat($newSize, $newSize['orientation']);
  110. }
  111. $this->_out(
  112. // reset standard values, translate and scale
  113. \sprintf(
  114. 'q 0 J 1 w 0 j 0 G 0 g %.4F 0 0 %.4F %.4F %.4F cm /%s Do Q',
  115. ($newSize['width'] / $originalSize['width']),
  116. ($newSize['height'] / $originalSize['height']),
  117. $x * $this->k,
  118. ($this->h - $y - $newSize['height']) * $this->k,
  119. $template['id']
  120. )
  121. );
  122. return $newSize;
  123. }
  124. /**
  125. * Get the size of a template.
  126. *
  127. * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the
  128. * aspect ratio.
  129. *
  130. * @param mixed $tpl The template id
  131. * @param float|int|null $width The width.
  132. * @param float|int|null $height The height.
  133. * @return array|bool An array with following keys: width, height, 0 (=width), 1 (=height), orientation (L or P)
  134. */
  135. public function getTemplateSize($tpl, $width = null, $height = null)
  136. {
  137. if (!isset($this->templates[$tpl])) {
  138. return false;
  139. }
  140. if ($width === null && $height === null) {
  141. $width = $this->templates[$tpl]['width'];
  142. $height = $this->templates[$tpl]['height'];
  143. } elseif ($width === null) {
  144. $width = $height * $this->templates[$tpl]['width'] / $this->templates[$tpl]['height'];
  145. }
  146. if ($height === null) {
  147. $height = $width * $this->templates[$tpl]['height'] / $this->templates[$tpl]['width'];
  148. }
  149. if ($height <= 0. || $width <= 0.) {
  150. throw new \InvalidArgumentException('Width or height parameter needs to be larger than zero.');
  151. }
  152. return [
  153. 'width' => $width,
  154. 'height' => $height,
  155. 0 => $width,
  156. 1 => $height,
  157. 'orientation' => $width > $height ? 'L' : 'P'
  158. ];
  159. }
  160. /**
  161. * Begins a new template.
  162. *
  163. * @param float|int|null $width The width of the template. If null, the current page width is used.
  164. * @param float|int|null $height The height of the template. If null, the current page height is used.
  165. * @param bool $groupXObject Define the form XObject as a group XObject to support transparency (if used).
  166. * @return int A template identifier.
  167. */
  168. public function beginTemplate($width = null, $height = null, $groupXObject = false)
  169. {
  170. if ($width === null) {
  171. $width = $this->w;
  172. }
  173. if ($height === null) {
  174. $height = $this->h;
  175. }
  176. $templateId = $this->getNextTemplateId();
  177. // initiate buffer with current state of FPDF
  178. $buffer = "2 J\n"
  179. . \sprintf('%.2F w', $this->LineWidth * $this->k) . "\n";
  180. if ($this->FontFamily) {
  181. $buffer .= \sprintf("BT /F%d %.2F Tf ET\n", $this->CurrentFont['i'], $this->FontSizePt);
  182. }
  183. if ($this->DrawColor !== '0 G') {
  184. $buffer .= $this->DrawColor . "\n";
  185. }
  186. if ($this->FillColor !== '0 g') {
  187. $buffer .= $this->FillColor . "\n";
  188. }
  189. if ($groupXObject && \version_compare('1.4', $this->PDFVersion, '>')) {
  190. $this->PDFVersion = '1.4';
  191. }
  192. $this->templates[$templateId] = [
  193. 'objectNumber' => null,
  194. 'id' => 'TPL' . $templateId,
  195. 'buffer' => $buffer,
  196. 'width' => $width,
  197. 'height' => $height,
  198. 'groupXObject' => $groupXObject,
  199. 'state' => [
  200. 'x' => $this->x,
  201. 'y' => $this->y,
  202. 'AutoPageBreak' => $this->AutoPageBreak,
  203. 'bMargin' => $this->bMargin,
  204. 'tMargin' => $this->tMargin,
  205. 'lMargin' => $this->lMargin,
  206. 'rMargin' => $this->rMargin,
  207. 'h' => $this->h,
  208. 'w' => $this->w,
  209. 'FontFamily' => $this->FontFamily,
  210. 'FontStyle' => $this->FontStyle,
  211. 'FontSizePt' => $this->FontSizePt,
  212. 'FontSize' => $this->FontSize,
  213. 'underline' => $this->underline,
  214. 'TextColor' => $this->TextColor,
  215. 'DrawColor' => $this->DrawColor,
  216. 'FillColor' => $this->FillColor,
  217. 'ColorFlag' => $this->ColorFlag
  218. ]
  219. ];
  220. $this->SetAutoPageBreak(false);
  221. $this->currentTemplateId = $templateId;
  222. $this->h = $height;
  223. $this->w = $width;
  224. $this->SetXY($this->lMargin, $this->tMargin);
  225. $this->SetRightMargin($this->w - $width + $this->rMargin);
  226. return $templateId;
  227. }
  228. /**
  229. * Ends a template.
  230. *
  231. * @return bool|int|null A template identifier.
  232. */
  233. public function endTemplate()
  234. {
  235. if ($this->currentTemplateId === null) {
  236. return false;
  237. }
  238. $templateId = $this->currentTemplateId;
  239. $template = $this->templates[$templateId];
  240. $state = $template['state'];
  241. $this->SetXY($state['x'], $state['y']);
  242. $this->tMargin = $state['tMargin'];
  243. $this->lMargin = $state['lMargin'];
  244. $this->rMargin = $state['rMargin'];
  245. $this->h = $state['h'];
  246. $this->w = $state['w'];
  247. $this->SetAutoPageBreak($state['AutoPageBreak'], $state['bMargin']);
  248. $this->FontFamily = $state['FontFamily'];
  249. $this->FontStyle = $state['FontStyle'];
  250. $this->FontSizePt = $state['FontSizePt'];
  251. $this->FontSize = $state['FontSize'];
  252. $this->TextColor = $state['TextColor'];
  253. $this->DrawColor = $state['DrawColor'];
  254. $this->FillColor = $state['FillColor'];
  255. $this->ColorFlag = $state['ColorFlag'];
  256. $this->underline = $state['underline'];
  257. $fontKey = $this->FontFamily . $this->FontStyle;
  258. if ($fontKey) {
  259. $this->CurrentFont =& $this->fonts[$fontKey];
  260. } else {
  261. unset($this->CurrentFont);
  262. }
  263. $this->currentTemplateId = null;
  264. return $templateId;
  265. }
  266. /**
  267. * Get the next template id.
  268. *
  269. * @return int
  270. */
  271. protected function getNextTemplateId()
  272. {
  273. return $this->templateId++;
  274. }
  275. /* overwritten FPDF methods: */
  276. /**
  277. * @inheritdoc
  278. */
  279. public function AddPage($orientation = '', $size = '', $rotation = 0)
  280. {
  281. if ($this->currentTemplateId !== null) {
  282. throw new \BadMethodCallException('Pages cannot be added when writing to a template.');
  283. }
  284. parent::AddPage($orientation, $size, $rotation);
  285. }
  286. /**
  287. * @inheritdoc
  288. */
  289. public function Link($x, $y, $w, $h, $link)
  290. {
  291. if ($this->currentTemplateId !== null) {
  292. throw new \BadMethodCallException('Links cannot be set when writing to a template.');
  293. }
  294. parent::Link($x, $y, $w, $h, $link);
  295. }
  296. /**
  297. * @inheritdoc
  298. */
  299. public function SetLink($link, $y = 0, $page = -1)
  300. {
  301. if ($this->currentTemplateId !== null) {
  302. throw new \BadMethodCallException('Links cannot be set when writing to a template.');
  303. }
  304. return parent::SetLink($link, $y, $page);
  305. }
  306. /**
  307. * @inheritdoc
  308. */
  309. public function SetDrawColor($r, $g = null, $b = null)
  310. {
  311. parent::SetDrawColor($r, $g, $b);
  312. if ($this->page === 0 && $this->currentTemplateId !== null) {
  313. $this->_out($this->DrawColor);
  314. }
  315. }
  316. /**
  317. * @inheritdoc
  318. */
  319. public function SetFillColor($r, $g = null, $b = null)
  320. {
  321. parent::SetFillColor($r, $g, $b);
  322. if ($this->page === 0 && $this->currentTemplateId !== null) {
  323. $this->_out($this->FillColor);
  324. }
  325. }
  326. /**
  327. * @inheritdoc
  328. */
  329. public function SetLineWidth($width)
  330. {
  331. parent::SetLineWidth($width);
  332. if ($this->page === 0 && $this->currentTemplateId !== null) {
  333. $this->_out(\sprintf('%.2F w', $width * $this->k));
  334. }
  335. }
  336. /**
  337. * @inheritdoc
  338. */
  339. public function SetFont($family, $style = '', $size = 0)
  340. {
  341. parent::SetFont($family, $style, $size);
  342. if ($this->page === 0 && $this->currentTemplateId !== null) {
  343. $this->_out(\sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  344. }
  345. }
  346. /**
  347. * @inheritdoc
  348. */
  349. public function SetFontSize($size)
  350. {
  351. parent::SetFontSize($size);
  352. if ($this->page === 0 && $this->currentTemplateId !== null) {
  353. $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  354. }
  355. }
  356. /**
  357. * @inheritdoc
  358. */
  359. protected function _putimages()
  360. {
  361. parent::_putimages();
  362. foreach ($this->templates as $key => $template) {
  363. $this->_newobj();
  364. $this->templates[$key]['objectNumber'] = $this->n;
  365. $this->_put('<</Type /XObject /Subtype /Form /FormType 1');
  366. $this->_put(\sprintf(
  367. '/BBox[0 0 %.2F %.2F]',
  368. $template['width'] * $this->k,
  369. $template['height'] * $this->k
  370. ));
  371. $this->_put('/Resources 2 0 R'); // default resources dictionary of FPDF
  372. if ($this->compress) {
  373. $buffer = \gzcompress($template['buffer']);
  374. $this->_put('/Filter/FlateDecode');
  375. } else {
  376. $buffer = $template['buffer'];
  377. }
  378. $this->_put('/Length ' . \strlen($buffer));
  379. if ($template['groupXObject']) {
  380. $this->_put('/Group <</Type/Group/S/Transparency>>');
  381. }
  382. $this->_put('>>');
  383. $this->_putstream($buffer);
  384. $this->_put('endobj');
  385. }
  386. }
  387. /**
  388. * @inheritdoc
  389. */
  390. protected function _putxobjectdict()
  391. {
  392. foreach ($this->templates as $key => $template) {
  393. $this->_put('/' . $template['id'] . ' ' . $template['objectNumber'] . ' 0 R');
  394. }
  395. parent::_putxobjectdict();
  396. }
  397. /**
  398. * @inheritdoc
  399. */
  400. public function _out($s)
  401. {
  402. if ($this->currentTemplateId !== null) {
  403. $this->templates[$this->currentTemplateId]['buffer'] .= $s . "\n";
  404. } else {
  405. parent::_out($s);
  406. }
  407. }
  408. }