Html to pdf in php

Html to pdf in php

Welcome to programmopedia! I am writing this article to explain the conversion of HTML to pdf in PHP. Pdf is a fixed-layout format developed by adobe to display text and images. This format is widely used by websites to provide the download of important data. So, in this article, I am going to first fetch dynamic data from the database and arrange it properly in  HTML. Then I will use a PHP library called dompdf to generate pdf from html in PHP.  

How to convert Html to pdf in PHP?

I am dividing the complete thought into different small steps to make it easily understandable.

  • First of all, download and set up the dompdf library.
  • Create a PHP document and load the library. 
  • Fetch the dynamic data from the Mysql database.
  •  Arrange the data in proper Html format.
  • Use dompdf functionality to generate pdf.

It’s time to see how each of these steps can be performed practically. Let’s do it.

How to download dompdf?

Dompdf is available on GitHub and it can be downloaded very easily. We can download it through composer but it’s not recommended as a beginner because it can be a bit tricky. I am going to discuss two simple ways to install it.

  • We can use git commands to download the library. 
  •  Open your project root directory and run the following git commands to install the dompdf PHP library.
git clone https://github.com/dompdf/dompdf.git
cd dompdf/lib

git clone https://github.com/PhenX/php-font-lib.git php-font-lib
cd php-font-lib
git checkout 0.5.1
cd ..

git clone https://github.com/PhenX/php-svg-lib.git php-svg-lib
cd php-svg-lib
git checkout v0.3.2
cd ..

git clone https://github.com/sabberworm/PHP-CSS-Parser.git php-css-parser
cd php-css-parser
git checkout 8.1.0
Dompdf example in php
  •  The easiest and simplest way is to download directly from GitHub or their website.
  •   Extract the code and paste it into the root directory of your project.

Now since we have successfully downloaded and installed the dompdf library, it’s time to use it.

How to load dompdf library to generate pdf from html?

Now I am going to explain a simple dom pdf example in PHP.

  • Create a PHP document called “generatepdf.php”.
  • Include “the autoload.inc.php” into your code.
  • reference to dompdf namespace also.
  •  Create a variable and instantiate the dompdf class inside it. So, this variable will act as the object of the dompdf class.

Now we can access the functionality of the dompdf library through its object. Let’s connect to the database to fetch dynamic data to create pdf from html in PHP.

<?php
require "Dompdf/autoload.inc.php";

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set([
    'defaultFont' => 'helvetica',
    'defaultPaperOrientation' => "portrait",
]);

$PdfDoc = new Dompdf($options);

How to fetch dynamic data from database?

I am going to fetch data from the “books” table in the “library” database.

  •  Include your database connectivity file to connect to your database.
  •  Write a MySQL select query to fetch all records from our books table.
  •  First, make sure that the returned rows are greater than 0. Use mysqli_num_rows() function for this purpose.
  • Write a while loop to fetch all the from the database.
require_once "includes/db.inc.php";
$sql = "SELECT * FROM `books` ";
$query = mysqli_query($conn, $sql);
$row = mysqli_num_rows($query);
if ($row == 0) {
    echo "error";
}

while ($result = mysqli_fetch_assoc($query)) {

   
}

How to arrange dynamic data in a table?

This part of the article is really important. I am going to store the dynamic data in $html variable in a tabular format. let’s learn how we can do this.

  • Create a variable $html and start writing html table tags.
  •  First, create one tr tag with four th tags outside the while loop to display the heading of all columns.
  •  Then inside the while loop, concatenate the $html variable and write a tr tag with four td tags to fetch the dynamic database data.
  • Set the border attribute of the table to 1 to generate borders.
$html = "<table border='1'>";
$html .= "
    <tr>
      <th>Title </th>
      <th>Author</th>
      <th>Description</th>
      <th>Date</th>
    </tr>
 ";
while ($result = mysqli_fetch_assoc($query)) {

    $html .= "<tr><td>" . $result['id'] . "</td>";
    $html .= "<td>" . $result['title'] . "</td>";
    $html  .= "<td>" . $result['author'] . "</td>";
    $html  .= "<td>" . $result['description'] . "</td></tr>";
}

$html .= "</table>";
  

That’s it. We have fetched the dynamic data in html tabular format inside the $html variable. Now let’s generate a pdf from HTML in PHP.

How to generate pdf from HTML in PHP?

  •  Use dompdf loadHtml() function to load the content of $html variable. You can use file_get_contents and loadFile() functions to load an HTML markup file.
  •  If you want to change the default page size and orientation, use the setPaper() function. The first parameter takes page sizes and the second takes page orientation. The recommended page size is A4  and the landscape orientation considerably works fine.
  •  Now to render the HTML as a pdf document, we need to call the render() function. After call to render() function the document is ready to be downloaded or previewed in the browser.
  •  Finally, we need the stream() function to send the pdf document to the browser as a downloadable attachment. 
  •  Now if we open this PHP document in a browser, a pdf file will be downloaded containing our dynamic HTML data.
  •  We can also control the output of the stream() function. Specify the name of the pdf file as the first argument. It’s optional and the file will be downloaded with the default name if not specified.
  •  We can use array options as a second argument to further control the pdf download. If we set the attachment option to 0, the browser will preview the document. It’s set to 1 by default and it will directly download the document.
$PdfDoc->loadHtml($html);

//manage the page size
$PdfDoc->setPaper('A4', 'landscape');
//render the html as pdf doc
$PdfDoc->render();
//output the pdf file with name programmopedia
$PdfDoc->stream("programmopedia", array("Attachment" => 0));

?>

Complete code to convert Html to pdf:

Now it’s time to see the complete code at once to understand the concepts. 

<?php
require "Dompdf/autoload.inc.php";

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set([
    'defaultFont' => 'helvetica',
    'defaultPaperOrientation' => "portrait",
]);

$PdfDoc = new Dompdf($options);

require_once "includes/db.inc.php";
$sql = "SELECT * FROM `books` ";
$query = mysqli_query($conn, $sql);
$row = mysqli_num_rows($query);
if ($row == 0) {
    echo "error";
}
$html = "<table border='1'>";
$html .= "
    <tr>
      <th>Title </th>
      <th>Author</th>
      <th>Description</th>
      <th>Date</th>
    </tr>
 ";
while ($result = mysqli_fetch_assoc($query)) {

    $html .= "<tr><td>" . $result['id'] . "</td>";
    $html .= "<td>" . $result['title'] . "</td>";
    $html  .= "<td>" . $result['author'] . "</td>";
    $html  .= "<td>" . $result['description'] . "</td></tr>";
}

$html .= "</table>";



$PdfDoc->loadHtml($html);

//manage the page size
$PdfDoc->setPaper('A4', 'landscape');
//render the html as pdf doc
$PdfDoc->render();
//output the pdf file with name programmopedia
$PdfDoc->stream("programmopedia", array("Attachment" => 0));

?>

Dompdf is not the only PHP library available to convert HTML to pdf. It’s a good and easy-to-use library though has some problems or limitations too. We can also use other PHP libraries like mpdf or fpdf. 
Output of the code:

generate pdf from html php


Now let’s conclude this article. I tried to explain the conversion of HTML to pdf using the dompdf example. I tried to explain the most used configuration and I hope I have conveyed the complete thought. Now you can play around yourself to develop different variations according to your requirements. Thanks for reading and supporting us

Leave a Comment

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

Scroll to Top