4 * @link http://dompdf.github.com/
5 * @author Benj Carson <benjcarson@digitaljunkies.ca>
6 * @author Orion Richardson <orionr@yahoo.com>
7 * @author Helmut Tischer <htischer@weihenstephan.org>
8 * @author Fabien Ménager <fabien.menager@gmail.com>
9 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
12 // FIXME: Need to sanity check inputs to this class
13 namespace Dompdf\Adapter
;
19 use Dompdf\Image\Cache
;
20 use Dompdf\PhpEvaluator
;
23 * PDF rendering interface
25 * Dompdf\Adapter\CPDF provides a simple stateless interface to the stateful one
26 * provided by the Cpdf class.
28 * Unless otherwise mentioned, all dimensions are in points (1/72 in). The
29 * coordinate origin is in the top left corner, and y values increase
32 * See {@link http://www.ros.co.nz/pdf/} for more complete documentation
33 * on the underlying {@link Cpdf} class.
37 class CPDF
implements Canvas
41 * Dimensions of paper sizes in points
45 static $PAPER_SIZES = array(
46 "4a0" => array(0, 0, 4767.87, 6740.79),
47 "2a0" => array(0, 0, 3370.39, 4767.87),
48 "a0" => array(0, 0, 2383.94, 3370.39),
49 "a1" => array(0, 0, 1683.78, 2383.94),
50 "a2" => array(0, 0, 1190.55, 1683.78),
51 "a3" => array(0, 0, 841.89, 1190.55),
52 "a4" => array(0, 0, 595.28, 841.89),
53 "a5" => array(0, 0, 419.53, 595.28),
54 "a6" => array(0, 0, 297.64, 419.53),
55 "a7" => array(0, 0, 209.76, 297.64),
56 "a8" => array(0, 0, 147.40, 209.76),
57 "a9" => array(0, 0, 104.88, 147.40),
58 "a10" => array(0, 0, 73.70, 104.88),
59 "b0" => array(0, 0, 2834.65, 4008.19),
60 "b1" => array(0, 0, 2004.09, 2834.65),
61 "b2" => array(0, 0, 1417.32, 2004.09),
62 "b3" => array(0, 0, 1000.63, 1417.32),
63 "b4" => array(0, 0, 708.66, 1000.63),
64 "b5" => array(0, 0, 498.90, 708.66),
65 "b6" => array(0, 0, 354.33, 498.90),
66 "b7" => array(0, 0, 249.45, 354.33),
67 "b8" => array(0, 0, 175.75, 249.45),
68 "b9" => array(0, 0, 124.72, 175.75),
69 "b10" => array(0, 0, 87.87, 124.72),
70 "c0" => array(0, 0, 2599.37, 3676.54),
71 "c1" => array(0, 0, 1836.85, 2599.37),
72 "c2" => array(0, 0, 1298.27, 1836.85),
73 "c3" => array(0, 0, 918.43, 1298.27),
74 "c4" => array(0, 0, 649.13, 918.43),
75 "c5" => array(0, 0, 459.21, 649.13),
76 "c6" => array(0, 0, 323.15, 459.21),
77 "c7" => array(0, 0, 229.61, 323.15),
78 "c8" => array(0, 0, 161.57, 229.61),
79 "c9" => array(0, 0, 113.39, 161.57),
80 "c10" => array(0, 0, 79.37, 113.39),
81 "ra0" => array(0, 0, 2437.80, 3458.27),
82 "ra1" => array(0, 0, 1729.13, 2437.80),
83 "ra2" => array(0, 0, 1218.90, 1729.13),
84 "ra3" => array(0, 0, 864.57, 1218.90),
85 "ra4" => array(0, 0, 609.45, 864.57),
86 "sra0" => array(0, 0, 2551.18, 3628.35),
87 "sra1" => array(0, 0, 1814.17, 2551.18),
88 "sra2" => array(0, 0, 1275.59, 1814.17),
89 "sra3" => array(0, 0, 907.09, 1275.59),
90 "sra4" => array(0, 0, 637.80, 907.09),
91 "letter" => array(0, 0, 612.00, 792.00),
92 "legal" => array(0, 0, 612.00, 1008.00),
93 "ledger" => array(0, 0, 1224.00, 792.00),
94 "tabloid" => array(0, 0, 792.00, 1224.00),
95 "executive" => array(0, 0, 521.86, 756.00),
96 "folio" => array(0, 0, 612.00, 936.00),
97 "commercial #10 envelope" => array(0, 0, 684, 297),
98 "catalog #10 1/2 envelope" => array(0, 0, 648, 864),
99 "8.5x11" => array(0, 0, 612.00, 792.00),
100 "8.5x14" => array(0, 0, 612.00, 1008.0),
101 "11x17" => array(0, 0, 792.00, 1224.00),
112 * Instance of Cpdf class
119 * PDF width, in points
126 * PDF height, in points
133 * Current page number
137 private $_page_number;
140 * Total number of pages
144 private $_page_count;
147 * Text to display on every page
154 * Array of pages for accesing after rendering is initially complete
161 * Array of temporary cached images to be deleted when processing is complete
165 private $_image_cache;
170 * @param mixed $paper The size of paper to use in this PDF ({@link CPDF::$PAPER_SIZES})
171 * @param string $orientation The orientation of the document (either 'landscape' or 'portrait')
172 * @param Dompdf $dompdf The Dompdf instance
174 function __construct($paper = "letter", $orientation = "portrait", Dompdf
$dompdf)
176 if (is_array($paper)) {
178 } else if (isset(self
::$PAPER_SIZES[mb_strtolower($paper)])) {
179 $size = self
::$PAPER_SIZES[mb_strtolower($paper)];
181 $size = self
::$PAPER_SIZES["letter"];
184 if (mb_strtolower($orientation) === "landscape") {
185 list($size[2], $size[3]) = array($size[3], $size[2]);
188 $this->_dompdf
= $dompdf;
190 $this->_pdf
= new \
Cpdf(
193 $dompdf->get_option("font_cache"),
194 $dompdf->get_option("temp_dir")
197 $this->_pdf
->addInfo("Producer", sprintf("%s + CPDF", $dompdf->version
));
198 $time = substr_replace(date('YmdHisO'), '\'', -2, 0) . '\'';
199 $this->_pdf
->addInfo("CreationDate", "D:$time");
200 $this->_pdf
->addInfo("ModDate", "D:$time");
202 $this->_width
= $size[2] - $size[0];
203 $this->_height
= $size[3] - $size[1];
205 $this->_page_number
= $this->_page_count
= 1;
206 $this->_page_text
= array();
208 $this->_pages
= array($this->_pdf
->getFirstPageId());
210 $this->_image_cache
= array();
213 function get_dompdf()
215 return $this->_dompdf
;
221 * Deletes all temporary image files
223 function __destruct()
225 foreach ($this->_image_cache
as $img) {
226 // The file might be already deleted by 3rd party tmp cleaner,
227 // the file might not have been created at all
228 // (if image outputting commands failed)
229 // or because the destructor was called twice accidentally.
230 if (!file_exists($img)) {
234 if ($this->_dompdf
->get_option("debugPng")) print '[__destruct unlink ' . $img . ']';
235 if (!$this->_dompdf
->get_option("debugKeepTemp")) unlink($img);
240 * Returns the Cpdf instance
250 * Add meta information to the PDF
252 * @param string $label label of the value (Creator, Producer, etc.)
253 * @param string $value the text to set
255 function add_info($label, $value)
257 $this->_pdf
->addInfo($label, $value);
261 * Opens a new 'object'
263 * While an object is open, all drawing actions are recored in the object,
264 * as opposed to being drawn on the current page. Objects can be added
265 * later to a specific page or to several pages.
267 * The return value is an integer ID for the new object.
269 * @see CPDF_Adapter::close_object()
270 * @see CPDF_Adapter::add_object()
274 function open_object()
276 $ret = $this->_pdf
->openObject();
277 $this->_pdf
->saveState();
282 * Reopens an existing 'object'
284 * @see CPDF_Adapter::open_object()
285 * @param int $object the ID of a previously opened object
287 function reopen_object($object)
289 $this->_pdf
->reopenObject($object);
290 $this->_pdf
->saveState();
294 * Closes the current 'object'
296 * @see CPDF_Adapter::open_object()
298 function close_object()
300 $this->_pdf
->restoreState();
301 $this->_pdf
->closeObject();
305 * Adds a specified 'object' to the document
307 * $object int specifying an object created with {@link
308 * CPDF::open_object()}. $where can be one of:
309 * - 'add' add to current page only
310 * - 'all' add to every page from the current one onwards
311 * - 'odd' add to all odd numbered pages from now on
312 * - 'even' add to all even numbered pages from now on
313 * - 'next' add the object to the next page only
314 * - 'nextodd' add to all odd numbered pages from the next one
315 * - 'nexteven' add to all even numbered pages from the next one
317 * @see Cpdf::addObject()
320 * @param string $where
322 function add_object($object, $where = 'all')
324 $this->_pdf
->addObject($object, $where);
328 * Stops the specified 'object' from appearing in the document.
330 * The object will stop being displayed on the page following the current
335 function stop_object($object)
337 $this->_pdf
->stopObject($object);
343 function serialize_object($id)
345 // Serialize the pdf object's current state for retrieval later
346 return $this->_pdf
->serializeObject($id);
352 function reopen_serialized_object($obj)
354 return $this->_pdf
->restoreSerializedObject($obj);
357 //........................................................................
360 * Returns the PDF's width in points
365 return $this->_width
;
369 * Returns the PDF's height in points
372 function get_height()
374 return $this->_height
;
378 * Returns the current page number
381 function get_page_number()
383 return $this->_page_number
;
387 * Returns the total number of pages in the document
390 function get_page_count()
392 return $this->_page_count
;
396 * Sets the current page number
400 function set_page_number($num)
402 $this->_page_number
= $num;
406 * Sets the page count
410 function set_page_count($count)
412 $this->_page_count
= $count;
416 * Sets the stroke color
418 * See {@link Style::set_color()} for the format of the color array.
419 * @param array $color
421 protected function _set_stroke_color($color)
423 $this->_pdf
->setStrokeColor($color);
427 * Sets the fill colour
429 * See {@link Style::set_color()} for the format of the colour array.
430 * @param array $color
432 protected function _set_fill_color($color)
434 $this->_pdf
->setColor($color);
438 * Sets line transparency
439 * @see Cpdf::setLineTransparency()
441 * Valid blend modes are (case-sensitive):
443 * Normal, Multiply, Screen, Overlay, Darken, Lighten,
444 * ColorDodge, ColorBurn, HardLight, SoftLight, Difference,
447 * @param string $mode the blending mode to use
448 * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
450 protected function _set_line_transparency($mode, $opacity)
452 $this->_pdf
->setLineTransparency($mode, $opacity);
456 * Sets fill transparency
457 * @see Cpdf::setFillTransparency()
459 * Valid blend modes are (case-sensitive):
461 * Normal, Multiply, Screen, Overlay, Darken, Lighten,
462 * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
465 * @param string $mode the blending mode to use
466 * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
468 protected function _set_fill_transparency($mode, $opacity)
470 $this->_pdf
->setFillTransparency($mode, $opacity);
474 * Sets the line style
476 * @see Cpdf::setLineStyle()
478 * @param float $width
480 * @param string $join
483 protected function _set_line_style($width, $cap, $join, $dash)
485 $this->_pdf
->setLineStyle($width, $cap, $join, $dash);
494 function set_opacity($opacity, $mode = "Normal")
496 $this->_set_line_transparency($mode, $opacity);
497 $this->_set_fill_transparency($mode, $opacity);
500 function set_default_view($view, $options = array())
502 array_unshift($options, $view);
503 call_user_func_array(array($this->_pdf
, "openHere"), $options);
507 * Remaps y coords from 4th to 1st quadrant
512 protected function y($y)
514 return $this->_height
- $y;
517 // Canvas implementation
518 function line($x1, $y1, $x2, $y2, $color, $width, $style = array())
520 $this->_set_stroke_color($color);
521 $this->_set_line_style($width, "butt", "", $style);
523 $this->_pdf
->line($x1, $this->y($y1),
527 function arc($x, $y, $r1, $r2, $astart, $aend, $color, $width, $style = array())
529 $this->_set_stroke_color($color);
530 $this->_set_line_style($width, "butt", "", $style);
532 $this->_pdf
->ellipse($x, $this->y($y), $r1, $r2, 0, 8, $astart, $aend, false, false, true, false);
535 //........................................................................
538 * Convert a GIF or BMP image to a PNG image
540 * @param string $image_url
541 * @param integer $type
544 * @return string The url of the newly converted image
546 protected function _convert_gif_bmp_to_png($image_url, $type)
548 $func_name = "imagecreatefrom$type";
550 if (!function_exists($func_name)) {
551 if (!method_exists("Dompdf\Helpers", $func_name)) {
552 throw new Exception("Function $func_name() not found. Cannot convert $type image: $image_url. Please install the image PHP extension.");
554 $func_name = "\\Dompdf\\Helpers::" . $func_name;
557 set_error_handler(array("\\Dompdf\\Helpers", "record_warnings"));
558 $im = call_user_func($func_name, $image_url);
561 imageinterlace($im, false);
563 $tmp_dir = $this->_dompdf
->get_option("temp_dir");
564 $tmp_name = tempnam($tmp_dir, "{$type}dompdf_img_");
566 $filename = "$tmp_name.png";
567 $this->_image_cache
[] = $filename;
569 imagepng($im, $filename);
572 $filename = Cache
::$broken_image;
575 restore_error_handler();
580 function rectangle($x1, $y1, $w, $h, $color, $width, $style = array())
582 $this->_set_stroke_color($color);
583 $this->_set_line_style($width, "butt", "", $style);
584 $this->_pdf
->rectangle($x1, $this->y($y1) - $h, $w, $h);
587 function filled_rectangle($x1, $y1, $w, $h, $color)
589 $this->_set_fill_color($color);
590 $this->_pdf
->filledRectangle($x1, $this->y($y1) - $h, $w, $h);
593 function clipping_rectangle($x1, $y1, $w, $h)
595 $this->_pdf
->clippingRectangle($x1, $this->y($y1) - $h, $w, $h);
598 function clipping_roundrectangle($x1, $y1, $w, $h, $rTL, $rTR, $rBR, $rBL)
600 $this->_pdf
->clippingRectangleRounded($x1, $this->y($y1) - $h, $w, $h, $rTL, $rTR, $rBR, $rBL);
603 function clipping_end()
605 $this->_pdf
->clippingEnd();
610 $this->_pdf
->saveState();
615 $this->_pdf
->restoreState();
618 function rotate($angle, $x, $y)
620 $this->_pdf
->rotate($angle, $x, $y);
623 function skew($angle_x, $angle_y, $x, $y)
625 $this->_pdf
->skew($angle_x, $angle_y, $x, $y);
628 function scale($s_x, $s_y, $x, $y)
630 $this->_pdf
->scale($s_x, $s_y, $x, $y);
633 function translate($t_x, $t_y)
635 $this->_pdf
->translate($t_x, $t_y);
638 function transform($a, $b, $c, $d, $e, $f)
640 $this->_pdf
->transform(array($a, $b, $c, $d, $e, $f));
643 function polygon($points, $color, $width = null, $style = array(), $fill = false)
645 $this->_set_fill_color($color);
646 $this->_set_stroke_color($color);
649 for ($i = 1; $i < count($points); $i +
= 2) {
650 $points[$i] = $this->y($points[$i]);
653 $this->_pdf
->polygon($points, count($points) / 2, $fill);
656 function circle($x, $y, $r1, $color, $width = null, $style = null, $fill = false)
658 $this->_set_fill_color($color);
659 $this->_set_stroke_color($color);
661 if (!$fill && isset($width)) {
662 $this->_set_line_style($width, "round", "round", $style);
665 $this->_pdf
->ellipse($x, $this->y($y), $r1, 0, 0, 8, 0, 360, 1, $fill);
668 function image($img, $x, $y, $w, $h, $resolution = "normal")
670 list($width, $height, $type) = Helpers
::dompdf_getimagesize($img, $this->get_dompdf()->getHttpContext());
672 $debug_png = $this->_dompdf
->get_option("debug_png");
674 if ($debug_png) print "[image:$img|$width|$height|$type]";
678 if ($debug_png) print '!!!jpg!!!';
679 $this->_pdf
->addJpegFromFile($img, $x, $this->y($y) - $h, $w, $h);
684 if ($debug_png) print '!!!bmp or gif!!!';
685 // @todo use cache for BMP and GIF
686 $img = $this->_convert_gif_bmp_to_png($img, $type);
689 if ($debug_png) print '!!!png!!!';
691 $this->_pdf
->addPngFromFile($img, $x, $this->y($y) - $h, $w, $h);
695 if ($debug_png) print '!!!SVG!!!';
697 $this->_pdf
->addSvgFromFile($img, $x, $this->y($y) - $h, $w, $h);
701 if ($debug_png) print '!!!unknown!!!';
705 function text($x, $y, $text, $font, $size, $color = array(0, 0, 0), $word_space = 0.0, $char_space = 0.0, $angle = 0.0)
709 $pdf->setColor($color);
712 $pdf->selectFont($font);
714 //FontMetrics::getFontHeight($font, $size) ==
715 //$this->getFontHeight($font, $size) ==
716 //$this->_pdf->selectFont($font),$this->_pdf->getFontHeight($size)
717 //- FontBBoxheight+FontHeightOffset, scaled to $size, in pt
718 //$this->_pdf->getFontDescender($size)
719 //- Descender scaled to size
721 //$this->_pdf->fonts[$this->_pdf->currentFont] sizes:
722 //['FontBBox'][0] left, ['FontBBox'][1] bottom, ['FontBBox'][2] right, ['FontBBox'][3] top
723 //Maximum extent of all glyphs of the font from the baseline point
724 //['Ascender'] maximum height above baseline except accents
725 //['Descender'] maximum depth below baseline, negative number means below baseline
726 //['FontHeightOffset'] manual enhancement of .afm files to trim windows fonts. currently not used.
727 //Values are in 1/1000 pt for a font size of 1 pt
729 //['FontBBox'][1] should be close to ['Descender']
730 //['FontBBox'][3] should be close to ['Ascender']+Accents
731 //in practice, FontBBox values are a little bigger
733 //The text position is referenced to the baseline, not to the lower corner of the FontBBox,
734 //for what the left,top corner is given.
735 //FontBBox spans also the background box for the text.
736 //If the lower corner would be used as reference point, the Descents of the glyphs would
737 //hang over the background box border.
738 //Therefore compensate only the extent above the Baseline.
740 //print '<pre>['.$font.','.$size.','.$pdf->getFontHeight($size).','.$pdf->getFontDescender($size).','.$pdf->fonts[$pdf->currentFont]['FontBBox'][3].','.$pdf->fonts[$pdf->currentFont]['FontBBox'][1].','.$pdf->fonts[$pdf->currentFont]['FontHeightOffset'].','.$pdf->fonts[$pdf->currentFont]['Ascender'].','.$pdf->fonts[$pdf->currentFont]['Descender'].']</pre>';
742 //$pdf->addText($x, $this->y($y) - ($pdf->fonts[$pdf->currentFont]['FontBBox'][3]*$size)/1000, $size, $text, $angle, $word_space, $char_space);
743 $pdf->addText($x, $this->y($y) - $pdf->getFontHeight($size), $size, $text, $angle, $word_space, $char_space);
746 //........................................................................
748 function javascript($code)
750 $this->_pdf
->addJavascript($code);
753 //........................................................................
756 * Add a named destination (similar to <a name="foo">...</a> in html)
758 * @param string $anchorname The name of the named destination
760 function add_named_dest($anchorname)
762 $this->_pdf
->addDestination($anchorname, "Fit");
765 //........................................................................
768 * Add a link to the pdf
770 * @param string $url The url to link to
771 * @param float $x The x position of the link
772 * @param float $y The y position of the link
773 * @param float $width The width of the link
774 * @param float $height The height of the link
776 function add_link($url, $x, $y, $width, $height)
779 $y = $this->y($y) - $height;
781 if (strpos($url, '#') === 0) {
783 $name = substr($url, 1);
785 $this->_pdf
->addInternalLink($name, $x, $y, $x +
$width, $y +
$height);
789 $this->_pdf
->addLink(rawurldecode($url), $x, $y, $x +
$width, $y +
$height);
793 function get_text_width($text, $font, $size, $word_spacing = 0, $char_spacing = 0)
795 $this->_pdf
->selectFont($font);
796 return $this->_pdf
->getTextWidth($size, $text, $word_spacing, $char_spacing);
799 function register_string_subset($font, $string)
801 $this->_pdf
->registerText($font, $string);
804 function get_font_height($font, $size)
806 $this->_pdf
->selectFont($font);
808 $ratio = $this->_dompdf
->get_option("font_height_ratio");
809 return $this->_pdf
->getFontHeight($size) * $ratio;
812 /*function get_font_x_height($font, $size) {
813 $this->_pdf->selectFont($font);
814 $ratio = $this->_dompdf->get_option("font_height_ratio");
815 return $this->_pdf->getFontXHeight($size) * $ratio;
818 function get_font_baseline($font, $size)
820 $ratio = $this->_dompdf
->get_option("font_height_ratio");
821 return $this->get_font_height($font, $size) / $ratio;
825 * Writes text at the specified x and y coordinates on every page
827 * The strings '{PAGE_NUM}' and '{PAGE_COUNT}' are automatically replaced
828 * with their current values.
830 * See {@link Style::munge_color()} for the format of the colour array.
834 * @param string $text the text to write
835 * @param string $font the font file to use
836 * @param float $size the font size, in points
837 * @param array $color
838 * @param float $word_space word spacing adjustment
839 * @param float $char_space char spacing adjustment
840 * @param float $angle angle to write the text at, measured CW starting from the x-axis
842 function page_text($x, $y, $text, $font, $size, $color = array(0, 0, 0), $word_space = 0.0, $char_space = 0.0, $angle = 0.0)
845 $this->_page_text
[] = compact("_t", "x", "y", "text", "font", "size", "color", "word_space", "char_space", "angle");
849 * Processes a script on every page
851 * The variables $pdf, $PAGE_NUM, and $PAGE_COUNT are available.
853 * This function can be used to add page numbers to all pages
854 * after the first one, for example.
856 * @param string $code the script code
857 * @param string $type the language type for script
859 function page_script($code, $type = "text/php")
862 $this->_page_text
[] = compact("_t", "code", "type");
867 $this->_page_number++
;
868 $this->_page_count++
;
870 $ret = $this->_pdf
->newPage();
871 $this->_pages
[] = $ret;
876 * Add text to each page after rendering is complete
878 protected function _add_page_text()
881 if (!count($this->_page_text
)) {
888 foreach ($this->_pages
as $pid) {
889 $this->reopen_object($pid);
891 foreach ($this->_page_text
as $pt) {
896 $text = str_replace(array("{PAGE_NUM}", "{PAGE_COUNT}"),
897 array($page_number, $this->_page_count
), $text);
898 $this->text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
903 $eval = new PhpEvaluator($this);
905 $eval->evaluate($code, array('PAGE_NUM' => $page_number, 'PAGE_COUNT' => $this->_page_count
));
910 $this->close_object();
916 * Streams the PDF directly to the browser
918 * @param string $filename the name of the PDF file
919 * @param array $options associative array, 'Attachment' => 0 or 1, 'compress' => 1 or 0
921 function stream($filename, $options = null)
924 $this->_add_page_text();
926 $options["Content-Disposition"] = $filename;
927 $this->_pdf
->stream($options);
931 * Returns the PDF as a string
933 * @param array $options Output options
936 function output($options = null)
938 $this->_add_page_text();
940 $debug = isset($options["compress"]) && $options["compress"] != 1;
942 return $this->_pdf
->output($debug);
946 * Returns logging messages generated by the Cpdf class
950 function get_messages()
952 return $this->_pdf
->messages
;