PDF is a widely-used cross-platform format for electronic documents that has been a standard for over two decades. The format is ideal for exporting data from a website in the form of various templates, such as important user information, certificates, documents, reports, coupons, instructions, and more.
Overview of Popular PHP Libraries
There are many libraries available in PHP for generating PDFs. The most popular ones are:
- FPDF - A completely free library for creating PDF documents using pure PHP without any markup.
Minimum PHP version 5.1.
Key Features:
- Support for JPEG, PNG, and GIF image formats;
- Header and footer configuration;
- Automatic line breaks and page breaks;
- Links;
- Text alignment;
- Changing the color of document elements; - TCPDF - Minimum PHP version 5.3.
Main Features of the Library:
- Default support for JPEG, PNG, and SVG images;
- Support for all images supported by GD and ImageMagick extensions;
- Automatic line breaks;
- Page breaks;
- Text alignment;
- Text rendering modes (fill, stroke, and clip);
- Automatic page and page group numbering;
- Methods for XHTML + CSS, JavaScript; - HTML2PDF - An API for converting ready HTML markup into PDF format. On the website, you can generate a document by inserting a link into the appropriate field. It uses the TCPDF library.
Requires PHP version 5.6 or higher, as well as the mbstring or gd extension.
Supports all necessary functions:
- Ability to configure page sizes;
- Allows personalization of layout by changing fonts and colors, margins;
- Tools for adding watermarks to documents;
- Uses encryption or passwords to protect PDF files from unauthorized printing and copying; - DOMPDF - An HTML to PDF converter based on PHP. This library converts HTML and CSS (including inline styles and external stylesheets) into PDF documents.
Requires PHP version 7.1 or higher.
The library supports many features such as:
- CSS 2.1 and several CSS3 properties, including @import, @media, and @page rules;
- Most HTML attributes;
- Support for gif, png (8, 24, and 32-bit with alpha channel), bmp, and jpeg images;
- No dependency on third-party PDF libraries.
Example of Generating PDF with DOMPDF Package
Project Initialization
To initialize the project, use the Composer package manager command - “composer init”. Execute it through the terminal in the root of your project.
After the standard procedure of answering all questions proposed by Composer, create a file named index.php in the root of the project. For simplicity, all the logic of the PDF generator will be located here.
Create a folder named resources for storing HTML template files, and a folder named storage for storing the results.
Installing DOMPDF
1) COMPOSER - The library can be installed as a regular PHP package using the package manager command, which will install all necessary dependencies.
composer require dompdf/dompdf
2) GIT - You can either clone the repository or simply download the library as a zip file and place its contents into the project.
git clone https://github.com/dompdf/dompdf/ .
In this case, to use DOMPDF classes in PHP code, you need to include the package autoloader file, which is located at dompdf/autoload.inc.php.
How DOMPDF Works
Creating a PDF document involves several steps:
- Setting up necessary parameters such as paper size and orientation, paths to font and cache files, remote resource access settings, and more.
- Generating the document view.
- Calling the render method to start the document generation process.
- Obtaining the results of the document generation.
DOMPDF Configuration
The main class of the library is the Dompdf\Dompdf class, which contains methods for loading HTML markup, generating the document, and obtaining the result.
The configuration is handled by the Dompdf\Options class, which can be passed as an optional parameter to the constructor of the main Dompdf class.
In the index.php file, include the autoloader created by the package manager and import the necessary classes:
require 'vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
Main Methods of the Options Class:
setChroot - All local files accessed by dompdf must be located in the directory specified in this method. It is not recommended to set this value to "/" as it could allow dompdf to read any files on the server, which is not secure. All local file paths in the template should be relative to the specified directory, which in our case is the previously created resources folder.
setTempDir - The path for storing temporary files for fetching remote images. The specified directory must be writable by the executing process.
setIsRemoteEnabled - Enables remote access to files. If this parameter is set to true, DOMPDF will access images and CSS files from remote sites. For this method to work, the PHP configuration parameter allow_url_fopen must also be set to true.
setAllowedRemoteHosts - List of allowed remote hosts. Each value in the array should be a host name that will be used to filter which resources can be loaded. If isRemoteEnabled is FALSE, this method will have no effect. By default, the value is NULL, which allows any remote host.
setPdfBackend - The extension used for rendering PDF. Allowed settings: "PDFLib", "CPDF", "GD", and "auto". "Auto" will check for the presence of the PDFLib extension and use it if found; otherwise, it will use CPDF.
setFontDir - The location of the directory where DOMPDF will store fonts and font metrics. This directory must exist and be writable.
setDefaultPaperSize - The paper size, defaulting to "a4" for most countries.
All allowable sizes can be found in the class variable \Dompdf\Adapter\CPDF::PAPER_SIZES.
setDefaultPaperOrientation - The default paper orientation. Available options are portrait or landscape.
setLogOutputFile - Log file for recording the output buffer contents after converting HTML to PDF, which can be useful for debugging information.
Example Configuration of Dompdf\Options()
define('ROOT', 'D:/OSPanel/domains/pdf/');
$options = new Options();
$options->setChroot(ROOT . 'resources/');
$options->setTempDir(ROOT . 'storage/tmp');
$options->setIsRemoteEnabled(true);
$options->setFontDir(ROOT . 'resources/fonts/');
$options->setDefaultPaperSize('a4');
$options->setDefaultPaperOrientation('portrait');
$dompdf = new Dompdf($options);
Example of Generating PDF from HTML
The generator class method accepts already prepared HTML markup as a string, so this step does not depend on the library, and any convenient method can be used to generate the markup, whether it's a templating engine, a PHP string variable, or output buffering.
We will use the third option and place the contents of the file resources/pdf-example.php into the $html variable:
ob_start();
require 'resources/pdf-example.php';
$html = ob_get_contents();
ob_end_clean();
Using CSS in DOMPDF has some limitations:
- Table cells cannot be paginated; a table row must fit on one page;
- Does not support CSS Flexbox;
- Does not support CSS Grid;
- A single instance of Dompdf should not be used for rendering more than one HTML document, as residual rendering artifacts can affect future results;
- Using "unprocessed" SVG does not work; you need to either create a link to an external SVG file or use DataURI as follows:
$html = '<img src="data:image/svg+xml;base64,' . base64_encode($svg) . '" ...>';
Including Fonts
By default, DOMPDF supports only the following fonts:
- Helvetica (Normal, Bold, Oblique, and BoldOblique variants)
- Times (Normal, Bold, Oblique, and BoldOblique variants)
- Symbol
- ZapfDingbats
- Courier (Normal, Bold, Oblique, and BoldOblique variants)
These fonts support only the Windows ANSI encoding.
To display characters in the PDF file that are not available in Windows ANSI, you need to specify an external font that will be embedded in the PDF file.
DOMPDF will embed any specified font in the PDF file if it was preloaded or specified in a CSS @font-face rule.
Let's consider both methods for adding external fonts.
- Download the Google font Jost-Regular - https://fonts.google.com/specimen/Jost
Place it at resources/fonts/Jost-Regular.ttf
Then, include the downloaded font using the @font-face rule in the %3Cstyle%3E tags of the template:
@font-face { font-family: "Jost-Regular"; font-style: normal; font-weight: normal; src: url("resources/fonts/Jost-Regular.ttf") format('truetype'); }
Now, you can specify the new font in CSS properties:
body { font-family: 'Jost-Regular'; }
- Include the font directly via a link in the tags:
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet" />
Then, also specify the font family in CSS properties:
body { font-family: 'Montserrat'; }
Example HTML Markup for DOMPDF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet" />
<title>PDF Example</title>
<style>
@font-face {
font-family: "Jost-Regular";
font-style: normal;
font-weight: normal;
src: url("resources/fonts/Jost-Regular.ttf") format('truetype');
}
body {
font-family: 'Montserrat';
}
table {
font-family: 'Helvetica';
}
td, th {
padding: 5px;
}
tr:nth-child(even) {
background-color: #BFE7FF;
}
tr:nth-child(odd) {
background-color: #F5F8FA;
}
img {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<img src="https://ventiontech.com/cdn/shop/products/vention-black-vention-bluetooth-5-3-earphones-tws-true-wireless-headphones-usb-c-aac-sbc-stereo-sports-earbuds-with-mic-hi-fi-headset-35952785981606.jpg?v=1698226840" />
<img src="resources/img/image.jpg" />
<h1>PRODUCT #9823832</h1>
<table>
<tr>
<td><b>Name</b></td>
<td>Earphone</td>
</tr>
<tr>
<td><b>Price</b></td>
<td>$40.00</td>
</tr>
<tr>
<td><b>Description</b></td>
<td>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur quam excepturi omnis veniam odio saepe...</td>
</tr>
<tr>
<td><b>Rate</b></td>
<td>4.6</td>
</tr>
</table>
</body>
</html>
Rendering a PDF Document with PHP (DOMPDF)
To load the provided markup, the Dompdf class has a method called loadHtml. It takes two arguments: the HTML string to load and the encoding method. By default, the second parameter is null, in which case the encoding specified in thetag is used.
Parsing errors are saved in the global array $_dompdf_warnings.
In addition to loading a string, dompdf also provides the loadHtmlFile method, which is identical in use to the previous method but takes a file name or URL as the first parameter for loading.
After loading the markup, you should call the render method, which performs the HTML to PDF conversion:
try {
$dompdf->loadHtml($html);
$dompdf->render();
} catch (Exception $e) {
print_r($e->getMessage());
}
Getting the PDF Render Result
The DOMPDF library provides a convenient method for outputting the result directly to the browser - this method is called stream and it takes two parameters: the name of the output file and an array of additional options.
The options array allows two keys:
- compress - apply content stream compression. Default is 1;
- attachment - sets the HTTP header "Content-Disposition:" to "attachment", which causes the browser to open a download dialog. Default is 1
If you need to save the file to disk or if the standard method for outputting to the browser is not suitable, you can obtain the PDF document as a string using the output method, which takes an optional array with one key, compress.
You can then save this result to a file using any method, for example, the file_put_contents function:
// Outputs the PDF document to the browser
$dompdf->stream('pdf', ['Attachment' => 0]);
// Creates the PDF document at the specified path
file_put_contents('storage/results/' . time() . '.pdf', $pdf);
Complete PHP Code Example for Generating a PDF Document
<?php
ini_set('allow_url_fopen', 'On');
require 'vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
define('ROOT', 'D:/OSPanel/domains/pdf/');
$options = new Options();
$options->setChroot(ROOT . 'resources/');
$options->setTempDir(ROOT . 'storage/tmp');
$options->setIsRemoteEnabled(true);
$options->setFontDir(ROOT . 'resources/fonts/');
$options->setDefaultPaperSize('a4');
$options->setDefaultPaperOrientation('portrait');
$dompdf = new Dompdf($options);
ob_start();
require 'resources/pdf-example.php';
$html = ob_get_contents();
ob_end_clean();
try {
$dompdf->loadHtml($html);
$dompdf->render();
} catch (Exception $e) {
print_r($e->getMessage());
}
// Outputs the PDF document to the browser
$dompdf->stream('pdf', ['Attachment' => 0]);
// Creates the PDF document at the specified path
file_put_contents('storage/results/' . time() . '.pdf', $pdf);