Have you ever been in a situation where you were required to generate PDF of HTML code? Recently, I came across a similar situation. In Drupal 8, there are several PHP libraries that allow you to generate PDF. However, out of curiosity, I thought of finding better alternatives. After some research, I found an interesting library, called mPDF, that converts HTML code to PDF without changing the structure.

mPDF is a smart library that considers the CSS attached to the HTML. Not only CSS, it takes care of almost all the HTML tags like form tags, tables, images, lists etc.

Generating PDF of HTML in custom module

Requirements

mPDF 7.0 requires PHP ^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0. PHP mbstring and gd extensions

Installation

Step 1 Download mPDF via composer and its packageist package mpdf/mpdf.

Step 2 Run the following command in the Drupal root directory: 

$ composer requires mpdf/mpdf

Step 3 Once the mPDF libraries install generate the pdf in the custom module.

Step 4 In custom module, create a controller with routing path(/pdf-download)

Step 5 Now hit the URL (/pdf-download) to download pdf

Whenever you hit the URL, pdf will automatically get downloaded. Further, the HTML which we wish to print can be passed dynamically too. For example, by passing the node contents, we can download the node contents in a pdf file.

Hope you can now generate PDF from encoded HTML in the custom module. If you have any suggestions or queries please comment down let me try to answer.
 

 

comments powered by Disqus