Nowadays, exporting data to PDF is common. The PDF files can contain links, buttons, tables, and formatted data like doc files and can be electronically signed as actual documents.
While providing bulk download functionality to users, PDF can be an idle choice. It can be useful to provide dynamically created data offline. There are plenty of libraries or software to generate PDF files from Web pages. Most of them are JavaScript based.
In this example, we will create a webpage and export it into a PDF file that user can download and view. Here, we will use jsPDF which is the best library to create PDF from HTML using JavaScript. The jsPDF is easy to integrate and has a variety of methods.
Before starting, you need to download the library file for jsPDF or you can use below CDN:
Let's take an example, to create PDF from a current webpage with a click of a button. This webpage will contain a simple heading, paragraph, table, and button. When user clicks on the button it will convert the current webpage into PDF and download it.
Create a new file HTML file and update it as below:
In the above example, we have created a simple webpage and included jsPDF library file. When using click-on button then our PDF generator function is called.
In this function, we will set PDF size as per pepper size and set the height and width of PDF. Then we will convert body part of a webpage and get HTML of it. At last, we will call the save method of jsPDF and give provide one parameter which will be file name of new PDF file.
So whenever user clicks on the download button, it will automatically convert webpage into PDF file and download it to user's system.
There are plenty of methods that can be used while generating PDF file like text(), addPage(), or addImage() functions. Please consider the below example to use those functions :
As per the above example, it will add custom data to PDF files like paragraphs, page, or image to our PDF. Here, we can append data using those functions into our HTML-based PDF file too.
Conclusion
In this article, we have created a simple PDF file using JavaScript and the jsPDF library. There are many configurations available like page orientation or size. Here, we can also specify one portion of a page to generate PDF.