Convert HTML Content to PDF using JavaScript

PDF stands for the Portable Document Format. The PDF format is commonly used for saving documents and publications in a standard format that can be viewed on multiple devices. For example, invoices, concert tickets, and flight tickets tend to be available as PDF downloads.
In previous article, we have explained about how to Create PDF file using Codeigniter with MYSQL. In this tutorial, I will explain you how to Convert HTML Content to PDF in JavaScript using jsPDF library.
Before starting to implement the Convert HTML Content to PDF using JavaScript, look files structure:
  • html-pdf-javascript
    • css
    • js
      • jsPDF.js
    • templates
      • header.php
      • footer.php
    • index.php
    • menus.php.php
Step 1: Include jQuery, Bootstrap and jsPDF Library
Include the jQuery and jsPDF library files to use the jsPDF class.
Include jsPDF and html2canvas library.
Step 2: Create HTML Form
Create a file named index.php, we will create HTML form with file input to browse HTML file to convert into PDF.
Step 3: Generate PDF using JavaScript
Step 4: Upload file and Preview HTML
call function previewHTMLFile() to show HTML file preview.
Create function previewHTMLFile() to upload html file and preview
Step 5: Convert HTML File to PDF
call function saveHTMLToPDF() to convert HTML to PDF, save and download
We will implement function saveHTMLToPDF() to get HTML file content and convert to PDF using function html() from jsPDF. The function save() called from jsPDF to dwonload output PDF file.
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
menus.php
footer.php