Generating PDF File using JavaScript and JSPDF Library Tutorial

In this tutorial, you will learn how to Generate or Create a PDF File for your web applications on the client side using JavaScript and JSPDF Library. The tutorial aims to provide IT/CS students and new web developers with a reference for learning how to generate PDF files using JavaScript. Here, simple snippets that demonstrate the goal of this tutorial are provided. A sample and working source code zip file is also provided and is free to download.

Why implement a PDF Generation in web applications?

Developers implement a PDF Generation Feature in web applications to achieve the requirement of the system that they are building. It is one of the common features that end-users asked or look for in a web application, especially when exporting some information or reports from the system.

How to generate PDF Files using JavaScript?

There are lots of JS Libraries that are available online that were built for Generating PDF Files in web applications. One of these libraries is the JSPDF Library. JSPDF Library is a free JS library for generating PDFs. See the Installation process of the JSPDF Library on Github.

Demo Snippets

Here are some sample snippets for using the JSPDF Library.

Simple Generating PDF

The following snippet demonstrates how to generate a PDF File. The script explains how to add content on a PDF per line or paragraph. The snippet loads the Bootstrap Framework using CDNs which requires an Internet connection to display the User Interface properly.

Interface

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>jsPDF Library Demo</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="style.css">
  10.  
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <script src="./jquer-3.6.1.min.js"></script>
  13. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  14. <!-- HTML2 Canvas Library -->
  15. <script src="./html2canvas.min.js"></script>
  16. <!-- JSPDF Library -->
  17. <script src="./jspdf.debug.js"></script>
  18. </head>
  19. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  20. <div class="container">
  21. <a class="navbar-brand" href="./">jsPDF Library - DEMO</a>
  22. <div>
  23. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  24. </div>
  25. </div>
  26. </nav>
  27. <div class="container-fluid px-5 my-3">
  28. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  29. <div class="card rounded-0">
  30. <div class="card-header">
  31. <div class="d-flex w-100 align-items-end">
  32. <div class="col-auto flex-shrink-1 flex-grow-1">
  33. <div class="card-title text-muted"><b>Simple PDF Content</b></div>
  34. </div>
  35. <div class="col-auto flex-shrink-1">
  36. <button class="btn btn-primary rounded-0 btn-sm" type="button" id="simple_pdf">Export to PDF</button>
  37. </div>
  38. </div>
  39.  
  40. </div>
  41. <!-- Simple Exporting PDf Card -->
  42. <div class="card-body rounded-0">
  43. <div class="container-fluid">
  44. <div id="simple_pdf_container" class="page-container">
  45. <p>jsPDF Library DEMO</p>
  46. <p>I love SourceCodester</p>
  47. <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sed alias nam nesciunt soluta unde nemo provident vero sit architecto veniam expedita ab, non illum nulla pariatur error magni! Ducimus, facere.</p>
  48. <p></p>
  49. <p>I love SourceCodester</p>
  50. </div>
  51. </div>
  52. </div>
  53. <!-- End of Simple Exporting PDf Card -->
  54. </div>
  55. </div>
  56. </div>
  57. <script src="./script.js"></script>
  58. </body>
  59. </html>

Output

JSPDF DEMO Script

JavaScript

  1. var simple_pdf_btn = document.getElementById('simple_pdf')
  2. window.simple_pdf = function(){
  3. var container = document.getElementById('simple_pdf_container')
  4. let pdf = new jsPDF();
  5.  
  6. var p = container.querySelectorAll('p')
  7. var line = 10;
  8. p.forEach(el => {
  9. pdf.text(pdf.splitTextToSize(el.innerText, 180), 10,line);
  10. line += 10
  11. })
  12. pdf.save('simple_pdf.pdf')
  13. }
  14. window.onload = function(){
  15.  
  16. simple_pdf_btn.addEventListener('click', function(e){
  17. e.preventDefault()
  18. simple_pdf()
  19. })
  20.  
  21. }

Output

JSPDF DEMO Script

Converting HTML Elements to PDF

The following snippet demonstrates how to generate a PDF File that from using the HTML Node as the content.

Interface

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>jsPDF Library Demo</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="style.css">
  10.  
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <script src="./jquer-3.6.1.min.js"></script>
  13. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  14. <!-- HTML2 Canvas Library -->
  15. <script src="./html2canvas.min.js"></script>
  16. <!-- JSPDF Library -->
  17. <script src="./jspdf.debug.js"></script>
  18. </head>
  19. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  20. <div class="container">
  21. <a class="navbar-brand" href="./">jsPDF Library - DEMO</a>
  22. <div>
  23. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  24. </div>
  25. </div>
  26. </nav>
  27. <div class="container-fluid px-5 my-3">
  28.  
  29. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  30. <!-- Converting and Exporting an HTML Element as PDF -->
  31. <div class="card rounded-0">
  32. <div class="card-header">
  33. <div class="d-flex w-100 align-items-end">
  34. <div class="col-auto flex-shrink-1 flex-grow-1">
  35. <div class="card-title text-muted"><b>Exporting HTML Element to PDF</b></div>
  36. </div>
  37. <div class="col-auto flex-shrink-1">
  38. <button class="btn btn-primary rounded-0 btn-sm" type="button" id="html_pdf">Export Element to PDF</button>
  39. </div>
  40. </div>
  41. </div>
  42. <div class="card-body rounded-0">
  43. <div class="container-fluid">
  44. <div id="html_pdf_container" class="page-container">
  45. <h2>Exported HTML</h2>
  46. <p>
  47. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque est odio, lobortis eget pharetra et, commodo non felis. Pellentesque dui dolor, lobortis et blandit vel, commodo nec tellus. Nunc ac metus iaculis, scelerisque quam et, luctus ipsum. Proin euismod nec mi sed venenatis. Suspendisse id nibh ipsum. Sed vestibulum vulputate purus, ac ultricies nulla finibus at. Maecenas vel lacus erat. Nam odio magna, porttitor luctus efficitur ac, auctor sit amet lorem. Etiam ultrices tempus molestie. Sed sagittis nulla nec nibh auctor finibus.
  48. </p>
  49.  
  50. <h2>Table</h2>
  51. <table class="table table-bordered">
  52. <tr>
  53. <th>Header 1</th>
  54. <th>Header 2</th>
  55. <th>Header 3</th>
  56. </tr>
  57. <tr>
  58. <td>Column 1</td>
  59. <td>Column 2</td>
  60. <td>Column 3</td>
  61. </tr>
  62. <tr>
  63. <td>Column 2.1</td>
  64. <td>Column 2.2</td>
  65. <td>Column 2.3</td>
  66. </tr>
  67. </table>
  68.  
  69. </div>
  70. </div>
  71. </div>
  72. </div>
  73. <!-- End of Converting and Exporting an HTML Element as PDF -->
  74. </div>
  75. </div>
  76. <script src="./script.js"></script>
  77. </body>
  78. </html>

Output

JSPDF DEMO Script

JavaScript

  1. var html_pdf_btn = document.getElementById('html_pdf')
  2.  
  3. window.html_pdf = function(){
  4. var container = document.getElementById('html_pdf_container').cloneNode(true)
  5.  
  6. let pdf = new jsPDF('p', 'pt', 'letter');
  7. container.querySelectorAll('table').forEach(el=>{
  8. el.removeAttribute('class')
  9. el.style.borderCollapse = 'collapse'
  10. el.style.width = '100%'
  11. el.querySelectorAll('td, th').forEach(cell=>{
  12. cell.style.border = '1px solid'
  13. })
  14. })
  15. console.log(container.innerHTML)
  16.  
  17. pdf.html(`<div style='position:absolute;left:0; top:0; bottom:0; height:auto; width:600px; padding:10px;'>${container.innerHTML}<div>`, {
  18. callback: function (pdf) {
  19. pdf.save('html_pdf.pdf')
  20. },
  21. windowWidth: 100
  22. }
  23. )
  24. // pdf.save('html_pdf.pdf')
  25. }
  26.  
  27. window.onload = function(){
  28.  
  29. html_pdf_btn.addEventListener('click', function(e){
  30. e.preventDefault()
  31. html_pdf()
  32. })
  33. }

Output

JSPDF DEMO Script

To learn more about how to use JSPDF Library, you can visit their documentation site.

I also provided the working source code zip file that I created for this tutorial. You can download it by clicking the Download Button located after this article's content.

That's it! I hope this Generating PDF File using JavaScript and JSPDF Library Tutorial helps you with what you are looking for and will be useful for your current and future web applications projects.

Happy Coding :)

Add new comment