composer package updates
[openemr.git] / vendor / dompdf / dompdf / src / Adapter / PDFLib.php
blobd002754fdbec28722630b96df26516212220d697
1 <?php
2 /**
3 * @package dompdf
4 * @link http://dompdf.github.com/
5 * @author Benj Carson <benjcarson@digitaljunkies.ca>
6 * @author Helmut Tischer <htischer@weihenstephan.org>
7 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
8 */
10 namespace Dompdf\Adapter;
12 use Dompdf\Canvas;
13 use Dompdf\Dompdf;
14 use Dompdf\Helpers;
15 use Dompdf\Exception;
16 use Dompdf\Image\Cache;
17 use Dompdf\PhpEvaluator;
19 /**
20 * PDF rendering interface
22 * Dompdf\Adapter\PDFLib provides a simple, stateless interface to the one
23 * provided by PDFLib.
25 * Unless otherwise mentioned, all dimensions are in points (1/72 in).
26 * The coordinate origin is in the top left corner and y values
27 * increase downwards.
29 * See {@link http://www.pdflib.com/} for more complete documentation
30 * on the underlying PDFlib functions.
32 * @package dompdf
34 class PDFLib implements Canvas
37 /**
38 * Dimensions of paper sizes in points
40 * @var array;
42 static public $PAPER_SIZES = array(); // Set to Dompdf\Adapter\CPDF::$PAPER_SIZES below.
44 /**
45 * Whether to create PDFs in memory or on disk
47 * @var bool
49 static $IN_MEMORY = true;
51 /**
52 * @var Dompdf
54 private $_dompdf;
56 /**
57 * Instance of PDFLib class
59 * @var \PDFlib
61 private $_pdf;
63 /**
64 * Name of temporary file used for PDFs created on disk
66 * @var string
68 private $_file;
70 /**
71 * PDF width, in points
73 * @var float
75 private $_width;
77 /**
78 * PDF height, in points
80 * @var float
82 private $_height;
84 /**
85 * Last fill color used
87 * @var array
89 private $_last_fill_color;
91 /**
92 * Last stroke color used
94 * @var array
96 private $_last_stroke_color;
98 /**
99 * The current opacity level
101 * @var array
103 private $_current_opacity;
106 * Cache of image handles
108 * @var array
110 private $_imgs;
113 * Cache of font handles
115 * @var array
117 private $_fonts;
120 * List of objects (templates) to add to multiple pages
122 * @var array
124 private $_objs;
127 * List of gstate objects created for this PDF (for reuse)
129 * @var array
131 private $_gstates = array();
134 * Current page number
136 * @var int
138 private $_page_number;
141 * Total number of pages
143 * @var int
145 private $_page_count;
148 * Text to display on every page
150 * @var array
152 private $_page_text;
155 * Array of pages for accesing after rendering is initially complete
157 * @var array
159 private $_pages;
162 * Class constructor
164 * @param mixed $paper The size of paper to use either a string (see {@link Dompdf\Adapter\CPDF::$PAPER_SIZES}) or
165 * an array(xmin,ymin,xmax,ymax)
166 * @param string $orientation The orientation of the document (either 'landscape' or 'portrait')
167 * @param Dompdf $dompdf
169 public function __construct($paper = "letter", $orientation = "portrait", Dompdf $dompdf)
171 if (is_array($paper)) {
172 $size = $paper;
173 } else if (isset(self::$PAPER_SIZES[mb_strtolower($paper)])) {
174 $size = self::$PAPER_SIZES[mb_strtolower($paper)];
175 } else {
176 $size = self::$PAPER_SIZES["letter"];
179 if (mb_strtolower($orientation) === "landscape") {
180 list($size[2], $size[3]) = array($size[3], $size[2]);
183 $this->_width = $size[2] - $size[0];
184 $this->_height = $size[3] - $size[1];
186 $this->_dompdf = $dompdf;
188 $this->_pdf = new \PDFLib();
190 $license = $dompdf->getOptions()->getPdflibLicense();
191 if (strlen($license) > 0) {
192 $this->_pdf->set_parameter("license", $license);
195 $this->_pdf->set_parameter("textformat", "utf8");
196 $this->_pdf->set_parameter("fontwarning", "false");
198 // TODO: fetch PDFLib version information for the producer field
199 $this->_pdf->set_info("Producer Addendum", sprintf("%s + PDFLib", $dompdf->version));
201 // Silence pedantic warnings about missing TZ settings
202 $tz = @date_default_timezone_get();
203 date_default_timezone_set("UTC");
204 $this->_pdf->set_info("Date", date("Y-m-d"));
205 date_default_timezone_set($tz);
207 if (self::$IN_MEMORY) {
208 $this->_pdf->begin_document("", "");
209 } else {
210 $tmp_dir = $this->_dompdf->getOptions()->getTempDir();
211 $tmp_name = tempnam($tmp_dir, "libdompdf_pdf_");
212 @unlink($tmp_name);
213 $this->_file = "$tmp_name.pdf";
214 $this->_pdf->begin_document($this->_file, "");
217 $this->_pdf->begin_page_ext($this->_width, $this->_height, "");
219 $this->_page_number = $this->_page_count = 1;
220 $this->_page_text = array();
222 $this->_imgs = array();
223 $this->_fonts = array();
224 $this->_objs = array();
228 * @return Dompdf
230 function get_dompdf()
232 return $this->_dompdf;
236 * Close the pdf
238 protected function _close()
240 $this->_place_objects();
242 // Close all pages
243 $this->_pdf->suspend_page("");
244 for ($p = 1; $p <= $this->_page_count; $p++) {
245 $this->_pdf->resume_page("pagenumber=$p");
246 $this->_pdf->end_page_ext("");
249 $this->_pdf->end_document("");
254 * Returns the PDFLib instance
256 * @return PDFLib
258 public function get_pdflib()
260 return $this->_pdf;
264 * Add meta information to the PDF
266 * @param string $label label of the value (Creator, Producter, etc.)
267 * @param string $value the text to set
269 public function add_info($label, $value)
271 $this->_pdf->set_info($label, $value);
275 * Opens a new 'object' (template in PDFLib-speak)
277 * While an object is open, all drawing actions are recorded to the
278 * object instead of being drawn on the current page. Objects can
279 * be added later to a specific page or to several pages.
281 * The return value is an integer ID for the new object.
283 * @see PDFLib::close_object()
284 * @see PDFLib::add_object()
286 * @return int
288 public function open_object()
290 $this->_pdf->suspend_page("");
291 $ret = $this->_pdf->begin_template($this->_width, $this->_height);
292 $this->_pdf->save();
293 $this->_objs[$ret] = array("start_page" => $this->_page_number);
294 return $ret;
298 * Reopen an existing object (NOT IMPLEMENTED)
299 * PDFLib does not seem to support reopening templates.
301 * @param int $object the ID of a previously opened object
303 * @throws Exception
304 * @return void
306 public function reopen_object($object)
308 throw new Exception("PDFLib does not support reopening objects.");
312 * Close the current template
314 * @see PDFLib::open_object()
316 public function close_object()
318 $this->_pdf->restore();
319 $this->_pdf->end_template();
320 $this->_pdf->resume_page("pagenumber=" . $this->_page_number);
324 * Adds the specified object to the document
326 * $where can be one of:
327 * - 'add' add to current page only
328 * - 'all' add to every page from the current one onwards
329 * - 'odd' add to all odd numbered pages from now on
330 * - 'even' add to all even numbered pages from now on
331 * - 'next' add the object to the next page only
332 * - 'nextodd' add to all odd numbered pages from the next one
333 * - 'nexteven' add to all even numbered pages from the next one
335 * @param int $object the object handle returned by open_object()
336 * @param string $where
338 public function add_object($object, $where = 'all')
341 if (mb_strpos($where, "next") !== false) {
342 $this->_objs[$object]["start_page"]++;
343 $where = str_replace("next", "", $where);
344 if ($where == "") {
345 $where = "add";
349 $this->_objs[$object]["where"] = $where;
353 * Stops the specified template from appearing in the document.
355 * The object will stop being displayed on the page following the
356 * current one.
358 * @param int $object
360 public function stop_object($object)
363 if (!isset($this->_objs[$object])) {
364 return;
367 $start = $this->_objs[$object]["start_page"];
368 $where = $this->_objs[$object]["where"];
370 // Place the object on this page if required
371 if ($this->_page_number >= $start &&
372 (($this->_page_number % 2 == 0 && $where === "even") ||
373 ($this->_page_number % 2 == 1 && $where === "odd") ||
374 ($where === "all"))
376 $this->_pdf->fit_image($object, 0, 0, "");
379 $this->_objs[$object] = null;
380 unset($this->_objs[$object]);
384 * Add all active objects to the current page
386 protected function _place_objects()
389 foreach ($this->_objs as $obj => $props) {
390 $start = $props["start_page"];
391 $where = $props["where"];
393 // Place the object on this page if required
394 if ($this->_page_number >= $start &&
395 (($this->_page_number % 2 == 0 && $where === "even") ||
396 ($this->_page_number % 2 == 1 && $where === "odd") ||
397 ($where === "all"))
399 $this->_pdf->fit_image($obj, 0, 0, "");
406 * @return float|mixed
408 public function get_width()
410 return $this->_width;
414 * @return float|mixed
416 public function get_height()
418 return $this->_height;
422 * @return int
424 public function get_page_number()
426 return $this->_page_number;
430 * @return int
432 public function get_page_count()
434 return $this->_page_count;
438 * @param $num
440 public function set_page_number($num)
442 $this->_page_number = (int)$num;
446 * @param int $count
448 public function set_page_count($count)
450 $this->_page_count = (int)$count;
454 * Sets the line style
456 * @param float $width
457 * @param $cap
458 * @param string $join
459 * @param array $dash
461 * @return void
463 protected function _set_line_style($width, $cap, $join, $dash)
465 if (count($dash) == 1) {
466 $dash[] = $dash[0];
469 if (count($dash) > 1) {
470 $this->_pdf->setdashpattern("dasharray={" . implode(" ", $dash) . "}");
471 } else {
472 $this->_pdf->setdash(0, 0);
475 switch ($join) {
476 case "miter":
477 $this->_pdf->setlinejoin(0);
478 break;
480 case "round":
481 $this->_pdf->setlinejoin(1);
482 break;
484 case "bevel":
485 $this->_pdf->setlinejoin(2);
486 break;
488 default:
489 break;
492 switch ($cap) {
493 case "butt":
494 $this->_pdf->setlinecap(0);
495 break;
497 case "round":
498 $this->_pdf->setlinecap(1);
499 break;
501 case "square":
502 $this->_pdf->setlinecap(2);
503 break;
505 default:
506 break;
509 $this->_pdf->setlinewidth($width);
513 * Sets the line color
515 * @param array $color array(r,g,b)
517 protected function _set_stroke_color($color)
519 if ($this->_last_stroke_color == $color) {
520 //return;
523 $alpha = isset($color["alpha"]) ? $color["alpha"] : 1;
524 if (isset($this->_current_opacity)) {
525 $alpha *= $this->_current_opacity;
528 $this->_last_stroke_color = $color;
530 if (isset($color[3])) {
531 $type = "cmyk";
532 list($c1, $c2, $c3, $c4) = array($color[0], $color[1], $color[2], $color[3]);
533 } elseif (isset($color[2])) {
534 $type = "rgb";
535 list($c1, $c2, $c3, $c4) = array($color[0], $color[1], $color[2], null);
536 } else {
537 $type = "gray";
538 list($c1, $c2, $c3, $c4) = array($color[0], $color[1], null, null);
541 $this->_set_stroke_opacity($alpha);
542 $this->_pdf->setcolor("stroke", $type, $c1, $c2, $c3, $c4);
546 * Sets the fill color
548 * @param array $color array(r,g,b)
550 protected function _set_fill_color($color)
552 if ($this->_last_fill_color == $color) {
553 return;
556 $alpha = isset($color["alpha"]) ? $color["alpha"] : 1;
557 if (isset($this->_current_opacity)) {
558 $alpha *= $this->_current_opacity;
561 $this->_last_fill_color = $color;
563 if (isset($color[3])) {
564 $type = "cmyk";
565 list($c1, $c2, $c3, $c4) = array($color[0], $color[1], $color[2], $color[3]);
566 } elseif (isset($color[2])) {
567 $type = "rgb";
568 list($c1, $c2, $c3, $c4) = array($color[0], $color[1], $color[2], null);
569 } else {
570 $type = "gray";
571 list($c1, $c2, $c3, $c4) = array($color[0], $color[1], null, null);
574 $this->_set_fill_opacity($alpha);
575 $this->_pdf->setcolor("fill", $type, $c1, $c2, $c3, $c4);
579 * Sets the fill opacity
581 * @param $opacity
582 * @param $mode
584 public function _set_fill_opacity($opacity, $mode = "Normal")
586 if ($mode === "Normal") {
587 $this->_set_gstate("opacityfill=$opacity");
592 * Sets the stroke opacity
594 * @param $opacity
595 * @param $mode
597 public function _set_stroke_opacity($opacity, $mode = "Normal")
599 if ($mode === "Normal") {
600 $this->_set_gstate("opacitystroke=$opacity");
605 * Sets the opacity
607 * @param $opacity
608 * @param $mode
610 public function set_opacity($opacity, $mode = "Normal")
612 if ($mode === "Normal") {
613 $this->_set_gstate("opacityfill=$opacity opacitystroke=$opacity");
614 $this->_current_opacity = $opacity;
619 * Sets the gstate
621 * @param $gstate_options
622 * @return int
624 public function _set_gstate($gstate_options)
626 if (($gstate = array_search($gstate_options, $this->_gstates)) === false) {
627 $gstate = $this->_pdf->create_gstate($gstate_options);
628 $this->_gstates[$gstate] = $gstate_options;
630 return $this->_pdf->set_gstate($gstate);
633 public function set_default_view($view, $options = array())
635 // TODO
636 // http://www.pdflib.com/fileadmin/pdflib/pdf/manuals/PDFlib-8.0.2-API-reference.pdf
638 * fitheight Fit the page height to the window, with the x coordinate left at the left edge of the window.
639 * fitrect Fit the rectangle specified by left, bottom, right, and top to the window.
640 * fitvisible Fit the visible contents of the page (the ArtBox) to the window.
641 * fitvisibleheight Fit the visible contents of the page to the window with the x coordinate left at the left edge of the window.
642 * fitvisiblewidth Fit the visible contents of the page to the window with the y coordinate top at the top edge of the window.
643 * fitwidth Fit the page width to the window, with the y coordinate top at the top edge of the window.
644 * fitwindow Fit the complete page to the window.
645 * fixed
647 //$this->_pdf->set_parameter("openaction", $view);
651 * Loads a specific font and stores the corresponding descriptor.
653 * @param string $font
654 * @param string $encoding
655 * @param string $options
657 * @return int the font descriptor for the font
659 protected function _load_font($font, $encoding = null, $options = "")
661 // Set up font paths
662 if ($this->_pdf->get_parameter("FontOutline", 1) === "") {
663 $families = $this->_dompdf->getFontMetrics()->getFontFamilies();
664 foreach ($families as $files) {
665 foreach ($files as $file) {
666 $face = basename($file);
667 $afm = null;
669 // Prefer ttfs to afms
670 if (file_exists("$file.ttf")) {
671 $outline = "$file.ttf";
673 } else if (file_exists("$file.TTF")) {
674 $outline = "$file.TTF";
676 } else if (file_exists("$file.pfb")) {
677 $outline = "$file.pfb";
678 if (file_exists("$file.afm")) {
679 $afm = "$file.afm";
682 } else if (file_exists("$file.PFB")) {
683 $outline = "$file.PFB";
684 if (file_exists("$file.AFM")) {
685 $afm = "$file.AFM";
687 } else {
688 continue;
691 $this->_pdf->set_parameter("FontOutline", "\{$face\}=\{$outline\}");
693 if (!is_null($afm)) {
694 $this->_pdf->set_parameter("FontAFM", "\{$face\}=\{$afm\}");
700 // Check if the font is a native PDF font
701 // Embed non-native fonts
702 $test = strtolower(basename($font));
703 if (in_array($test, DOMPDF::$nativeFonts)) {
704 $font = basename($font);
705 } else {
706 // Embed non-native fonts
707 $options .= " embedding=true";
710 if (is_null($encoding)) {
711 // Unicode encoding is only available for the commerical
712 // version of PDFlib and not PDFlib-Lite
713 if (strlen($this->_dompdf->getOptions()->getPdflibLicense()) > 0) {
714 $encoding = "unicode";
715 } else {
716 $encoding = "auto";
720 $key = "$font:$encoding:$options";
722 if (isset($this->_fonts[$key])) {
723 return $this->_fonts[$key];
724 } else {
725 $this->_fonts[$key] = $this->_pdf->load_font($font, $encoding, $options);
726 return $this->_fonts[$key];
731 * Remaps y coords from 4th to 1st quadrant
733 * @param float $y
734 * @return float
736 protected function y($y)
738 return $this->_height - $y;
742 * @param float $x1
743 * @param float $y1
744 * @param float $x2
745 * @param float $y2
746 * @param array $color
747 * @param float $width
748 * @param array $style
750 public function line($x1, $y1, $x2, $y2, $color, $width, $style = null)
752 $this->_set_line_style($width, "butt", "", $style);
753 $this->_set_stroke_color($color);
755 $y1 = $this->y($y1);
756 $y2 = $this->y($y2);
758 $this->_pdf->moveto($x1, $y1);
759 $this->_pdf->lineto($x2, $y2);
760 $this->_pdf->stroke();
762 $this->_set_line_transparency("Normal", $this->_current_opacity);
766 * @param float $x1
767 * @param float $y1
768 * @param float $r1
769 * @param float $r2
770 * @param float $astart
771 * @param float $aend
772 * @param array $color
773 * @param float $width
774 * @param array $style
776 public function arc($x1, $y1, $r1, $r2, $astart, $aend, $color, $width, $style = array())
778 $this->_set_line_style($width, "butt", "", $style);
779 $this->_set_stroke_color($color);
781 $y1 = $this->y($y1);
783 $this->_pdf->arc($x1, $y1, $r1, $astart, $aend);
784 $this->_pdf->stroke();
786 $this->_set_line_transparency("Normal", $this->_current_opacity);
790 * @param float $x1
791 * @param float $y1
792 * @param float $w
793 * @param float $h
794 * @param array $color
795 * @param float $width
796 * @param null $style
798 public function rectangle($x1, $y1, $w, $h, $color, $width, $style = null)
800 $this->_set_stroke_color($color);
801 $this->_set_line_style($width, "butt", "", $style);
803 $y1 = $this->y($y1) - $h;
805 $this->_pdf->rect($x1, $y1, $w, $h);
806 $this->_pdf->stroke();
808 $this->_set_line_transparency("Normal", $this->_current_opacity);
812 * @param float $x1
813 * @param float $y1
814 * @param float $w
815 * @param float $h
816 * @param array $color
818 public function filled_rectangle($x1, $y1, $w, $h, $color)
820 $this->_set_fill_color($color);
822 $y1 = $this->y($y1) - $h;
824 $this->_pdf->rect(floatval($x1), floatval($y1), floatval($w), floatval($h));
825 $this->_pdf->fill();
827 $this->_set_fill_transparency("Normal", $this->_current_opacity);
831 * @param float $x1
832 * @param float $y1
833 * @param float $w
834 * @param float $h
836 public function clipping_rectangle($x1, $y1, $w, $h)
838 $this->_pdf->save();
840 $y1 = $this->y($y1) - $h;
842 $this->_pdf->rect(floatval($x1), floatval($y1), floatval($w), floatval($h));
843 $this->_pdf->clip();
847 * @param float $x1
848 * @param float $y1
849 * @param float $w
850 * @param float $h
851 * @param float $rTL
852 * @param float $rTR
853 * @param float $rBR
854 * @param float $rBL
856 public function clipping_roundrectangle($x1, $y1, $w, $h, $rTL, $rTR, $rBR, $rBL)
858 // @todo
859 $this->clipping_rectangle($x1, $y1, $w, $h);
865 public function clipping_end()
867 $this->_pdf->restore();
873 public function save()
875 $this->_pdf->save();
878 function restore()
880 $this->_pdf->restore();
884 * @param $angle
885 * @param $x
886 * @param $y
888 public function rotate($angle, $x, $y)
890 $pdf = $this->_pdf;
891 $pdf->translate($x, $this->_height - $y);
892 $pdf->rotate(-$angle);
893 $pdf->translate(-$x, -$this->_height + $y);
897 * @param $angle_x
898 * @param $angle_y
899 * @param $x
900 * @param $y
902 public function skew($angle_x, $angle_y, $x, $y)
904 $pdf = $this->_pdf;
905 $pdf->translate($x, $this->_height - $y);
906 $pdf->skew($angle_y, $angle_x); // Needs to be inverted
907 $pdf->translate(-$x, -$this->_height + $y);
911 * @param $s_x
912 * @param $s_y
913 * @param $x
914 * @param $y
916 public function scale($s_x, $s_y, $x, $y)
918 $pdf = $this->_pdf;
919 $pdf->translate($x, $this->_height - $y);
920 $pdf->scale($s_x, $s_y);
921 $pdf->translate(-$x, -$this->_height + $y);
925 * @param $t_x
926 * @param $t_y
928 public function translate($t_x, $t_y)
930 $this->_pdf->translate($t_x, -$t_y);
934 * @param $a
935 * @param $b
936 * @param $c
937 * @param $d
938 * @param $e
939 * @param $f
941 public function transform($a, $b, $c, $d, $e, $f)
943 $this->_pdf->concat($a, $b, $c, $d, $e, $f);
947 * @param array $points
948 * @param array $color
949 * @param null $width
950 * @param null $style
951 * @param bool $fill
953 public function polygon($points, $color, $width = null, $style = null, $fill = false)
955 $this->_set_fill_color($color);
956 $this->_set_stroke_color($color);
958 if (!$fill && isset($width)) {
959 $this->_set_line_style($width, "square", "miter", $style);
962 $y = $this->y(array_pop($points));
963 $x = array_pop($points);
964 $this->_pdf->moveto($x, $y);
966 while (count($points) > 1) {
967 $y = $this->y(array_pop($points));
968 $x = array_pop($points);
969 $this->_pdf->lineto($x, $y);
972 if ($fill) {
973 $this->_pdf->fill();
974 } else {
975 $this->_pdf->closepath_stroke();
978 $this->_set_fill_transparency("Normal", $this->_current_opacity);
979 $this->_set_line_transparency("Normal", $this->_current_opacity);
983 * @param float $x
984 * @param float $y
985 * @param float $r
986 * @param array $color
987 * @param null $width
988 * @param null $style
989 * @param bool $fill
991 public function circle($x, $y, $r, $color, $width = null, $style = null, $fill = false)
993 $this->_set_fill_color($color);
994 $this->_set_stroke_color($color);
996 if (!$fill && isset($width)) {
997 $this->_set_line_style($width, "round", "round", $style);
1000 $y = $this->y($y);
1002 $this->_pdf->circle($x, $y, $r);
1004 if ($fill) {
1005 $this->_pdf->fill();
1006 } else {
1007 $this->_pdf->stroke();
1010 $this->_set_fill_transparency("Normal", $this->_current_opacity);
1011 $this->_set_line_transparency("Normal", $this->_current_opacity);
1015 * @param string $img_url
1016 * @param float $x
1017 * @param float $y
1018 * @param int $w
1019 * @param int $h
1020 * @param string $resolution
1022 public function image($img_url, $x, $y, $w, $h, $resolution = "normal")
1024 $w = (int)$w;
1025 $h = (int)$h;
1027 $img_type = Cache::detect_type($img_url, $this->get_dompdf()->getHttpContext());
1029 if (!isset($this->_imgs[$img_url])) {
1030 $this->_imgs[$img_url] = $this->_pdf->load_image($img_type, $img_url, "");
1033 $img = $this->_imgs[$img_url];
1035 $y = $this->y($y) - $h;
1036 $this->_pdf->fit_image($img, $x, $y, 'boxsize={' . "$w $h" . '} fitmethod=entire');
1040 * @param float $x
1041 * @param float $y
1042 * @param string $text
1043 * @param string $font
1044 * @param float $size
1045 * @param array $color
1046 * @param int $word_spacing
1047 * @param int $char_spacing
1048 * @param int $angle
1050 public function text($x, $y, $text, $font, $size, $color = array(0, 0, 0), $word_spacing = 0, $char_spacing = 0, $angle = 0)
1052 $fh = $this->_load_font($font);
1054 $this->_pdf->setfont($fh, $size);
1055 $this->_set_fill_color($color);
1057 $y = $this->y($y) - $this->get_font_height($font, $size);
1059 $word_spacing = (float)$word_spacing;
1060 $char_spacing = (float)$char_spacing;
1061 $angle = -(float)$angle;
1063 $this->_pdf->fit_textline($text, $x, $y, "rotate=$angle wordspacing=$word_spacing charspacing=$char_spacing ");
1065 $this->_set_fill_transparency("Normal", $this->_current_opacity);
1069 * @param string $code
1071 public function javascript($code)
1073 if (strlen($this->_dompdf->getOptions()->getPdflibLicense()) > 0) {
1074 $this->_pdf->create_action("JavaScript", $code);
1079 * Add a named destination (similar to <a name="foo">...</a> in html)
1081 * @param string $anchorname The name of the named destination
1083 public function add_named_dest($anchorname)
1085 $this->_pdf->add_nameddest($anchorname, "");
1089 * Add a link to the pdf
1091 * @param string $url The url to link to
1092 * @param float $x The x position of the link
1093 * @param float $y The y position of the link
1094 * @param float $width The width of the link
1095 * @param float $height The height of the link
1097 public function add_link($url, $x, $y, $width, $height)
1099 $y = $this->y($y) - $height;
1100 if (strpos($url, '#') === 0) {
1101 // Local link
1102 $name = substr($url, 1);
1103 if ($name) {
1104 $this->_pdf->create_annotation($x, $y, $x + $width, $y + $height, 'Link',
1105 "contents={$url} destname=" . substr($url, 1) . " linewidth=0");
1107 } else {
1108 list($proto, $host, $path, $file) = Helpers::explode_url($url);
1110 if ($proto == "" || $proto === "file://") {
1111 return; // Local links are not allowed
1113 $url = Helpers::build_url($proto, $host, $path, $file);
1114 $url = '{' . rawurldecode($url) . '}';
1116 $action = $this->_pdf->create_action("URI", "url=" . $url);
1117 $this->_pdf->create_annotation($x, $y, $x + $width, $y + $height, 'Link', "contents={$url} action={activate=$action} linewidth=0");
1122 * @param string $text
1123 * @param string $font
1124 * @param float $size
1125 * @param int $word_spacing
1126 * @param int $letter_spacing
1127 * @return mixed
1129 public function get_text_width($text, $font, $size, $word_spacing = 0, $letter_spacing = 0)
1131 $fh = $this->_load_font($font);
1133 // Determine the additional width due to extra spacing
1134 $num_spaces = mb_substr_count($text, " ");
1135 $delta = $word_spacing * $num_spaces;
1137 if ($letter_spacing) {
1138 $num_chars = mb_strlen($text);
1139 $delta += ($num_chars - $num_spaces) * $letter_spacing;
1142 return $this->_pdf->stringwidth($text, $fh, $size) + $delta;
1146 * @param string $font
1147 * @param float $size
1148 * @return float
1150 public function get_font_height($font, $size)
1152 $fh = $this->_load_font($font);
1154 $this->_pdf->setfont($fh, $size);
1156 $asc = $this->_pdf->get_value("ascender", $fh);
1157 $desc = $this->_pdf->get_value("descender", $fh);
1159 // $desc is usually < 0,
1160 $ratio = $this->_dompdf->getOptions()->getFontHeightRatio();
1161 return $size * ($asc - $desc) * $ratio;
1165 * @param string $font
1166 * @param float $size
1167 * @return float
1169 public function get_font_baseline($font, $size)
1171 $ratio = $this->_dompdf->getOptions()->getFontHeightRatio();
1172 return $this->get_font_height($font, $size) / $ratio * 1.1;
1176 * Writes text at the specified x and y coordinates on every page
1178 * The strings '{PAGE_NUM}' and '{PAGE_COUNT}' are automatically replaced
1179 * with their current values.
1181 * See {@link Style::munge_color()} for the format of the color array.
1183 * @param float $x
1184 * @param float $y
1185 * @param string $text the text to write
1186 * @param string $font the font file to use
1187 * @param float $size the font size, in points
1188 * @param array $color
1189 * @param float $word_space word spacing adjustment
1190 * @param float $char_space char spacing adjustment
1191 * @param float $angle angle to write the text at, measured CW starting from the x-axis
1193 public function page_text($x, $y, $text, $font, $size, $color = array(0, 0, 0), $word_space = 0.0, $char_space = 0.0, $angle = 0.0)
1195 $_t = "text";
1196 $this->_page_text[] = compact("_t", "x", "y", "text", "font", "size", "color", "word_space", "char_space", "angle");
1199 //........................................................................
1202 * Processes a script on every page
1204 * The variables $pdf, $PAGE_NUM, and $PAGE_COUNT are available.
1206 * This function can be used to add page numbers to all pages
1207 * after the first one, for example.
1209 * @param string $code the script code
1210 * @param string $type the language type for script
1212 public function page_script($code, $type = "text/php")
1214 $_t = "script";
1215 $this->_page_text[] = compact("_t", "code", "type");
1221 public function new_page()
1223 // Add objects to the current page
1224 $this->_place_objects();
1226 $this->_pdf->suspend_page("");
1227 $this->_pdf->begin_page_ext($this->_width, $this->_height, "");
1228 $this->_page_number = ++$this->_page_count;
1232 * Add text to each page after rendering is complete
1234 protected function _add_page_text()
1236 if (!count($this->_page_text)) {
1237 return;
1240 $eval = null;
1241 $this->_pdf->suspend_page("");
1243 for ($p = 1; $p <= $this->_page_count; $p++) {
1244 $this->_pdf->resume_page("pagenumber=$p");
1246 foreach ($this->_page_text as $pt) {
1247 extract($pt);
1249 switch ($_t) {
1250 case "text":
1251 $text = str_replace(array("{PAGE_NUM}", "{PAGE_COUNT}"),
1252 array($p, $this->_page_count), $text);
1253 $this->text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
1254 break;
1256 case "script":
1257 if (!$eval) {
1258 $eval = new PHPEvaluator($this);
1260 $eval->evaluate($code, array('PAGE_NUM' => $p, 'PAGE_COUNT' => $this->_page_count));
1261 break;
1265 $this->_pdf->suspend_page("");
1268 $this->_pdf->resume_page("pagenumber=" . $this->_page_number);
1272 * Streams the PDF to the client.
1274 * @param string $filename The filename to present to the client.
1275 * @param array $options Associative array: 'compress' => 1 or 0 (default 1); 'Attachment' => 1 or 0 (default 1).
1276 * @throws Exception
1278 public function stream($filename = "document.pdf", $options = array())
1280 if (headers_sent()) {
1281 die("Unable to stream pdf: headers already sent");
1284 if (!isset($options["compress"])) $options["compress"] = true;
1285 if (!isset($options["Attachment"])) $options["Attachment"] = true;
1287 $this->_add_page_text();
1289 if ($options["compress"]) {
1290 $this->_pdf->set_value("compress", 6);
1291 } else {
1292 $this->_pdf->set_value("compress", 0);
1295 $this->_close();
1297 $data = "";
1299 if (self::$IN_MEMORY) {
1300 $data = $this->_pdf->get_buffer();
1301 $size = mb_strlen($data, "8bit");
1302 } else {
1303 $size = filesize($this->_file);
1306 header("Cache-Control: private");
1307 header("Content-Type: application/pdf");
1308 header("Content-Length: " . $size);
1310 $filename = str_replace(array("\n", "'"), "", basename($filename, ".pdf")) . ".pdf";
1311 $attachment = $options["Attachment"] ? "attachment" : "inline";
1312 header(Helpers::buildContentDispositionHeader($attachment, $filename));
1314 if (self::$IN_MEMORY) {
1315 echo $data;
1316 } else {
1317 // Chunked readfile()
1318 $chunk = (1 << 21); // 2 MB
1319 $fh = fopen($this->_file, "rb");
1320 if (!$fh) {
1321 throw new Exception("Unable to load temporary PDF file: " . $this->_file);
1324 while (!feof($fh)) {
1325 echo fread($fh, $chunk);
1327 fclose($fh);
1329 //debugpng
1330 if ($this->_dompdf->getOptions()->getDebugPng()) {
1331 print '[pdflib stream unlink ' . $this->_file . ']';
1333 if (!$this->_dompdf->getOptions()->getDebugKeepTemp()) {
1334 unlink($this->_file);
1336 $this->_file = null;
1337 unset($this->_file);
1340 flush();
1344 * Returns the PDF as a string.
1346 * @param array $options Associative array: 'compress' => 1 or 0 (default 1).
1347 * @return string
1349 public function output($options = array())
1351 if (!isset($options["compress"])) $options["compress"] = true;
1353 $this->_add_page_text();
1355 if ($options["compress"]) {
1356 $this->_pdf->set_value("compress", 6);
1357 } else {
1358 $this->_pdf->set_value("compress", 0);
1361 $this->_close();
1363 if (self::$IN_MEMORY) {
1364 $data = $this->_pdf->get_buffer();
1365 } else {
1366 $data = file_get_contents($this->_file);
1368 //debugpng
1369 if ($this->_dompdf->getOptions()->getDebugPng()) {
1370 print '[pdflib output unlink ' . $this->_file . ']';
1372 if (!$this->_dompdf->getOptions()->getDebugKeepTemp()) {
1373 unlink($this->_file);
1375 $this->_file = null;
1376 unset($this->_file);
1379 return $data;
1383 // Workaround for idiotic limitation on statics...
1384 PDFLib::$PAPER_SIZES = CPDF::$PAPER_SIZES;