Home > PHP > How to Convert HTML to PDF using PHP [2024 Complete guide]

How to Convert HTML to PDF using PHP [2024 Complete guide]

In this tutorial, we will learn how to convert HTML and CSS-styled pages to PDF using PHP. We will use third-party libraries to achieve this because PHP does not have an in-built core functionality for this.

You just need a little bit of knowledge of HTML and PHP to convert the HTML page into a PDF with CSS styling. I’ll explain to you each and every step. So let’s get started.

As you probably know or hear from somewhere, there are many PDF converters and third-party PHP libraries. That will allow you to convert your HTML page into PDF with styling. You can also make any modifications in files for better conversion in PDF.

The following are the best libraries to convert HTML to PDF using the PHP script code.

So these are the best PHP libraries for transferring the HTML content with design into PDF files. You can choose any of them.

Also Read: How to Convert an HTML to PDF Using JavaScript?

Let’s have a look at how to convert HTML pages to PDF using these PHP libraries one by one.

Convert HTML to PDF Using TCPDF

The TCPDF PHP library will generate a PDF document with a writing couple of lines of code. It is easy to use this library. Just clone the GitHub repository or you can also download directly from GitHub.

Then you can import this library on your PHP file and use the library function. This library allows you modification while converting HTML pages into PDFs. It has many collections of examples and ready-to-test snippets on its official homepage.

TCPDF features

  • No external libraries are required for the basic functions.
  • All standard page formats, custom page formats, custom margins, and units of measure.
  • UTF-8 Unicode and Right-To-Left languages.
  • TrueTypeUnicode, OpenTypeUnicode v1, TrueType, OpenType v1, Type1 and CID-0 fonts.
  • Font subsetting.
  • Methods to publish some XHTML + CSS code, Javascript, and Forms.
  • Images, graphics (geometric figures), and transformation methods.
  • Supports JPEG, PNG, and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM), and all images supported via ImageMagick (http://www.imagemagick.org/script/formats.php)
  • 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index – Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417.

TCPDF More Advanced Feature

  • JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors, and Transparencies.
  • Automatic page header and footer management.
  • Document encryption up to 256-bit and digital signature certifications.
  • Transactions to UNDO commands.
  • PDF annotations, including links, text and file attachments.
  • Text rendering modes (fill, stroke, and clipping).
  • Multiple columns mode.
  • No-write page regions.
  • Bookmarks, named destinations, and table of contents.
  • Text hyphenation.
  • Text stretching and spacing (tracking).
  • Automatic page break, line break, and text alignments including justification.
  • Automatic page numbering and page groups.
  • Move and delete pages.
  • Page compression (requires php-zlib extension).
  • XOBject Templates.
  • Layers and object visibility.
  • PDF/A-1b support.

TCPDF Example

Follow the below steps to understand how to convert HTML to PDF in PHP using the TCPDF library:

Step 1: Download the TCPDF library from this link https://github.com/tecnickcom/tcpdf

Step 2: After downloading, you will get the zip folder, so unzip it in the folder where your project is hosted.

Step 3: Now create a PHP file (index.php) or any other name it is up to you. Then add the following code in your file.

Step 4: Make sure your TCPDF folder path is correct in first-line require_once('tcpdf_include.php');.

// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Blog Coach');
$pdf->SetTitle('Heading');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(20, 20, 20);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// add a page
$pdf->AddPage();

$html = '<h4>HTML to PDF Using TCPDF</h4><br><p>by yourblogcoach</p>';

$pdf->writeHTML($html, true, false, true, false, '');

// add a page
$pdf->AddPage();

$html = '<h4>Second page</h4>';

$pdf->writeHTML($html, true, false, true, false, '');

// reset pointer to the last page
$pdf->lastPage();
//Close and output PDF document
$pdf->Output('example.pdf', 'I');

As you see I made some changes while converting HTML to PDF using the TCPDF library. You can also make more customization as per your requirements. You can check more customization examples here.

Also Read: How to Convert an HTML to PDF Using JavaScript?

Convert HTML to PDF Using Dompdf

Dompdf is also one of the best PHP libraries to convert any HTML page to a PDF file simply and easily. This library also allows modification while converting our HTML page to a PDF document using the PHP code.

I’ll show you how you can implement it and convert your HTML with CSS styling into a PDF document.

Dompdf features

  • Handles most CSS 2.1 and a few CSS3 properties, including @import, @media & @page rules
  • Supports most presentational HTML 4.0 attributes
  • Supports external stylesheets, either local or through http/ftp (via fopen-wrappers)
  • Supports complex tables, including row & column spans, separate & collapsed border models, individual cell styling
  • Image support (gif, png (8, 24, and 32 bit with alpha channel), bmp & jpeg)
  • No dependencies on external PDF libraries, thanks to the R&OS PDF class
  • Inline PHP support
  • Basic SVG support

Dompdf Example

Follow the below steps to understand how to convert HTML to PDF in PHP using the Dompdf library:

Step 1: Download the Dompdf library from the GitHub repository by this link https://github.com/dompdf/dompdf.

Step 2: After downloading, extract the zip folder and place it where your project is located.

Step 3: Now create a new PHP file (index.php) and include the autoloader script for the Dompdf library to instantiate the Dompdf class.

// Include autoloader 
require_once 'dompdf/autoload.inc.php'; 

// Reference the Dompdf namespace 
use Dompdf\Dompdf; 

// Instantiate and use the dompdf class 
$dompdf = new Dompdf();

Step 4: Now use the following basic code for PDF conversion.

require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('<h4>HTML to PDF using Dompdf</h4><br><p>by yourblogcoach</p>');

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

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

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

In the above code, we are converting the inline HTML content to a PDF file. You can modify the HTML and other settings as per your requirements.

As I said above, this library also allows you to modify and you can do it. It has more advanced features to convert HTML to PDF.

Let’s use this library’s features more extensively.

Convert HTML File to PDF with Dompdf

In the above example, you are converting inline HTML code. Now let’s see how to convert HTML files to PDF files. For this, we will use file_get_contents() PHP function to fetch all HTML content from files. Then pass that HTML content to loadHTML() the library’s function.

// Load content from html file 
$html = file_get_contents("page.html"); 
$dompdf->loadHtml($html);

There are more useful methods that you can use to convert HTML files to PDF and those methods you can check here.

Also Read: How to Convert an HTML to PDF Using JavaScript?

Convert HTML to PDF Using mPDF

mPDF is also a PDF-generation PHP library. It will convert HTML (UTF-8 encoded) to PDF with CSS style. It is based on FPDF and HTML2FPDF with several enhancements. It is a bit slower than the original script (HTML2PDF) but it can generate PDF from large HTML files with CSS support.

mPDF features

  • Accepts UTF-8 encoded HTML
  • Supports almost all languages including
    RTL
    (arabic and hebrew), and
    CJK
    – (chinese-japanese-korean)
  • Bookmarks
  • CSS stylesheets
  • Word spacing and character spacing for justification
  • Nested block-level elements (e.g. P, DIV) including margins, borders, padding, line height, background colors, etc.
  • Support (partial) for floating and fixed-position block-elements
  • Page layout and orientation
  • Text-justification and hyphenation
  • Page numbering
  • Odd and even paging with mirrored margins
  • Page headers & footers
  • Columns
  • Tables – nested tables, rotated, or auto-sized to fit on a page
  • Table of contents
  • Index
  • Watermarks (with customizable text angle)
  • Images in JPG, GIF, PNG, SVG, BMP or WMF format
  • Password protection
  • Annotations
  • Barcodes (EAN13, UPC-A/E, Code 11, 39, 93, 128, Codabar, MSI, IMB, Planet, Postnet, RM4SCC etc.)
  • Import another PDF file and use it as a template
  • Embedded font subsets
  • PDF/A-1b support (ISO 19005-1:2005)
  • PDF/X-1a support
  • PDF/A-3 support (along with ZUGFeRD invoices compatibility)

mPDF Example

Follow the below steps to understand how to convert HTML to PDF in PHP using the mPDF library:

Step 1: Download the mPDF library from this link https://github.com/spipu/html2pdf

Step 2: Extract the folder and place it in your project folder.

Step 3: Create a new .php file (index.php) and import the mPDF autoloader into the file. And then create a new object of the mPDF class.

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new mPDF();

Step 4: Now it is ready to use and you can convert your HTML into a PDF file.

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new mPDF();

// Write some HTML code:
$mpdf->WriteHTML('<h4>HTML to PDF using mPDF</h4>');

// Output a PDF file directly to the browser
$mpdf->Output();

Also Read: How to Convert an HTML to PDF Using JavaScript?

Convert Website URL to PDF

You can also convert any website URL to a PDF file and it is a convenient way to preserve web content for offline viewing or sharing. With this process, users can capture the entire webpage, including text, images, and formatting, in a single, easily accessible document.

All the above three PDF libraries, you can use to generate a PDF file from a website URL.

Let’s see the example of the Dompdf library to convert website URLs to PDF files. Dompdf allows us to generate PDF files from HTML content.

And To get the HTML of any website, we will use the file_get_contents() function of PHP. You have to pass the website URL in the file_get_contents() function and it will fetch the HTML content for you. Then you can use that HTML in the Dompdf function loadHtml() to load the HTML content. After that, you can render it and get the output of that.

require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();

// Load html content from website
$html = file_get_contents("https://yourblogcoach.com/"); 
$dompdf->loadHtml($html);

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

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

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

In the above code, we are fetching the HTML content from the https://yourblogcoach.com website and then using the lodaHtml() to load that HTML content. And in the last, we are setting the page size as A4 and rendering it to get the output.

Conclusion

So we learned the TCPDF, Dompdf, and mPDF libraries to convert the HTML page to PDF files. You see how we can download the libraries and import them into the project and then use their functions to customize and generate the PDF file. Each library has different ways to convert HTML pages into PDFs.

If you found this helpful please share it and if you have any questions please ask me in the comment section, I’ll respond to you as soon as possible.

FAQs

What are TCPDF, Dompdf, and mPDF?

TCPDF, Dompdf, and mPDF are PHP libraries designed for converting HTML content into PDF files dynamically. Each library offers unique features and functionalities, catering to different needs in PHP-based PDF generation.

How to handle page breaks in TCPDF?

You can use the SetAutoPageBreak() function to handle the auto page breaks according to content length.
E.g. $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

How to convert HTML to PDF files using Dompdf?

You can use the loadHtml() method to load the HTML and then use the render() method to render it. To download, use the stream() method.

How to convert HTML to PDF using mPDF?

To convert HTML to PDF with mPDF, WriteHTML() method, and Output() method.

Do TCPDF, Dompdf, and mPDF support the inclusion of images and external assets in the PDF output?

Yes, all three libraries generally support the inclusion of images and external assets in the PDF output.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment