PDFS in PHP with DomPDF, HTML and CSS

In this tutorial we are going to see step by step how we can easily generate PDFs with PHP, HTML and CSS.

Content

  • How to get PDFs using PHP?
  • How to start forming a pdf with PHP
    • Use DomPDF through its download
    • DomPDF with Git commands
    • DomPDF with composer
    • Prerequisites for using DomPDF
  • Basic example of creating PDF with DomPDF
  • Extra: Advanced functions to generate PDF
  • Conclusion: It is very easy to generate PDFs in PHP
  • Recommendations to create your PDF without errors

How to get PDFs using PHP?

PDF does not natively support the creation of PDFs, therefore, we must resort to a library designed specifically for this purpose. Among the libraries that we can find I have chosen, for this tutorial, DOMpdf, a library open source which provides a good solution to the problem that is often dealt with with this file format.

Dompdf is a fantastic library, capable of generating a PDF from content in HTML language and CSS styles (mainly CSS 2.1 and with support for some CSS3 properties). As you will see, you have the possibility of giving your PDF files a design with the use of these markup languages ​​in a similar way to how we would do it to generate a web page.

How to start forming a pdf with PHP

Dompdf, as free software, is available on GitHub and can also be installed with Composer. Let’s quickly see the 3 ways to include the library in our projects.

Use DomPDF through its download

The first way to work with Dompdf is to download it from GitHub: download the library from GitHub. Once you have the file .zip on your computer, unzip it in the directory you use for the libraries. Then, you just have to include the file autoload.inc.php which is located in the library directory on the script where you are going to use it:

require_once 'dompdf/autoload.inc.php';

DomPDF with Git commands

If you are comfortable dealing with Git and its terminal you can include the library as follows:

  • Navigate through the file explorer to the directory where you want to include the library.
  • Open the Git terminal
  • Run the following commands:
    • git clone https://github.com/dompdf/dompdf.git
    • cd dompdf
    • git clone https://github.com/PhenX/php-font-lib.git lib/php-font-lib
    • cd lib/php-font-lib
    • git checkout 0.4
    • cd ..
    • git clone https://github.com/PhenX/php-svg-lib.git php-svg-lib
    • cd php-svg-libgit checkout v0.1
  • Now include a library in the programming script where you are going to create your PDFs:
    • require_once ‘dompdf/autoload.inc.php’;

DomPDF with composer

With composer you will only need to execute the following command in the root directory of your project:

composer require dompdf/dompdf

Prerequisites for using DomPDF

Before you start fighting with DomPdf and generate PDF You must take into account several limitations and requirements for full compatibility:

  1. The DomPdf library requires a PHP version higher than 5.3. In principle, this point will be fulfilled by any recent installation of XAMPP, WAMP or LAMP.
  2. You can use HTML tags but never HTML5.
  3. The style sheets can be written in CSS, up to CSS version 2.1. Some properties belonging to the most recent version, CSS3, are also supported, although their number is very small.
  4. DOMPDF is programmed with OOP (Object Oriented Programming), and although it is not completely necessary to master this type of programming to use the library, I do recommend that you have at least a basic understanding of creating objects and using their methods.

Basic example of creating PDF with DomPDF

Once the library is installed in our project, and correctly included, we are going to see a simple example to generate your first PDF.

The first thing to do is create an object of the DOMPDF class. This object will be the one that at all times controls the construction and subsequent PDF rendering. We will also establish that the size of the paper to be used will be A4 with the method set_paper() of the class DOMPDF.

<?php
$dompdf = new DOMPDF();
$dompdf->set_paper("A4");

Secondly, you have to store an HTML output in a PHP variable, that is, save an HTML sheet similar to what a web page would be. For this we can use a buffer PHP:

ob_start();
include 'mi_template_html_de_pdf.php';
$html_para_pdf = ob_get_clean();

Once we have our HTML inside the variable we will load it in the object DOMPDF with the method load_html() of DOMPDF.

$dompdf->load_html($html_para_pdf);

You almost have it! All that remains is to indicate that we want the HTML to be transformed into a valid PDF file, save it or view it.

$dompdf->render(); //este comando renderiza el PDF
$output = $dompdf->output(); //extrae el contenido renderizado del PDF
file_put_contents('mipdf.pdf', $output); //guarda el PDF en un fichero llamado mipdf.pdf

Extra: Advanced functions to generate PDF

Dompdf has many more features than the views in the previous example, some of them would be:

  • Set default font from the created PDF: $dompdf->set_option(‘defaultFont’, ‘Courier’);
  • Get the height of the PDF document: $dompdf->get_height()
  • Get the width of the document: $dompdf->get_width()
  • Display the pdf directly in the HTML output from the web page: $dompdf->render(‘pdf_name.pdf’, array(‘Attachment’=>false))
  • To establish a custom document size: $dompdf->set_paper(x, y, width, height)

Conclusion: It is very easy to generate PDFs in PHP

In this article we have seen how, in a simple way, How can PDFs be generated working with the same languages ​​that our web pages use?.

Also, although DomPDF is a good library, special care must be taken, as it does not tolerate malformed HTML documents.

In addition, one must have special be careful generating large PDFsas the server will run out of memory in a heartbeat.

Recommendations to create your PDF without errors

I would not like to end this article without pointing out a few important information so that you can generate your PDFs with the minimum amount of errors possible:

  1. try to use HTML tables to structure the data. DomPDF doesn’t really like CSS3 properties like Float.
  2. If you are going to generate very large PDFs make sure that the PHP configuration accepts large amounts of memory allocation. Do this with caution, the server may be slow to respond.
  3. Generate the structure of your PDFs similar to how you would a normal web page. Use full HTML HEAD and BODY tags and use CLASSES and IDs to apply styles like fonts, colors, or spacing.
  4. Compose the HTML and CSS of your PDF with files reserved for this purpose, that is, a php file with the purpose of being a template.
  5. In case of errors, always check that the HTML structure is properly marked and you have not left tags without closing or with attributes not used correctly.

Leave a Reply