4 * @link http://dompdf.github.com/
5 * @author Benj Carson <benjcarson@digitaljunkies.ca>
6 * @author Fabien Ménager <fabien.menager@gmail.com>
7 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
9 namespace Dompdf\Adapter
;
13 use Dompdf\Image\Cache
;
17 * Image rendering interface
19 * Renders to an image format supported by GD (jpeg, gif, png, xpm).
20 * Not super-useful day-to-day but handy nonetheless
24 class GD
implements Canvas
32 * Resource handle for the image
39 * Resource handle for the image
46 * Apparent canvas width in pixels
53 * Apparent canvas height in pixels
60 * Actual image width in pixels
64 private $_actual_width;
67 * Actual image height in pixels
71 private $_actual_height;
78 private $_page_number;
81 * Total number of pages
88 * Image antialias factor
109 * Background color array
113 private $_bg_color_array;
123 * Amount to scale font sizes
125 * Font sizes are 72 DPI, GD internally uses 96. Scale them proportionally.
130 const FONT_SCALE
= 0.75;
135 * @param mixed $size The size of image to create: array(x1,y1,x2,y2) or "letter", "legal", etc.
136 * @param string $orientation The orientation of the document (either 'landscape' or 'portrait')
137 * @param Dompdf $dompdf
138 * @param float $aa_factor Anti-aliasing factor, 1 for no AA
139 * @param array $bg_color Image background color: array(r,g,b,a), 0 <= r,g,b,a <= 1
141 public function __construct($size = 'letter', $orientation = "portrait", Dompdf
$dompdf, $aa_factor = 1.0, $bg_color = array(1, 1, 1, 0))
144 if (!is_array($size)) {
145 $size = strtolower($size);
147 if (isset(CPDF
::$PAPER_SIZES[$size])) {
148 $size = CPDF
::$PAPER_SIZES[$size];
150 $size = CPDF
::$PAPER_SIZES["letter"];
154 if (strtolower($orientation) === "landscape") {
155 list($size[2], $size[3]) = array($size[3], $size[2]);
158 $this->_dompdf
= $dompdf;
160 $this->dpi
= $this->get_dompdf()->getOptions()->getDpi();
162 if ($aa_factor < 1) {
166 $this->_aa_factor
= $aa_factor;
168 $size[2] *= $aa_factor;
169 $size[3] *= $aa_factor;
171 $this->_width
= $size[2] - $size[0];
172 $this->_height
= $size[3] - $size[1];
174 $this->_actual_width
= $this->_upscale($this->_width
);
175 $this->_actual_height
= $this->_upscale($this->_height
);
177 if (is_null($bg_color) ||
!is_array($bg_color)) {
179 $bg_color = array(1, 1, 1, 0);
182 $this->_bg_color_array
= $bg_color;
190 public function get_dompdf()
192 return $this->_dompdf
;
196 * Return the GF image resource
200 public function get_image()
206 * Return the image's width in pixels
210 public function get_width()
212 return $this->_width
/ $this->_aa_factor
;
216 * Return the image's height in pixels
220 public function get_height()
222 return $this->_height
/ $this->_aa_factor
;
226 * Returns the current page number
229 public function get_page_number()
231 return $this->_page_number
;
235 * Returns the total number of pages in the document
238 public function get_page_count()
240 return $this->_page_count
;
244 * Sets the current page number
248 public function set_page_number($num)
250 $this->_page_number
= $num;
254 * Sets the page count
258 public function set_page_count($count)
260 $this->_page_count
= $count;
269 public function set_opacity($opacity, $mode = "Normal")
275 * Allocate a new color. Allocate with GD as needed and store
276 * previously allocated colors in $this->_colors.
278 * @param array $color The new current color
279 * @return int The allocated color
281 private function _allocate_color($color)
283 $a = isset($color["alpha"]) ?
$color["alpha"] : 1;
285 if (isset($color["c"])) {
286 $color = Helpers
::cmyk_to_rgb($color);
289 list($r, $g, $b) = $color;
294 $a = 127 - ($a * 127);
297 $r = $r > 255 ?
255 : $r;
298 $g = $g > 255 ?
255 : $g;
299 $b = $b > 255 ?
255 : $b;
300 $a = $a > 127 ?
127 : $a;
302 $r = $r < 0 ?
0 : $r;
303 $g = $g < 0 ?
0 : $g;
304 $b = $b < 0 ?
0 : $b;
305 $a = $a < 0 ?
0 : $a;
307 $key = sprintf("#%02X%02X%02X%02X", $r, $g, $b, $a);
309 if (isset($this->_colors
[$key])) {
310 return $this->_colors
[$key];
314 $this->_colors
[$key] = imagecolorallocatealpha($this->get_image(), $r, $g, $b, $a);
316 $this->_colors
[$key] = imagecolorallocate($this->get_image(), $r, $g, $b);
319 return $this->_colors
[$key];
323 * Scales value up to the current canvas DPI from 72 DPI
325 * @param float $length
328 private function _upscale($length)
330 return ($length * $this->dpi
) / 72 * $this->_aa_factor
;
334 * Scales value down from the current canvas DPI to 72 DPI
336 * @param float $length
339 private function _downscale($length)
341 return ($length / $this->dpi
* 72) / $this->_aa_factor
;
345 * Draws a line from x1,y1 to x2,y2
347 * See {@link Style::munge_color()} for the format of the color array.
348 * See {@link Cpdf::setLineStyle()} for a description of the format of the
349 * $style parameter (aka dash).
355 * @param array $color
356 * @param float $width
357 * @param array $style
359 public function line($x1, $y1, $x2, $y2, $color, $width, $style = null)
362 // Scale by the AA factor and DPI
363 $x1 = $this->_upscale($x1);
364 $y1 = $this->_upscale($y1);
365 $x2 = $this->_upscale($x2);
366 $y2 = $this->_upscale($y2);
367 $width = $this->_upscale($width);
369 $c = $this->_allocate_color($color);
371 // Convert the style array if required
372 if (is_array($style) && count($style) > 0) {
375 if (count($style) == 1) {
376 for ($i = 0; $i < $style[0] * $this->_aa_factor
; $i++
) {
380 for ($i = 0; $i < $style[0] * $this->_aa_factor
; $i++
) {
381 $gd_style[] = $this->_bg_color
;
385 foreach ($style as $length) {
388 for ($i = 0; $i < $style[0] * $this->_aa_factor
; $i++
) {
394 for ($i = 0; $i < $style[0] * $this->_aa_factor
; $i++
) {
395 $gd_style[] = $this->_bg_color
;
402 if (!empty($gd_style)) {
403 imagesetstyle($this->get_image(), $gd_style);
404 $c = IMG_COLOR_STYLED
;
408 imagesetthickness($this->get_image(), $width);
410 imageline($this->get_image(), $x1, $y1, $x2, $y2, $c);
418 * @param float $astart
420 * @param array $color
421 * @param float $width
422 * @param array $style
424 public function arc($x1, $y1, $r1, $r2, $astart, $aend, $color, $width, $style = array())
430 * Draws a rectangle at x1,y1 with width w and height h
432 * See {@link Style::munge_color()} for the format of the color array.
433 * See {@link Cpdf::setLineStyle()} for a description of the $style
434 * parameter (aka dash)
440 * @param array $color
441 * @param float $width
442 * @param array $style
444 public function rectangle($x1, $y1, $w, $h, $color, $width, $style = null)
447 // Scale by the AA factor and DPI
448 $x1 = $this->_upscale($x1);
449 $y1 = $this->_upscale($y1);
450 $w = $this->_upscale($w);
451 $h = $this->_upscale($h);
452 $width = $this->_upscale($width);
454 $c = $this->_allocate_color($color);
456 // Convert the style array if required
457 if (is_array($style) && count($style) > 0) {
460 foreach ($style as $length) {
461 for ($i = 0; $i < $length; $i++
) {
466 if (!empty($gd_style)) {
467 imagesetstyle($this->get_image(), $gd_style);
468 $c = IMG_COLOR_STYLED
;
472 imagesetthickness($this->get_image(), $width);
474 imagerectangle($this->get_image(), $x1, $y1, $x1 +
$w, $y1 +
$h, $c);
478 * Draws a filled rectangle at x1,y1 with width w and height h
480 * See {@link Style::munge_color()} for the format of the color array.
486 * @param array $color
488 public function filled_rectangle($x1, $y1, $w, $h, $color)
490 // Scale by the AA factor and DPI
491 $x1 = $this->_upscale($x1);
492 $y1 = $this->_upscale($y1);
493 $w = $this->_upscale($w);
494 $h = $this->_upscale($h);
496 $c = $this->_allocate_color($color);
498 imagefilledrectangle($this->get_image(), $x1, $y1, $x1 +
$w, $y1 +
$h, $c);
502 * Starts a clipping rectangle at x1,y1 with width w and height h
509 public function clipping_rectangle($x1, $y1, $w, $h)
514 public function clipping_roundrectangle($x1, $y1, $w, $h, $rTL, $rTR, $rBR, $rBL)
520 * Ends the last clipping shape
522 public function clipping_end()
530 public function save()
532 $this->get_dompdf()->getOptions()->setDpi(72);
538 public function restore()
540 $this->get_dompdf()->getOptions()->setDpi($this->dpi
);
548 public function rotate($angle, $x, $y)
559 public function skew($angle_x, $angle_y, $x, $y)
570 public function scale($s_x, $s_y, $x, $y)
579 public function translate($t_x, $t_y)
592 public function transform($a, $b, $c, $d, $e, $f)
600 * The polygon is formed by joining all the points stored in the $points
601 * array. $points has the following structure:
611 * See {@link Style::munge_color()} for the format of the color array.
612 * See {@link Cpdf::setLineStyle()} for a description of the $style
613 * parameter (aka dash)
615 * @param array $points
616 * @param array $color
617 * @param float $width
618 * @param array $style
619 * @param bool $fill Fills the polygon if true
621 public function polygon($points, $color, $width = null, $style = null, $fill = false)
624 // Scale each point by the AA factor and DPI
625 foreach (array_keys($points) as $i) {
626 $points[$i] = $this->_upscale($points[$i]);
629 $c = $this->_allocate_color($color);
631 // Convert the style array if required
632 if (is_array($style) && count($style) > 0 && !$fill) {
635 foreach ($style as $length) {
636 for ($i = 0; $i < $length; $i++
) {
641 if (!empty($gd_style)) {
642 imagesetstyle($this->get_image(), $gd_style);
643 $c = IMG_COLOR_STYLED
;
647 imagesetthickness($this->get_image(), $width);
650 imagefilledpolygon($this->get_image(), $points, count($points) / 2, $c);
652 imagepolygon($this->get_image(), $points, count($points) / 2, $c);
657 * Draws a circle at $x,$y with radius $r
659 * See {@link Style::munge_color()} for the format of the color array.
660 * See {@link Cpdf::setLineStyle()} for a description of the $style
661 * parameter (aka dash)
666 * @param array $color
667 * @param float $width
668 * @param array $style
669 * @param bool $fill Fills the circle if true
671 public function circle($x, $y, $r, $color, $width = null, $style = null, $fill = false)
673 // Scale by the AA factor and DPI
674 $x = $this->_upscale($x);
675 $y = $this->_upscale($y);
676 $r = $this->_upscale($r);
678 $c = $this->_allocate_color($color);
680 // Convert the style array if required
681 if (is_array($style) && count($style) > 0 && !$fill) {
684 foreach ($style as $length) {
685 for ($i = 0; $i < $length; $i++
) {
690 if (!empty($gd_style)) {
691 imagesetstyle($this->get_image(), $gd_style);
692 $c = IMG_COLOR_STYLED
;
696 imagesetthickness($this->get_image(), $width);
699 imagefilledellipse($this->get_image(), $x, $y, $r, $r, $c);
701 imageellipse($this->get_image(), $x, $y, $r, $r, $c);
706 * Add an image to the pdf.
707 * The image is placed at the specified x and y coordinates with the
708 * given width and height.
710 * @param string $img_url the path to the image
711 * @param float $x x position
712 * @param float $y y position
713 * @param int $w width (in pixels)
714 * @param int $h height (in pixels)
715 * @param string $resolution
719 * @internal param string $img_type the type (e.g. extension) of the image
721 public function image($img_url, $x, $y, $w, $h, $resolution = "normal")
723 $img_type = Cache
::detect_type($img_url, $this->get_dompdf()->getHttpContext());
729 $func_name = "imagecreatefrom$img_type";
730 if (!function_exists($func_name)) {
731 if (!method_exists("Dompdf\Helpers", $func_name)) {
732 throw new \
Exception("Function $func_name() not found. Cannot convert $type image: $img_url. Please install the image PHP extension.");
734 $func_name = "\\Dompdf\\Helpers::" . $func_name;
736 $src = @call_user_func
($func_name, $img_url);
739 return; // Probably should add to $_dompdf_errors or whatever here
742 // Scale by the AA factor and DPI
743 $x = $this->_upscale($x);
744 $y = $this->_upscale($y);
746 $w = $this->_upscale($w);
747 $h = $this->_upscale($h);
749 $img_w = imagesx($src);
750 $img_h = imagesy($src);
752 imagecopyresampled($this->get_image(), $src, $x, $y, 0, 0, $w, $h, $img_w, $img_h);
756 * Writes text at the specified x and y coordinates
757 * See {@link Style::munge_color()} for the format of the color array.
761 * @param string $text the text to write
762 * @param string $font the font file to use
763 * @param float $size the font size, in points
764 * @param array $color
765 * @param float $word_spacing word spacing adjustment
766 * @param float $char_spacing
767 * @param float $angle Text angle
771 public function text($x, $y, $text, $font, $size, $color = array(0, 0, 0), $word_spacing = 0.0, $char_spacing = 0.0, $angle = 0.0)
773 // Scale by the AA factor and DPI
774 $x = $this->_upscale($x);
775 $y = $this->_upscale($y);
776 $size = $this->_upscale($size) * self
::FONT_SCALE
;
778 $h = $this->get_font_height_actual($font, $size);
779 $c = $this->_allocate_color($color);
781 // imagettftext() converts numeric entities to their respective
782 // character. Preserve any originally double encoded entities to be
783 // represented as is.
784 // eg: &#160; will render   rather than its character.
785 $text = preg_replace('/&(#(?:x[a-fA-F0-9]+|[0-9]+);)/', '&\1', $text);
787 $text = mb_encode_numericentity($text, array(0x0080, 0xff, 0, 0xff), 'UTF-8');
789 $font = $this->get_ttf_file($font);
791 // FIXME: word spacing
792 imagettftext($this->get_image(), $size, $angle, $x, $y +
$h, $c, $font, $text);
795 public function javascript($code)
801 * Add a named destination (similar to <a name="foo">...</a> in html)
803 * @param string $anchorname The name of the named destination
805 public function add_named_dest($anchorname)
811 * Add a link to the pdf
813 * @param string $url The url to link to
814 * @param float $x The x position of the link
815 * @param float $y The y position of the link
816 * @param float $width The width of the link
817 * @param float $height The height of the link
819 public function add_link($url, $x, $y, $width, $height)
825 * Add meta information to the PDF
827 * @param string $label label of the value (Creator, Producer, etc.)
828 * @param string $value the text to set
830 public function add_info($label, $value)
836 * @param string $view
837 * @param array $options
839 public function set_default_view($view, $options = array())
845 * Calculates text size, in points
847 * @param string $text the text to be sized
848 * @param string $font the desired font
849 * @param float $size the desired font size
850 * @param float $word_spacing word spacing, if any
851 * @param float $char_spacing char spacing, if any
855 public function get_text_width($text, $font, $size, $word_spacing = 0.0, $char_spacing = 0.0)
857 $font = $this->get_ttf_file($font);
858 $size = $this->_upscale($size) * self
::FONT_SCALE
;
860 // imagettfbbox() converts numeric entities to their respective
861 // character. Preserve any originally double encoded entities to be
862 // represented as is.
863 // eg: &#160; will render   rather than its character.
864 $text = preg_replace('/&(#(?:x[a-fA-F0-9]+|[0-9]+);)/', '&\1', $text);
866 $text = mb_encode_numericentity($text, array(0x0080, 0xffff, 0, 0xffff), 'UTF-8');
868 // FIXME: word spacing
869 list($x1, , $x2) = imagettfbbox($size, 0, $font, $text);
871 // Add additional 1pt to prevent text overflow issues
872 return $this->_downscale($x2 - $x1) +
1;
879 public function get_ttf_file($font)
881 if ( stripos($font, ".ttf") === false ) {
885 if (!file_exists($font)) {
886 $font_metrics = $this->_dompdf
->getFontMetrics();
887 $font = $font_metrics->getFont($this->_dompdf
->getOptions()->getDefaultFont()) . ".ttf";
888 if (!file_exists($font)) {
889 if (strpos($font, "mono")) {
890 $font = $font_metrics->getFont("DejaVu Mono") . ".ttf";
891 } elseif (strpos($font, "sans") !== false) {
892 $font = $font_metrics->getFont("DejaVu Sans") . ".ttf";
893 } elseif (strpos($font, "serif")) {
894 $font = $font_metrics->getFont("DejaVu Serif") . ".ttf";
896 $font = $font_metrics->getFont("DejaVu Sans") . ".ttf";
905 * Calculates font height, in points
907 * @param string $font
911 public function get_font_height($font, $size)
913 $size = $this->_upscale($size) * self
::FONT_SCALE
;
915 $height = $this->get_font_height_actual($font, $size);
917 return $this->_downscale($height);
920 private function get_font_height_actual($font, $size)
922 $font = $this->get_ttf_file($font);
923 $ratio = $this->_dompdf
->getOptions()->getFontHeightRatio();
925 // FIXME: word spacing
926 list(, $y2, , , , $y1) = imagettfbbox($size, 0, $font, "MXjpqytfhl"); // Test string with ascenders, descenders and caps
927 return ($y2 - $y1) * $ratio;
931 * @param string $font
935 public function get_font_baseline($font, $size)
937 $ratio = $this->_dompdf
->getOptions()->getFontHeightRatio();
938 return $this->get_font_height($font, $size) / $ratio;
944 * Subsequent drawing operations will appear on the new page.
946 public function new_page()
948 $this->_page_number++
;
949 $this->_page_count++
;
951 $this->_img
= imagecreatetruecolor($this->_actual_width
, $this->_actual_height
);
953 $this->_bg_color
= $this->_allocate_color($this->_bg_color_array
);
954 imagealphablending($this->_img
, true);
955 imagesavealpha($this->_img
, true);
956 imagefill($this->_img
, 0, 0, $this->_bg_color
);
958 $this->_imgs
[] = $this->_img
;
961 public function open_object()
966 public function close_object()
971 public function add_object()
976 public function page_text()
982 * Streams the image to the client.
984 * @param string $filename The filename to present to the client.
985 * @param array $options Associative array: 'type' => jpeg|jpg|png; 'quality' => 0 - 100 (JPEG only);
986 * 'page' => Number of the page to output (defaults to the first); 'Attachment': 1 or 0 (default 1).
988 public function stream($filename, $options = array())
990 if (headers_sent()) {
991 die("Unable to stream image: headers already sent");
994 if (!isset($options["type"])) $options["type"] = "png";
995 if (!isset($options["Attachment"])) $options["Attachment"] = true;
996 $type = strtolower($options["type"]);
1001 $contentType = "image/jpeg";
1002 $extension = ".jpg";
1006 $contentType = "image/png";
1007 $extension = ".png";
1011 header("Cache-Control: private");
1012 header("Content-Type: $contentType");
1014 $filename = str_replace(array("\n", "'"), "", basename($filename, ".$type")) . $extension;
1015 $attachment = $options["Attachment"] ?
"attachment" : "inline";
1016 header(Helpers
::buildContentDispositionHeader($attachment, $filename));
1018 $this->_output($options);
1023 * Returns the image as a string.
1025 * @param array $options Associative array: 'type' => jpeg|jpg|png; 'quality' => 0 - 100 (JPEG only);
1026 * 'page' => Number of the page to output (defaults to the first).
1029 public function output($options = array())
1033 $this->_output($options);
1035 return ob_get_clean();
1039 * Outputs the image stream directly.
1041 * @param array $options Associative array: 'type' => jpeg|jpg|png; 'quality' => 0 - 100 (JPEG only);
1042 * 'page' => Number of the page to output (defaults to the first).
1044 private function _output($options = array())
1046 if (!isset($options["type"])) $options["type"] = "png";
1047 if (!isset($options["page"])) $options["page"] = 1;
1048 $type = strtolower($options["type"]);
1050 if (isset($this->_imgs
[$options["page"] - 1])) {
1051 $img = $this->_imgs
[$options["page"] - 1];
1053 $img = $this->_imgs
[0];
1056 // Perform any antialiasing
1057 if ($this->_aa_factor
!= 1) {
1058 $dst_w = $this->_actual_width
/ $this->_aa_factor
;
1059 $dst_h = $this->_actual_height
/ $this->_aa_factor
;
1060 $dst = imagecreatetruecolor($dst_w, $dst_h);
1061 imagecopyresampled($dst, $img, 0, 0, 0, 0,
1063 $this->_actual_width
, $this->_actual_height
);
1071 if (!isset($options["quality"])) {
1072 $options["quality"] = 75;
1075 imagejpeg($dst, null, $options["quality"]);
1083 if ($this->_aa_factor
!= 1) {