On this page:
Usage
The dompdf.php script included in the distribution can be used both from the command line or via a web browser. Alternatively, the dompdf class can be used directly.
Invoking dompdf via the web
The dompdf.php script is not intended to be an interactive page. It receives input parameters via $_GET and can stream a PDF directly to the browser. This makes it possible to embed links to the script in a page that look like static PDF links, but are actually dynamically generated. This method is also useful as a redirection target.
dompdf.php accepts the following $_GET variables:
| input_file | required | a rawurlencoded() path to the HTML file to process. Remote files (http/ftp) are supported if fopen wrappers are enabled. |
| paper | optional | the paper size. Defaults to 'letter' (unless the default has been changed in dompdf_config.inc.php). See include/pdf_adapter.cls.php, or invoke dompdf.php on the command line with the -l switch for accepted paper sizes. |
| orientation | optional | 'portrait' or 'landscape'. Defaults to 'portrait'. |
| base_path | optional | the base path to use when resolving relative links (images or CSS files). Defaults to the directory containing the file being accessed. (This option is useful for pointing dompdf at your CSS files even though the HTML file may be elsewhere.) |
| output_file | optional | the rawurlencoded() name of the output file. Defaults to 'dompdf_out.pdf'. |
| save_file | optional | If present (i.e. isset($_GET["save_file"]) == true');),
output_file is saved locally, Otherwise the file is streamed directly to the client. |
One technique for generating dynamic PDFs is to generate dynamic HTML as you normally would, except instead of displaying the output to the browser, you use output buffering and write the output to a temporary file. Once this file is saved, you redirect to the dompdf.php script. If you use a templating engine like Smarty, you can simply do:
<?php
$tmpfile = tempnam("/tmp", "dompdf_");
file_put_contents($tmpfile, $smarty->fetch()); // Replace $smarty->fetch()
// with your HTML string
$url = "dompdf.php?input_file=" . rawurlencode($tmpfile) .
"&paper=letter&output_file=" . rawurlencode("My Fancy PDF.pdf");
header("Location: http://" . $_SERVER["HTTP_HOST"] . "/$url");
?>
If you use any stylesheets, you may need to provide the
base_path option to tell dompdf where to look for them, as they
are not likely relative to /tmp ;).
Invoking dompdf via the command line
You can execute dompdf.php using the following command:
$ php -f dompdf.php -- [options]
(If you find yourself using only the cli interface, you can add
#!/usr/bin/php as the first line of dompdf.php to invoke dompdf.php
directly.)
dompdf.php is invoked as follows:
| $ ./dompdf.php [options] html_file | |
html_file can be a filename, a url if
fopen_wrappers are enabled, or the '-' character to read from standard input. |
|
| -h | Show a brief help message |
| -l | list available paper sizes |
| -p size | paper size; something like 'letter', 'A4', 'legal', etc. Thee default is 'letter' |
| -o orientation | either 'portrait' or 'landscape'. Default is 'portrait'. |
| -b path | the base path to use when resolving relative links (images or CSS files). Default is the directory of html_file. |
| -f file | the output filename. Default is the input [html_file].pdf. |
| -v | verbose: display html parsing warnings and file not found errors. |
| -d | very verbose: display oodles of debugging output; every frame in the tree is printed to stdout. |
Examples:
$ php -f dompdf.php -- my_resume.html $ ./dompdf.php -b /var/www/ ./web_stuff/index.html $ echo '<html><body>Hello world!</body></html>' | ./dompdf.php -
Using the dompdf class directly
Using the dompdf class directly is fairly straightforward:
<?php
require_once("dompdf_config.inc.php");
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
?>
Below is a summary of the methods available in the dompdf class. For complete details, see the API documentation for the class interface definition.
DOMPDF Class Reference
- DOMPDF __construct()
- string get_base_path()
- string get_host()
- string get_protocol()
- Frame_Tree get_tree()
- void load_html(string $str)
- void load_html_file(string $file)
- string output()
- void render()
- void set_base_path(string $path)
- void set_host(string $host)
- void set_paper(string $size, [string $orientation = "portrait"])
- void set_protocol(string $proto)
- void stream(string $filename, [mixed $options = null])
Return the underlying Canvas instance (e.g. CPDF_Adapter, GD_Adapter)
Loads an HTML string
Parse errors are stored in the global array _dompdf_warnings.
- string $str: HTML text to load
Loads an HTML file
Parse errors are stored in the global array _dompdf_warnings.
- string $file: a filename or url to load
Sets the paper size & orientation
- string $size: 'letter', 'legal', 'A4', etc. See CPDF_Adapter::$PAPER_SIZES
- string $orientation: 'portrait' or 'landscape'
Sets the protocol to use (http://, file://, ftp:// etc.)
- string $proto
Streams the PDF to the client
The file will always open a download dialog. The options parameter
controls the output headers. Accepted headers
are:
'Accept-Ranges' => 1 or 0 - if this is not set to 1, then this
header is not included, off by default. This header seems to have
caused some problems despite the fact that it is supposed to solve
them, so I am leaving it off by default.
'compress' = > 1 or 0 - apply content stream compression, this is
on (1) by default
'Attachment' => 1 or 0 - if 1, force the browser to open a download
dialog, on (1) by default
- string $filename: the name of the streamed file
- array $options: header options (see above)
Inline PHP Support
dompdf supports two varieties of inline PHP code. All PHP evaluation is
controlled by the DOMPDF_ENABLE_PHP configuration option. If it is set to
false, then no PHP code is executed. Otherwise, PHP is evaluated in two
passes:
The first pass is useful for inserting dynamic data into your PDF. You can do this by embedding <?php ?> tags in your HTML file, as you would in a normal .php file. This code is evaluated prior to parsing the HTML, so you can echo any text or markup and it will appear in the rendered PDF.
The second pass is useful for performing drawing operations on the
underlying PDF class directly. You can do this by embedding PHP code within
<script type="text/php"> </script> tags. This code is evaluated
during the rendering phase and you have access to a few internal objects and
operations. In particular, the $pdf variable is the current instance of
Canvas. Using this object, you can write and draw directly on the
current page. Using the Canvas::open_object(),
Canvas::close_object() and
Canvas::add_object() methods, you can create text and
drawing objects that appear on every page of your PDF (useful for headers &
footers).
The following variables are defined for you during the second pass of PHP execution:
$pdf the current instance of Canvas $PAGE_NUM the current page number $PAGE_COUNT the total number of pages in the document
See below for the full Canvas API.
Canvas class reference
- void add_object (int $object, [string $where = 'all'])
- void circle(float $x, float $y, float $r, array $color, [float $width = null], [array $style = null], [bool $fill = false])
- void close_object()
- void filled_rectangle(float $x1, float $y1, float $w, float $h, array $color)
- float get_font_height(string $font, float $size)
- float get_height()
- int get_page_count()
- int get_page_number()
- float get_text_width(string $text, string $font, float $size, float $spacing)
- float get_width()
- void image(string $img_url, string $img_type, float $x, float $y, int $w, int $h)
- void line(float $x1, float $y1, float $x2, float $y2, array $color, float $width, [array $style = null])
- void new_page()
- int open_object()
- void page_text(float $x, float $y, string $text, string $font, float $size, [array $color = array(0,0,0)], [float $adjust], [float $angle])
- void polygon(array $points, array $color, [float $width = null], [array $style = null], [bool $fill = false])
- void rectangle(float $x1, float $y1, float $w, float $h, array $color, float $width, [array $style = null])
- void set_page_count(int $count)
- void stop_object(int $object)
- void text(float $x, float $y, string $text, string $font, float $size, [array $color = array(0,0,0)], [float $adjust])
Adds a specified 'object' to the document.
$object int specifying an object created with Canvas::open_object(). $where can be one of:
- 'add' add to current page only
- 'all' add to every page from the current one onwards
- 'odd' add to all odd numbered pages from now on
- 'even' add to all even numbered pages from now on
- 'next' add the object to the next page only
- 'nextodd' add to all odd numbered pages from the next one
- 'nexteven' add to all even numbered pages from the next one
- int $object
- string $where
Draws a circle at $x,$y with radius $r
See Style::munge_colour() for the format of the colour array. See Cpdf::setLineStyle() for a description of the $style parameter (aka dash)
- float $x
- float $y
- float $r
- array $color
- float $width
- array $style
- bool $fill: Fills the circle if true
Closes the current 'object'. All subsequent drawing operations affect the page. The closed object can now be added to multiple pages using add_object().
Draws a filled rectangle at x1,y1 with width w and height h
See Style::munge_colour() for the format of the colour array.
- float $x1
- float $y1
- float $w
- float $h
- array $color
Calculates font height, in points.
- string $font
- float $size
Returns the total number of pages. Note this may be inaccurate during rendering. Use page_text() for headers and footers that use page numbers.
Calculates text size, in points.
- string $text: the text to be sized
- string $font: the desired font, retrieved with Font_Metrics::get_font()
- float $size: the desired font size
- float $spacing: word spacing, if any
Add an image to the pdf.
The image is placed at the specified x and y coordinates with the given width and height. The CPDF backend supports JPG, GIF and PNG. The PDFLib backend supports JPG, GIF, PNG, TIFF and BMP images. For both backends, PNGs with binary transparency are supported but PNGs with an alpha channel are not.
Use an absolute path or url if possible when specifying the image file. Relative paths are relative to the current working directory of the webserver.
- string $img_url: the path to the image
- string $img_type: the type (e.g. extension) of the image
- float $x: x position
- float $y: y position
- int $w: width (in pixels)
- int $h: height (in pixels)
Draws a line from x1,y1 to x2,y2
See Style::munge_colour() for the format of the colour array. See Cpdf::setLineStyle() for a description of the format of the $style parameter (aka dash).
- float $x1
- float $y1
- float $x2
- float $y2
- array $color
- float $width
- array $style
Starts a new page
Subsequent drawing operations will appear on the new page.
Opens a new 'object'.
While an object is open, all drawing actions are recored in the object, as opposed to being drawn on the current page. Objects can be added later to a specific page or to several pages using add_object().
The return value is an integer ID for the new object.
Writes text at the specified x and y coordinates on every page
The strings '{PAGE_NUM}' and '{PAGE_COUNT}' are automatically replaced with their current values within $text.
$font can be retrieved with Font_Metrics::get_font().
See Style::munge_colour() for the format of the colour array.
- float $x
- float $y
- string $text: the text to write
- string $font: the font file to use
- float $size: the font size, in points
- array $color
- float $adjust: word spacing adjustment
Draws a polygon
The polygon is formed by joining all the points stored in the $points array. $points has the following structure:
array(0 => x1,
1 => y1,
2 => x2,
3 => y2,
...
);
See Style::munge_colour() for the format of the colour array. See Cpdf::setLineStyle() for a description of the $style parameter (aka dash)
- array $points
- array $color
- float $width
- array $style
- bool $fill: Fills the polygon if true
Draws a rectangle at x1,y1 with width w and height h
See Style::munge_colour() for the format of the colour array. See Cpdf::setLineStyle() for a description of the $style parameter (aka dash)
- float $x1
- float $y1
- float $w
- float $h
- array $color
- float $width
- array $style
Stops the specified 'object' from appearing in the document.
The object will stop being displayed on the page following the current one.
- int $object
Writes text at the specified x and y coordinates
$font can retrieved with Font_Metrics::get_font().
See Style::munge_colour() for the format of the colour array.
- float $x
- float $y
- string $text: the text to write
- string $font: the font file to use
- float $size: the font size, in points
- array $color
- float $adjust: word spacing adjustment



