Skip to content
naitsirch edited this page Nov 10, 2020 · 56 revisions

Using Dompdf

Using the dompdf class

Using the dompdf class directly is fairly straightforward:

Version 0.7.0 or newer

<?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.

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 external stylesheets and images.

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 ...

Embedded PHP support

All 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).

The following variables are defined for you during the second pass of PHP execution:

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

PHP example with ob_start();

<?php ob_start();?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<style>body{font-size: 16px;color: black;}</style>
<title>Title</title>
</head>
<body>
<h2>Hello</h2>
</body>
</html>
<?php
$html = ob_get_clean();

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

$pdf_gen = $dompdf->output();

if(!file_put_contents($full_path, $pdf_gen)){
echo 'Not OK!';
}else{
echo 'OK';
}?>

Referencing Resources like Images

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 wp-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.

If you reference the image via a domain you're less likely to run into problems, but make sure your configuration meets the requirements for loading remote images.

Security restrictions for local files

If you are referencing files on the local filesystem, make sure that you adjust the chroot option correctly. Otherwise DomPDF will reject loading the file.

The chroot path is set to DomPDF's main folder per default. Usually this has to be changed to the path were your assets are located.

$dompdf = new Dompdf();
$dompdf->getOptions()->getChroot(); // somtheing like '/var/www/myproject/vendor/dompdf/dompdf'

$html = <<<HTML
<!DOCTYPE html>
<html lang="de">
    <body>
        <img src="/var/www/myproject/public/img/logo.png">
    </body>
</html>
HTML;

$dompdf->loadHtml($html);

The example above will fail. Because the source of the image is outside of the chroot path. You should change the option to something like this:

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