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
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <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" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <link rel="stylesheet" href="style.css">
- <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>
- <!-- HTML2 Canvas Library -->
- <!-- JSPDF Library -->
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3">
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <div class="card rounded-0">
- <div class="card-header">
- <div class="d-flex w-100 align-items-end">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- </div>
- <div class="col-auto flex-shrink-1">
- </div>
- </div>
- </div>
- <!-- Simple Exporting PDf Card -->
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <div id="simple_pdf_container" class="page-container">
- </div>
- </div>
- </div>
- <!-- End of Simple Exporting PDf Card -->
- </div>
- </div>
- </div>
- </body>
- </html>
Output
JavaScript
- var simple_pdf_btn = document.getElementById('simple_pdf')
- window.simple_pdf = function(){
- var container = document.getElementById('simple_pdf_container')
- let pdf = new jsPDF();
- var p = container.querySelectorAll('p')
- var line = 10;
- p.forEach(el => {
- pdf.text(pdf.splitTextToSize(el.innerText, 180), 10,line);
- line += 10
- })
- pdf.save('simple_pdf.pdf')
- }
- window.onload = function(){
- simple_pdf_btn.addEventListener('click', function(e){
- e.preventDefault()
- simple_pdf()
- })
- }
Output
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
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <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" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <link rel="stylesheet" href="style.css">
- <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>
- <!-- HTML2 Canvas Library -->
- <!-- JSPDF Library -->
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3">
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <!-- Converting and Exporting an HTML Element as PDF -->
- <div class="card rounded-0">
- <div class="card-header">
- <div class="d-flex w-100 align-items-end">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- </div>
- <div class="col-auto flex-shrink-1">
- </div>
- </div>
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <div id="html_pdf_container" class="page-container">
- <p>
- 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.
- </p>
- <table class="table table-bordered">
- <tr>
- </tr>
- <tr>
- </tr>
- <tr>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </div>
- <!-- End of Converting and Exporting an HTML Element as PDF -->
- </div>
- </div>
- </body>
- </html>
Output
JavaScript
- var html_pdf_btn = document.getElementById('html_pdf')
- window.html_pdf = function(){
- var container = document.getElementById('html_pdf_container').cloneNode(true)
- let pdf = new jsPDF('p', 'pt', 'letter');
- container.querySelectorAll('table').forEach(el=>{
- el.removeAttribute('class')
- el.style.borderCollapse = 'collapse'
- el.style.width = '100%'
- el.querySelectorAll('td, th').forEach(cell=>{
- cell.style.border = '1px solid'
- })
- })
- console.log(container.innerHTML)
- pdf.html(`<div style='position:absolute;left:0; top:0; bottom:0; height:auto; width:600px; padding:10px;'>${container.innerHTML}<div>`, {
- callback: function (pdf) {
- pdf.save('html_pdf.pdf')
- },
- windowWidth: 100
- }
- )
- // pdf.save('html_pdf.pdf')
- }
- window.onload = function(){
- html_pdf_btn.addEventListener('click', function(e){
- e.preventDefault()
- html_pdf()
- })
- }
Output
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
- 1172 views