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.
1 2 3 4 |
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> |
Include jsPDF and html2canvas library.
1 2 3 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.2.1/html2canvas.min.js"></script> <script src="js/jsPDF.js"></script> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php include('templates/header.php'); ?> <main role="main" class="container mcontainer"> <div class="row home-sections"> <h2 class="mt-5">Convert HTML Content to PDF using JavaScript</h2> </div> <div class="row"> <div class="col-md-12"> <form name="foo" method="post" class="input-form" enctype="multipart/form-data"> <div style="margin-bottom: 25px" class="input-group"> <div class="custom-file"> <input type="file" name="fileUpload" class="custom-file-input" id="file-upl" required accept=".html,.htm"> <label class="custom-file-label" for="file-upl">Choose file...</label> </div> </div> <div class="content-preview"> <div id="previewHtmlContent"></div> </div> <div style="float: right;"> <button type="button" class="btn btn-info btn-sm" id="previewHtml">Preview</button> <span id="error-message" class="error"></span> <button type="button" class="btn btn-success hidden btn-sm" id="convertHTMLToPDF">Create PDF</button> </div> </form> </div> </div> </main> <?php include('templates/footer.php'); ?> |
Step 3: Generate PDF using JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
jQuery(document).ready(function() { // preview file jQuery(document).on('click', 'button#previewHtml', function() { previewHTMLFile(); }); // convert pdf file jQuery(document).on('click', 'button#convertHTMLToPDF', function() { saveHTMLToPDF(); }); }); // upload pdf file and preview method function previewHTMLFile() { var fileContents = ''; jQuery("#error-message").html(""); var uplfilePath = jQuery('input#file-upl').get(0).files[0]; if (jQuery(uplfilePath).length != 0) { var filereader = new FileReader(); filereader.onload = function(e) { fileContents = e.target.result; jQuery(".content-preview").show(); jQuery("#previewHtmlContent").html(fileContents); jQuery("#previewHtml").addClass('hidden'); jQuery("#convertHTMLToPDF").removeClass('hidden'); } filereader.readAsText(uplfilePath); } else { jQuery("#error-message").html("Please choose file.").show(); } } // generate pdf file function saveHTMLToPDF() { const { jsPDF } = window.jspdf; var doc = new jsPDF('l', 'mm', [1200, 1210]); var pdfJS = document.querySelector('#previewHtmlContent'); doc.html(pdfJS, { callback: function(doc) { // Save the PDF doc.save("sample-document.pdf"); }, x: 10, y: 10 }); } |
Step 4: Upload file and Preview HTML
call function previewHTMLFile() to show HTML file preview.
1 2 3 4 |
// preview file jQuery(document).on('click', 'button#previewHtml', function() { previewHTMLFile(); }); |
Create function previewHTMLFile() to upload html file and preview
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// upload html file and preview function previewHTMLFile() { var fileContents = ''; jQuery("#error-message").html(""); var uplfilePath = jQuery('input#file-upl').get(0).files[0]; if (jQuery(uplfilePath).length != 0) { var filereader = new FileReader(); filereader.onload = function(e) { fileContents = e.target.result; jQuery(".content-preview").show(); jQuery("#previewHtmlContent").html(fileContents); jQuery("#previewHtml").addClass('hidden'); jQuery("#convertHTMLToPDF").removeClass('hidden'); } filereader.readAsText(uplfilePath); } else { jQuery("#error-message").html("Please choose file.").show(); } } |
Step 5: Convert HTML File to PDF
call function saveHTMLToPDF() to convert HTML to PDF, save and download
1 2 3 4 |
// convert pdf file jQuery(document).on('click', 'button#convertHTMLToPDF', function() { saveHTMLToPDF(); }); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// generate pdf file and save function saveHTMLToPDF() { const { jsPDF } = window.jspdf; var doc = new jsPDF('l', 'mm', [1200, 1210]); var pdfJS = document.querySelector('#previewHtmlContent'); doc.html(pdfJS, { callback: function(doc) { // Save the PDF doc.save("sample-document.pdf"); }, x: 10, y: 10 }); } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!doctype html> <html lang="en"> <head> <meta name="google-site-verification" content="jlByZLO42gqjZgfAEj29-VYfJC2hEwUj1KSeQpiGJcI" /> <link rel="canonical" href="https://techarise.com/" /> <meta name="author" content="TechArise"> <meta name="description" content="Learn Web Development Tutorials & Web Developer Resources, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, with TechArise tutorials. View live demo"> <meta name="keywords" content="TechArise, tutorial TechArise, tutorials, freebies, resources, web development, webdev, demo, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, php script, dynamic web content" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="icon" type="image/ico" href="https://techarise.com/wp-content/themes/v1/favicon.ico"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/style.css" /> <title> Convert HTML Content to PDF using JavaScript | Tech Arise</title> </head> <body> <?php include('menus.php'); ?> |
menus.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<header> <!-- Fixed navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark" style="background: #273E4A!important;"> <a class="navbar-brand" href="https://techarise.com"><strong>Tech Arise</strong></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span></a> </li> </ul> <span class="nav-item dropdown"> <a style="color:#fff;" class="nav-link" href="index.php" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-user" style="width:20px;"></i> Demo </a> </span> </div> </nav> </header> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 |
<footer class="footer"> <div class="container"> </div> </footer> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.2.1/html2canvas.min.js"></script> <script src="js/jsPDF.js"></script> </body> </html> |