Skip to content
Brian Sweeney edited this page Sep 19, 2023 · 55 revisions

Using Dompdf

Using the dompdf class

Using the dompdf class directly is fairly straightforward:

Version 0.8.6 or newer

<?php
// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->getOptions()->setChroot('/path/to/common/assets-directory');
$dompdf->loadHtml('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();
?>

More background information about the chroot option can be found here.

Version 0.7.0 until 0.8.5

<?php
// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();
?>

Version 0.6 or older

<?php
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->load_html('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->set_paper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream('document.pdf');
?>

Method summary

Please note: The method summary indicates the applicable version (if necessary) and whether or not the specific method has been deprecated for removal in future releases.

getOptions

Get the options as an instance of Dompdf\Options which is used as a container for several Dompdf options.

There are two ways to get the options' values

$dompdf->getOptions()->get('defaultFont'); // or
$dompdf->getOptions()->getDefaultFont();

The options instance allows you to change the options:

// pass an array of options
$dompdf->getOptions()->set([
    'defaultFont' => 'helvetica',
    'chroot' => '/var/www/myproject/public',
]);

$dompdf->getOptions()->set('defaultFont', 'helvetica');
$dompdf->getOptions()->set('chroot', '/var/www/myproject/public');

// or use the setters directly
$dompdf->getOptions()->setDefaultFont('helvetica');
$dompdf->getOptions()->setChroot('/var/www/myproject/public');

loadHtml

Loads an HTML string. Parse errors are stored in the global array $_dompdf_warnings.

Versions prior to 0.7.0 use load_html.

Arguments:

  • string $str: HTML text to load
  • string[optional] $encoding: encoding, if not provided, dompdf will try to find it.

loadHtmlFile

Loads an HTML file. Parse errors are stored in the global array $_dompdf_warnings.

Versions prior to 0.7.0 use load_html_file.

Arguments:

  • string $file: a filename or url to load

output

Returns the PDF as a string. The file will open a download dialog by default. The options parameter controls the output.

Arguments:

  • array $options: accepted options are:
    • compress => 1 or 0 - apply content stream compression, this is on (1) by default

render

Renders the HTML to PDF.

Arguments: none.

setBasePath

Sets the base path used for resources references when a relative path is specified. This path is not used for resources references that specify an absolute path (a path that begins with a "/").

Versions prior to 0.7.0 use set_base_path.

Arguments:

  • string $basePath: The base path to be used when resolving external resources URLs.

setPaper

Sets the paper size & orientation

Versions prior to 0.7.0 use set_paper.

Arguments:

  • string|array $size: 'letter', 'legal', 'A4', etc. See Dompdf\Adapter\CPDF::$PAPER_SIZES
  • string $orientation: 'portrait' or 'landscape'

stream

Streams the PDF to the client. The file will open a download dialog by default. The options parameter controls the output.

Arguments:

  • string $filename: the name of the streamed file (without the .pdf extension)
  • array $options: accepted options are:
    • '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

setHttpContext

Applies a stream context to retrieval of assets used in the creation of the PDF. This is applied directly to the third parameter of PHP's file_get_contents function.

If you are trying to add images to a PDF and they will not display, and if those images are hosted on a server with a self-signed security certificate or other certificate problems, creating and setting a stream context will be necessary.

Arguments:

Example:

<?php
use Dompdf\Dompdf;
use Dompdf\Options;
require_once 'dompdf/autoload.inc.php';
$options = new Options();
$options->set('isRemoteEnabled', TRUE);
$dompdf = new Dompdf($options);

$context = stream_context_create([ 
	'ssl' => [ 
		'verify_peer' => FALSE, 
		'verify_peer_name' => FALSE,
		'allow_self_signed'=> TRUE 
	] 
]);
$dompdf->setHttpContext($context);

// ... Finish creating your PDF ...

Options

  • allowedProtocols: Protocols and validation rules for resource URIs
    An array of the format ["protocol://" => ["rules" => [callable]], ...] (see the Validating resource URIs section for details on validation rules). Default rules apply for the file, http(s), and phar protocols when none are specified.
    Note: Full protocol support is not guaranteed for the allowed protocols.

  • chroot: dompdf's "chroot"
    Utilized by the file:// protocol validation rule to define the director(y|ies) from which dompdf may accessing files on the local filesystem. All local files opened by dompdf must be in a subdirectory of this directory. DO NOT set it to '/' since this could allow an attacker to use dompdf to read any files on the server. This should be an absolute path.
    IMPORTANT This setting may increase the risk of system exploit. Do not change this settings without understanding the consequences. Default is the root directory of the Dompdf library.

  • defaultFont: The default font family
    Used if no suitable fonts can be found. This must exist in the font folder. Default is 'serif'

  • defaultMediaType: The default CSS media type targeted by Dompdf.
    Styles targeted to this media type are applied to the document. This is on top of the media types that are always applied: all, static, visual, bitmap, paged, dompdf (custom media type for Dompdf).

  • defaultPaperSize: The default paper size.
    North America standard is "letter"; other countries generally "a4" See Dompdf\Adapter\CPDF::PAPER_SIZES for valid sizes

  • defaultPaperOrientation: The default paper orientation. Possible values: portrait (=default), landscape.

  • dpi: Image DPI setting
    This setting determines the default DPI setting for images and fonts. The DPI may be overridden for inline images by explicitly setting the image's width & height style attributes (i.e. if the image's native width is 600 pixels and you specify the image's width as 72 points, the image will have a DPI of 600 in the rendered PDF. The DPI of background images can not be overridden and is controlled entirely via this parameter.
    For the purposes of DOMPDF, pixels per inch (PPI) = dots per inch (DPI). If a size in html is given as px (or without unit as image size), this tells the corresponding size in pt at 72 DPI. This adjusts the relative sizes to be similar to the rendering of the html page in a reference browser.
    In pdf, always 1 pt = 1/72 inch
    Default is 96

  • fontCache: The location of the DOMPDF font cache directory
    This directory contains the cached font metrics for the fonts used by DOMPDF. This directory can be the same as $fontDir
    Note: This directory must exist and be writable by the webserver process.

  • fontDir: The location of the DOMPDF font directory.
    The location of the directory where DOMPDF will store fonts and font metrics Note: This directory must exist and be writable by the webserver process.

  • fontHeightRatio: A ratio applied to the fonts height to be more like browsers' line height
    Default is 1.1

  • isPhpEnabled: Enable embedded PHP
    If this setting is set to true then DOMPDF will automatically evaluate embedded PHP contained within <script type="text/php"> ... </script> tags.
    Default is false
    IMPORTANT Enabling this for documents you do not trust (e.g. arbitrary remote html pages or user-supplied content) is a security risk. Embedded scripts are run with the same level of system access available to dompdf, increasing the risk of system exploit.

  • isRemoteEnabled: Enable remote file access
    If this setting is set to true, DOMPDF will access images and CSS files hosted through web-based protocols.

  • logOutputFile: Path to file where logs are written to.

  • rootDir: The root of your DOMPDF installation

  • tempDir: The location of a temporary directory.
    The directory specified must be writable by the webserver process. The temporary directory is required to download remote images and when using the PFDLib back end.

Dompdf API

Follows is a highlight of commonly used methods from the Dompdf API.

Canvas

The Canvas is Dompdf's API for interacting with the underlying library that writes to the specific output format (Cpdf, PDFLib, GD). This API allows you to perform drawing operations directly to the output, bypassing the HTML/CSS rendering engine.

The following is a sampling of the methods defined by the API:

image

Adds an image at the specified x and y coordinates with the given width and height.

  • string $img: the path to the image
  • float $x: x position from the top left of the document in PT
  • float $y: y position from the top left of the document in PT
  • int $w: width of the image in the document in PT
  • int $h: height of the image in the document in PT
  • string $resolution: The resolution of the image (currently unused)

line

Draws a line from (x1,y1) to (x2,y2)

  • float $x1: starting x position from the top left of the document in PT
  • float $y1: starting y position from the top left of the document in PT
  • float $x2: ending x position from the top left of the document in PT
  • float $y2: ending y position from the top left of the document in PT
  • array $color: color array in the format [r, g, b, "alpha" => alpha] where r, g, b, and alpha are decimal values between 0 and 1
  • float $width: width of the line in PT
  • array $style: an array which sets the dash pattern, is a series of length values in PT, which are the lengths of the on and off dashes

text

Adds text to the current page

  • float $x: x position from the top left of the document in PT
  • float $y: y position from the top left of the document in PT
  • string $text: the text to write
  • string $font: the font file to use
  • float $size: the font size, in points
  • array $color: color array in the format [r, g, b, "alpha" => alpha] where r, g, b, and alpha are decimal values between 0 and 1
  • float $word_space: word spacing adjustment
  • float $char_space: character spacing adjustment
  • float $angle: angle to write the text at, measured clockwise starting from the x-axis

page_text

Adds text to every page of the document. The "{PAGE_NUM}" and "{PAGE_COUNT}" text variables are replaced with the current page number and total number of pages, respectively.

  • float $x: x position from the top left of the document in PT
  • float $y: y position from the top left of the document in PT
  • string $text: the text to write
  • string $font: the font file to use
  • float $size: the font size, in points
  • array $color: color array in the format [r, g, b, "alpha" => alpha] where r, g, b, and alpha are decimal values between 0 and 1
  • float $word_space: word spacing adjustment
  • float $char_space: char spacing adjustment
  • float $angle: angle to write the text at, measured clockwise starting from the x-axis

Note: For versions of dompdf before 2.0.0, page_text is actually processed during output generation, so it will always affect all pages independent of the point where it is called.

page_script

Processes a callback for every page of the document. Currently only available in the Cpdf and PDFLib adapters.

  • callable $callback: the callback function to process on every page

    The callback function receives the following four parameters:

    Parameter Description
    $pageNumber The current page number
    $pageCount The total (current) number of pages
    $canvas The current instance of Canvas
    $fontMetrics The instance of Dompdf\FontMetrics in use by dompdf

    Passing a callback function is supported since dompdf 1.2.0. For older versions, a script can be passed as string instead. The script is evaluated for every page of the document. The following variables are made available to the page script:

    Variable Description
    $PAGE_NUM The current page number
    $PAGE_COUNT The total (current) number of pages
    $pdf The current instance of Canvas
    $fontMetrics The instance of Dompdf\FontMetrics in use by dompdf

    Note: For versions of dompdf before 2.0.0, page_script is actually processed during output generation, so it will always affect all pages independent of the point where it is called.

get_{{backend}}

Each implementation of Canvas provides it's own method for accessing the backend library. This allows you to call methods of the backend that are not represented in the Canvas API.

  • get_cpdf (Cpdf)
  • get_pdflib (PDFLib)
  • get_image (GD)

The following snippet uses the Canvas API to render a footer on every page of a document:

$dompdf = new Dompdf();
$dompdf->loadHtml(<<<'EOL'
    <style>
    .container {
        page-break-before: always;
    }
    .container:first-of-type {
        page-break-before: auto;
    }
    </style>
    <div class="container"><h1>Chapter One</h1></div> 
    <div class="container"><h1>Chapter Two</h1></div> 
    <div class="container"><h1>Chapter Three</h1></div> 
EOL
);
$dompdf->render();
$canvas = $dompdf->getCanvas();
$canvas->page_script(function ($pageNumber, $pageCount, $canvas, $fontMetrics) {
    $text = "Page $pageNumber of $pageCount";
    $font = $fontMetrics->getFont('monospace');
    $pageWidth = $canvas->get_width();
    $pageHeight = $canvas->get_height();
    $size = 12;
    $width = $fontMetrics->getTextWidth($text, $font, $size);
    $canvas->text($pageWidth - $width - 20, $pageHeight - 20, $text, $font, $size);
});
$dompdf->stream();

Callbacks

Callbacks are functions that are executed by Dompdf at certain points during the rendering process.

To configure a callback you set up an array of arrays, where each inner array specifies the callback event and the function to execute.

$callbacks = [
  [
    "event" => "begin_frame",
    "f" => function ($frame, $canvas, $fontMetrics) { ... }
  ]
];

The callback events are:

  • begin_page_reflow: called before page reflow
  • begin_frame: called before a frame is rendered
  • end_frame: called after frame rendering is complete
  • begin_page_render: called before a page is rendered
  • end_page_render: called after page rendering is complete
  • end_document: called for every page after rendering is complete (since 2.0.0)

Callbacks receive three arguments for all events but end_document:

Parameter Description
$frame The current frame
$canvas The current instance of Canvas
$fontMetrics The instance of Dompdf\FontMetrics in use by dompdf

For end_document, they receive four arguments instead:

Parameter Description
$pageNumber The current page number
$pageCount The total number of pages
$canvas The current instance of Canvas
$fontMetrics The instance of Dompdf\FontMetrics in use by dompdf

Note: For versions of dompdf before 2.0.0, callbacks receive a single argument instead, which is an array containing the current frame and the Canvas instance. The array is structured as follows:

[
  0 => Canvas, "canvas" => Canvas,
  1 => Frame,  "frame"  => Frame,
];

The following sample uses a callback to render a footer that reflects the current H1 for a section:

$dompdf = new Dompdf();
$dompdf->loadHtml(<<<'EOL'
    <style>
    .container {
        page-break-before: always;
    }
    .container:first-of-type {
        page-break-before: auto;
    }
    </style>
    <div class="container"><h1>Chapter One</h1></div> 
    <div class="container"><h1>Chapter Two</h1></div> 
    <div class="container"><h1>Chapter Three</h1></div> 
EOL
);
$fontMetrics = $dompdf->getFontMetrics();
$GLOBALS['SECTION'] = null;
$dompdf->setCallbacks(
    [
        [
            'event' => 'begin_frame',
            'f' => function ($frame) {
                $node = $frame->get_node();
                if ($node->nodeName === 'h1') {
                    $GLOBALS['SECTION'] = $node->textContent;
                }
            }
        ],
        [
            'event' => 'end_page_render',
            'f' => function ($frame, $canvas) use ($fontMetrics) {
                $text = $GLOBALS['SECTION'];
                $font = $fontMetrics->getFont('monospace');
                $pageWidth = $canvas->get_width();
                $pageHeight = $canvas->get_height();
                $size = 12;
                $width = $fontMetrics->getTextWidth($text, $font, $size);
                $canvas->text($pageWidth - $width - 20, $pageHeight - 20, $text, $font, $size);
            }
        ]
    ]
);
$dompdf->render();
$dompdf->stream();

Embedded PHP support

Embedded PHP is a mechanism by which a developer can access the Canvas API from within the HTML document being rendered.

Note: Allowing execution of PHP embedded in an HTML document can potentially enable exploitation of your system. Please review the Securing Dompdf page for more information.

Due to the security implication of this functionality it will likely be removed in the future. To access the canvas and other underlying functionality we recommend calling the Dompdf API from the PHP script that is utilizing Dompdf instead. See the Dompdf API documentation for more information.

PHP evaluation is controlled by the \Dompdf\Options::$isPhpEnabled configuration option. If it is set to false, then no PHP code is executed.

Embedded PHP 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 Dompdf\Canvas::open_object(), Dompdf\Canvas::close_object(), and Dompdf\Canvas::add_object() methods, you can create text and drawing objects that appear on every page of your PDF (useful for headers & footers).

Because embedded script is used to interact with the underlying API and not with the HTML document or Dompdf itself you can not echo content from the script and see it rendered to the PDF.

The following variables are defined for use during PHP execution.

Variable Description
$pdf The current instance of Canvas
$PAGE_NUM The current page number
$PAGE_COUNT The total number of pages as of script execution
$fontMetrics The instance of Dompdf\FontMetrics in use by dompdf

And the following template variables are parsed when using the Dompdf\Canvas::page_text() method. To use, surround by {curly braces}.

Variable Description
PAGE_NUM The current page number
PAGE_COUNT The total number of pages in the document

Sample embedded script:

<html>
  <body>
    <script type="text/php">
      if ( isset($pdf) ) {
        $w = $pdf->get_width();
        $h = $pdf->get_height();

        $size = 6;
        $color = [0, 0, 0];
        $font = $fontMetrics->getFont("helvetica");
        $text_height = $fontMetrics->getFontHeight($font, $size);
        $y = $h - 2 * $text_height - 24;

        // a static object added to every page
        $foot = $pdf->open_object();
        // Draw a line along the bottom
        $pdf->line(16, $y, $w - 16, $y, $color, 1);
        $y += $text_height;
        $pdf->text(16, $y, "Generated by Dompdf", $font, $size, $color);
        $pdf->close_object();
        $pdf->add_object($foot, "all");
      }
    </script>
        
    <p>some text</p>
    <p style="page-break-before: always;">some text on a new page</p>

    <script type="text/php">
      if ( isset($pdf) ) {
        $h = $pdf->get_height();

        $size = 6;
        $font_bold = $fontMetrics->getFont("helvetica", "bold");
        $text_height = $fontMetrics->getFontHeight($font_bold, $size);
        $y = $h - $text_height - 24;

        // generated text written to every page after rendering
        $pdf->page_text(550, $y, "Page {PAGE_NUM} of {PAGE_COUNT}", $font_bold, $size, [0, 0, 0]);
      }
    </script>
  </body>
</html>

Note that the script is at the top of the HTML document. Because Dompdf renders content as it is encountered the script-generated content should be located at the start of where it should appear in the document. The exception are the page_text and page_script methods. They affect all pages that have been rendered so far, so they would usually be called at the end of the document in order to affect all pages*.

* For versions of dompdf before 2.0.0, these methods are parsed on every page of the document after the HTML has been fully rendered, so they will affect all pages independent of when they are called in the embedded script.

Resource References and URI Validation

How should resources like images be referenced? Think of Dompdf as a web browser. If you load a page into a web browser the same way you load it into Dompdf would the browser be able to view it?

For example, if the source path starts with content/img/example.jpg it is relative to the file location. File location depends on how you've loaded the document. If you load it via the web then it's relative to the URL of the page. If you load it via file, then it's relative to the location of the file on the filesystem. If you generate the HTML and feed it to Dompdf then the path is relative to the executing script on the file system.

Validation Rules

Dompdf determines whether or not a resource can be loaded using validation rules. Validation rules are defined based on the resource URI protocol (such as http://). Dompdf parses a resource URI to determine the protocol. If the protocol matches a key in the allowedProtocols Option the URI is then run through the defined validation rules. Dompdf will attempt to load a resource only when the URI passes validation (or if there are no validation rules defined).

Users can specify their own validation rules. Rules should accept a URI and return an array in the following format:

[
  (boolean), // did the URI pass validation
  (string) // validation response message
]

Dompdf includes the following default validation rules.

file://

Dompdf will not load files that are not located under the path(s) specified by the chroot option.

For example, let's say Dompdf is located under the file path /var/libs/dompdf and we are executing the following PHP script under /var/www/myproject/public.

$dompdf = new Dompdf();
$html = <<<HTML
<!DOCTYPE html>
<html>
    <body>
        <img src="/var/www/myproject/public/img/logo.png">
    </body>
</html>
HTML;
$dompdf->loadHtml($html);

In the example above the image will fail to load because the image path is outside the chroot path. The chroot option must be updated to allow loading by Dompdf:

$dompdf->getOptions()->setChroot(['/var/www/myproject/public']);

http(s)://

Remote resource will be rejected unless the isRemoteEnabled Option is set to true.

phar://

The PHAR protocol is not enabled by default. If enabled using the default validation rule the path to the PHAR file is validated using the same logic as file URIs.