How To Convert HTML To PDF Using JavaScript

Introduction

 
In this blog, I will demonstrate how to generate a PDF file of your HTML page with CSS using JavaScript and jQuery.
 
In this blog, we have to add two external JS files for converting the PDF -  JSPDF.js, and html2canvas.js.
 
Creating an HTML Page for converting the HTML to PDF
 
Add the following table in your HTML page.
  1. <form class="form" style="max-width: none; width: 1005px;">  
  2.         <h2 style="color: #0094ff">Hello</h2>  
  3.         <h3>a bit about this Project:</h3>  
  4.         <p style="font-size: large">  
  5.             I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and J query.  
  6.         </p>  
  7.         <table>  
  8.             <tbody>  
  9.                 <tr>  
  10.                     <th>Company</th>  
  11.                     <th>Contact</th>  
  12.                     <th>Country</th>  
  13.                 </tr>  
  14.                 <tr>  
  15.                     <td>Alfreds Futterkiste</td>  
  16.                     <td>Maria Anders</td>  
  17.                     <td>Germany</td>  
  18.                 </tr>  
  19.                 <tr>  
  20.                     <td>Centro comercial Moctezuma</td>  
  21.                     <td>Francisco Chang</td>  
  22.                     <td>Mexico</td>  
  23.                 </tr>  
  24.                 <tr>  
  25.                     <td>Ernst Handel</td>  
  26.                     <td>Roland Mendel</td>  
  27.                     <td>Austria</td>  
  28.                 </tr>  
  29.                 <tr>  
  30.                     <td>Island Trading</td>  
  31.                     <td>Helen Bennett</td>  
  32.                     <td>UK</td>  
  33.                 </tr>  
  34.                 <tr>  
  35.                     <td>Laughing Bacchus Winecellars</td>  
  36.                     <td>Yoshi Tannamuri</td>  
  37.                     <td>Canada</td>  
  38.                 </tr>  
  39.                 <tr>  
  40.                     <td>Magazzini Alimentari Riuniti</td>  
  41.                     <td>Giovanni Rovelli</td>  
  42.                     <td>Italy</td>  
  43.                 </tr>  
  44.             </tbody>  
  45.         </table>  
  46.     </form>  
Add the style of this HTML page.
  1. <style>  
  2.         table {  
  3.             font-family: arial, sans-serif;  
  4.             border-collapse: collapse;  
  5.             width: 100%;  
  6.         }  
  7.   
  8.         td, th {  
  9.             border: 1px solid #dddddd;  
  10.             text-align: left;  
  11.             padding: 8px;  
  12.         }  
  13.   
  14.         tr:nth-child(even) {  
  15.             background-color: #dddddd;  
  16.         }  
  17.     </style>  
Add the "Print" button in this page, above the form tag.
  1. <input type="button" id="create_pdf" value="Generate PDF">  
Add the following script in HTML page for converting it to pdf.
  1. <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>  
  2.    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>  
Add other two scripts for converting the document.
  1. <script>  
  2.     (function () {  
  3.         var  
  4.          form = $('.form'),  
  5.          cache_width = form.width(),  
  6.          a4 = [595.28, 841.89]; // for a4 size paper width and height  
  7.   
  8.         $('#create_pdf').on('click', function () {  
  9.             $('body').scrollTop(0);  
  10.             createPDF();  
  11.         });  
  12.         //create pdf  
  13.         function createPDF() {  
  14.             getCanvas().then(function (canvas) {  
  15.                 var  
  16.                  img = canvas.toDataURL("image/png"),  
  17.                  doc = new jsPDF({  
  18.                      unit: 'px',  
  19.                      format: 'a4'  
  20.                  });  
  21.                 doc.addImage(img, 'JPEG', 20, 20);  
  22.                 doc.save('Bhavdip-html-to-pdf.pdf');  
  23.                 form.width(cache_width);  
  24.             });  
  25.         }  
  26.   
  27.         // create canvas object  
  28.         function getCanvas() {  
  29.             form.width((a4[0] * 1.33333) - 80).css('max-width''none');  
  30.             return html2canvas(form, {  
  31.                 imageTimeout: 2000,  
  32.                 removeContainer: true  
  33.             });  
  34.         }  
  35.   
  36.     }());  
  37. </script>  
  38. <script>  
  39.     /* 
  40.  * jQuery helper plugin for examples and tests 
  41.  */  
  42.     (function ($) {  
  43.         $.fn.html2canvas = function (options) {  
  44.             var date = new Date(),  
  45.             $message = null,  
  46.             timeoutTimer = false,  
  47.             timer = date.getTime();  
  48.             html2canvas.logging = options && options.logging;  
  49.             html2canvas.Preload(this[0], $.extend({  
  50.                 complete: function (images) {  
  51.                     var queue = html2canvas.Parse(this[0], images, options),  
  52.                     $canvas = $(html2canvas.Renderer(queue, options)),  
  53.                     finishTime = new Date();  
  54.   
  55.                     $canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);  
  56.                     $canvas.siblings().toggle();  
  57.   
  58.                     $(window).click(function () {  
  59.                         if (!$canvas.is(':visible')) {  
  60.                             $canvas.toggle().siblings().toggle();  
  61.                             throwMessage("Canvas Render visible");  
  62.                         } else {  
  63.                             $canvas.siblings().toggle();  
  64.                             $canvas.toggle();  
  65.                             throwMessage("Canvas Render hidden");  
  66.                         }  
  67.                     });  
  68.                     throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);  
  69.                 }  
  70.             }, options));  
  71.   
  72.             function throwMessage(msg, duration) {  
  73.                 window.clearTimeout(timeoutTimer);  
  74.                 timeoutTimer = window.setTimeout(function () {  
  75.                     $message.fadeOut(function () {  
  76.                         $message.remove();  
  77.                     });  
  78.                 }, duration || 2000);  
  79.                 if ($message)  
  80.                     $message.remove();  
  81.                 $message = $('<div ></div>').html(msg).css({  
  82.                     margin: 0,  
  83.                     padding: 10,  
  84.                     background: "#000",  
  85.                     opacity: 0.7,  
  86.                     position: "fixed",  
  87.                     top: 10,  
  88.                     right: 10,  
  89.                     fontFamily: 'Tahoma',  
  90.                     color: '#fff',  
  91.                     fontSize: 12,  
  92.                     borderRadius: 12,  
  93.                     width: 'auto',  
  94.                     height: 'auto',  
  95.                     textAlign: 'center',  
  96.                     textDecoration: 'none'  
  97.                 }).hide().fadeIn().appendTo('body');  
  98.             }  
  99.         };  
  100.     })(jQuery);  
  101.   
  102. </script>  
Now, let's see the output. 
 
 
Click on the "Generate PDF " button and get the PDF file like this.