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. td, th {
  8. border: 1px solid #dddddd;
  9. text-align: left;
  10. padding: 8px;
  11. }
  12. tr:nth-child(even) {
  13. background-color: #dddddd;
  14. }
  15. </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. $('#create_pdf').on('click', function () {
  8. $('body').scrollTop(0);
  9. createPDF();
  10. });
  11. //create pdf
  12. function createPDF() {
  13. getCanvas().then(function (canvas) {
  14. var
  15. img = canvas.toDataURL("image/png"),
  16. doc = new jsPDF({
  17. unit: 'px',
  18. format: 'a4'
  19. });
  20. doc.addImage(img, 'JPEG', 20, 20);
  21. doc.save('Bhavdip-html-to-pdf.pdf');
  22. form.width(cache_width);
  23. });
  24. }
  25. // create canvas object
  26. function getCanvas() {
  27. form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
  28. return html2canvas(form, {
  29. imageTimeout: 2000,
  30. removeContainer: true
  31. });
  32. }
  33. }());
  34. </script>
  35. <script>
  36. /*
  37. * jQuery helper plugin for examples and tests
  38. */
  39. (function ($) {
  40. $.fn.html2canvas = function (options) {
  41. var date = new Date(),
  42. $message = null,
  43. timeoutTimer = false,
  44. timer = date.getTime();
  45. html2canvas.logging = options && options.logging;
  46. html2canvas.Preload(this[0], $.extend({
  47. complete: function (images) {
  48. var queue = html2canvas.Parse(this[0], images, options),
  49. $canvas = $(html2canvas.Renderer(queue, options)),
  50. finishTime = new Date();
  51. $canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
  52. $canvas.siblings().toggle();
  53. $(window).click(function () {
  54. if (!$canvas.is(':visible')) {
  55. $canvas.toggle().siblings().toggle();
  56. throwMessage("Canvas Render visible");
  57. } else {
  58. $canvas.siblings().toggle();
  59. $canvas.toggle();
  60. throwMessage("Canvas Render hidden");
  61. }
  62. });
  63. throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
  64. }
  65. }, options));
  66. function throwMessage(msg, duration) {
  67. window.clearTimeout(timeoutTimer);
  68. timeoutTimer = window.setTimeout(function () {
  69. $message.fadeOut(function () {
  70. $message.remove();
  71. });
  72. }, duration || 2000);
  73. if ($message)
  74. $message.remove();
  75. $message = $('<div ></div>').html(msg).css({
  76. margin: 0,
  77. padding: 10,
  78. background: "#000",
  79. opacity: 0.7,
  80. position: "fixed",
  81. top: 10,
  82. right: 10,
  83. fontFamily: 'Tahoma',
  84. color: '#fff',
  85. fontSize: 12,
  86. borderRadius: 12,
  87. width: 'auto',
  88. height: 'auto',
  89. textAlign: 'center',
  90. textDecoration: 'none'
  91. }).hide().fadeIn().appendTo('body');
  92. }
  93. };
  94. })(jQuery);
  95. </script>
Now, let's see the output.
Click on the "Generate PDF " button and get the PDF file like this.