Convert HTML to PDF in PHP using Dompdf

PDF is a file format developed by Adobe Systems for representing text and images in a fixed-layout document. PDF is used to retrieve lots of data or text content in a web application. The PDF file format is an excellent choice for downloading text or HTML content in one file. HTML to PDF conversion is required when downloading web page content as a PDF file. In this tutorial, we will show you how to convert HTML to PDF and generate PDF files using PHP.

How to Convert HTML to PDF

Dompdf is a PHP library that provides an easy way to convert HTML documents to PDF. You can easily generate a PDF from an HTML page in PHP using the Dompdf library. This is the sample way to help you to apply the PDF generation function in your web application and assist you in converting HTML to PDF in PHP using Dompdf.

Install Dompdf Library and Setup

Download dompdf library from https://github.com/dompdf/dompdf and include it in your PHP project. You can install domppdf using a composer command. Run the below command on your Composer.

composer require dompdf/dompdf

Create Database and Table by SQL query

Web need to create database and table, so here I create webscodex database and employees table. employees table holds the records which will be save in employees table and convert to html to pdf from employees table. You can simply create table as following SQL query.

-- Database: `webscodex`
-- --------------------------------------------------------
-- Table structure for table `employees`
--
CREATE TABLE `employees` (
  `id` int(11) NOT NULL PRIMARY KEY, AUTO_INCREMENT,
  `emp_id` varchar(100) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `job_title` varchar(100) NOT NULL,
  `department` varchar(100) NOT NULL,
  `gender` varchar(100) NOT NULL,
  `age` varchar(100) NOT NULL,
  `hire_date` date NOT NULL,
  `annual_salary` varchar(100) NOT NULL,
  `bonus` varchar(100) NOT NULL,
  `city` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

Create Database Configuration File

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create inc\config.php file on your project and put bellow code:

config.php

<?php
   
    // Database configuration
    define('DBSERVER', 'localhost');
    define('DBUSERNAME', 'root');
    define('DBPASSWORD', '');
    define('DBNAME', 'webscodex');
  
    // Create database connection 
    $con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
    
    // Check connection 
    if ($con->connect_error) { 
        die("Connection failed: " . $con->connect_error); 
    }

?>

Create HTML Form using Bootstrap

In this file we have created a form with html using bootstrap in which we have stored employee details and saved it.

index.php

<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Convert HTML to PDF in PHP with Dompdf</title>
        <!-- Bootstrap CSS -->
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">     
    </head>
<body>

<main role="main" class="container">
    <div class="text-center mt-3">
        <h1>Convert HTML to PDF In PHP with Dompdf</h1>
        <p class="lead">Convert HTML to PDF in PHP with Dompdf</p>
    </div>
    <form action="convert.php" method="POST">
        <div class="row">
            <div class="col-md-10 offset-1">
                <div class="card p-3">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="emp_id">Employee Id</label>
                            <input type="text" class="form-control" name="emp_id" placeholder="Employee Id" required="">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="firstName">Full Name </label>
                            <input type="text" class="form-control" name="full_name" placeholder="Full Name" required="">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="job_title">Job Title</label>                        
                            <input type="text" class="form-control" name="job_title" placeholder="Job title" required="">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="department">Department</label>
                            <input type="text" class="form-control" name="department" placeholder="Department" required="">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="gender">Gender</label>
                            <select type="text" class="form-control" name="gender">
                                <option value="male">Male</option>
                                <option value="female">Female</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="age">Age</label>
                            <input type="number" class="form-control" name="age" placeholder="Age">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="hire_date">Hire Date</label>
                            <input type="date" class="form-control" name="hire_date" required="">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="annual_salary">Annual Salary</label>
                            <input type="number" class="form-control" name="annual_salary" placeholder="Annual Salary" required="">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="city">City</label>
                            <input type="text" class="form-control" name="city" placeholder="City" required="">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="bonus">Bonus</label>
                            <input type="number" class="form-control" name="bonus" placeholder="Bonus" required="">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <button type="submit" name="convert-pdf" class="btn btn-success float-right">Convert PDF</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</main>

</body>
</html>

Convert HTML to PDF using Dompdf

In this file we got employee details from Index.php file. and convert it by storing in variables then on click of PDF button the data is saved in employee table then dynamically converted to PDF.

convert.php

<?php

use Dompdf\Dompdf;
use Dompdf\Options;

// Include DOM Pdf autoload file
require_once 'vendor/autoload.php';

// Include database connection file
require_once "config.php";

if(isset($_POST['convert-pdf'])){
    
    $emp_id = $_POST['emp_id'];
    $full_name = $_POST['full_name'];
    $job_title = $_POST['job_title'];
    $department = $_POST['department'];
    $age = $_POST['age'];
    $hire_date = $_POST['hire_date'];
    $annual_salary = $_POST['annual_salary'];
    $city = $_POST['city'];
    $bonus = $_POST['bonus'];
    $gender = $_POST['gender'];
    
    // If New record than insert into database
    $query ="INSERT INTO employees (emp_id, full_name, job_title, department, gender, age, hire_date, annual_salary, bonus, city) 
    VALUES('$emp_id', '$full_name', '$job_title', '$department', '$gender', '$age', '$hire_date', '$annual_salary', '$bonus', '$city')";
    
    $con->query($query);
    $last_id = $con->insert_id; // Get last insert id 
    
    // Get last insert data 
    $sql = "SELECT * FROM employees WHERE id = '$last_id'";
    $execute = $con->query($sql);
    $row = $execute->fetch_array(MYSQLI_ASSOC); // fetch last insert record from employee table

    //instantiate and use the dompdf class
    $dompdf = new Dompdf();
    $options = $dompdf->getOptions();
    $options->setDefaultFont('Courier');

    $dompdf->setOptions($options);

$html ='<style>
        .container{
            width: 750px;
            text-align: center;
        }
        #customers {
            border-collapse: collapse;
            width: 595px;
            margin-left: auto;
            margin-right: auto;
        }

        #customers td, #customers th {
          border: 1px solid #ddd;
          padding: 8px;
        }

        #customers tr:nth-child(even){background-color: #f2f2f2;}
        #customers th {
          padding-top: 12px;
          padding-bottom: 12px;
          text-align: left;
          color: #000;
        }
    </style>
    <div class="container">
        <h1>Convert HTML to PDF In PHP with Dompdf</h1>
        <table id="customers">
            <tbody>
                <tr>
                    <th>Employee Id</th>
                    <td>'.$row["emp_id"].'</td>
                </tr>
                <tr>
                    <th>Firstname</th>
                    <td>'.$row["full_name"].'</td>
                </tr>
                <tr>
                    <th>Job Title</th>
                    <td>'.$row["job_title"].'</td>
                </tr>
                <tr>
                    <th>Department</th>
                    <td>'.$row["department"].'</td>
                </tr>
                <tr>
                    <th>Gender</th>
                    <td>'.$row["gender"].'</td>
                </tr>
                <tr>
                    <th>Age</th>
                    <td>'.$row["age"].'</td>
                </tr>
                <tr>
                    <th>Hire Date</th>
                    <td>'.$row["hire_date"].'</td>
                </tr>
                <tr>
                    <th>Annual Salary</th>
                    <td>'.$row["annual_salary"].'</td>
                </tr>
                <tr>
                    <th>City</th>
                    <td>'.$row["city"].'</td>
                </tr>
                <tr>
                    <th>Bonus</th>
                    <td>'.$row["bonus"].'</td>
                </tr>
            </tbody>
        </table>
    </div>';
    
    // Load content from html file 
    $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 (1 = download and 0 = preview) 
    $dompdf->stream("webscodex_".$last_id,  array("Attachment" => 1));
}

?>

In this above file, the loadHtml() method is used to load the HTML content into dompdf and the render() method generates the PDF file. The setPaper() method is optional, but allows you to set the size and orientation of the paper.

Finally, the stream() method is used to send the generated PDF file to the browser, which prompts the user to download the file. If you want to save the PDF to a file on the server, you can replace the stream() method with output() and pass the file path as the first argument.

Conclusion

In this article, I have explain the process of How to convert HTML to PDF using Dompdf in PHP. I have tried to very simple way to implement convert html to pdf dynamically from database. You can easily extend the functionality according to your needs.To get all the necessary files, including the Dompdf library, download the source code.

Convert HTML to PDF in PHP using Dompdf

Leave a Reply

Your email address will not be published. Required fields are marked *