Convert HTML to PDF in PHP with Dompdf


PDF is a file format created by Adobe Systems for illustrating text and images in a fixed-layout document. PDF is used to downloading the bunch of data in the web application. At the time of download web page content as PDF file, we needed to convert HTML to PDF. This tutorial shows the easiest way for convert HTML to PDF using PHP.

Dompdf is a PHP library that used to convert HTML to PDF file. Using Dompdf library files you can easily implement the generate PDF feature in the web application. Here we’ll provide the simple script to Convert HTML to PDF in PHP with Dompdf.

Before begin take a look at the folders and files structure.

convert-html-to-pdf-in-php-files-structure-codexworld

Installation & Setup

Download stable release of dompdf from GitHub. Extract the downloaded dompdf package and rename it with “dompdf”.

Download php-font-lib from GitHub, extract it and place the entire folder into the dompdf/lib/ directory.

Download php-svg-lib from GitHub, extract it and place the entire folder into the dompdf/lib/ directory.

Instantiate Dompdf Class

Use the following PHP code to instantiate and use the dompdf class.

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

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

Basic Use

Just pass the HTML content to dompdf and genarate the PDF.

<?php
$dompdf
->loadHtml('<h1>Welcome to CodexWorld.com</h1>');

// (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();
?>

Advanced Use

The following code will generate PDF from HTML file (pdf-content.html). Also, it will provide the preview or download option.

<?php
$html 
file_get_contents("pdf-content.html");
$dompdf->loadHtml($html);

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

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

// Output the generated PDF (1 = download and 0 = preview)
$dompdf->stream("codexworld",array("Attachment"=>0));
?>

Options

Dompdf has many options for setting the PDF generation. You can see the lists of available options from here – Dompdf\Options

Conclusion

This article provides the simple script to convert HTML to PDF using Dompdf. Dompdf is a very useful library and you can use it in PHP script easily. Dompdf provides many advanced features which help a lot on PDF generation in PHP. Download our source code package to get all the files together.

Leave a reply

Connect With CodexWorld