How To Convert HTML To PDF Using JavaScript

In this blog, I will demonstrate how to generate 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.   
  3.   
  4.         <h2 style="color: #0094ff">Hello</h2>  
  5.         <h3>a bit about this Project:</h3>  
  6.         <p style="font-size: large">  
  7.             I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and J query.  
  8.         </p>  
  9.         <table>  
  10.             <tbody>  
  11.                 <tr>  
  12.                     <th>Company</th>  
  13.                     <th>Contact</th>  
  14.                     <th>Country</th>  
  15.                 </tr>  
  16.                 <tr>  
  17.                     <td>Alfreds Futterkiste</td>  
  18.                     <td>Maria Anders</td>  
  19.                     <td>Germany</td>  
  20.                 </tr>  
  21.                 <tr>  
  22.                     <td>Centro comercial Moctezuma</td>  
  23.                     <td>Francisco Chang</td>  
  24.                     <td>Mexico</td>  
  25.                 </tr>  
  26.                 <tr>  
  27.                     <td>Ernst Handel</td>  
  28.                     <td>Roland Mendel</td>  
  29.                     <td>Austria</td>  
  30.                 </tr>  
  31.                 <tr>  
  32.                     <td>Island Trading</td>  
  33.                     <td>Helen Bennett</td>  
  34.                     <td>UK</td>  
  35.                 </tr>  
  36.                 <tr>  
  37.                     <td>Laughing Bacchus Winecellars</td>  
  38.                     <td>Yoshi Tannamuri</td>  
  39.                     <td>Canada</td>  
  40.                 </tr>  
  41.                 <tr>  
  42.                     <td>Magazzini Alimentari Riuniti</td>  
  43.                     <td>Giovanni Rovelli</td>  
  44.                     <td>Italy</td>  
  45.                 </tr>  
  46.             </tbody>  
  47.         </table>  
  48.   
  49.   
  50.     </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.

Ebook Download
View all
Learn
View all