How to use jsPDF library In HTML
jsPDF is a JavaScript library that helps create PDF files in the browser. It’s used for easily generating PDF documents within web applications, providing functions for content creation and styling. In order to generate a pdf in runtime, we can use the jsPDF library. The steps are:
- Include the jsPDF CDN in the <head> tag in the HTML document. The CDN is given below, search ‘JsPDF CDN’ at Google for the latest version.
- Generate a pdf from the HTML div using the ‘fromHTML’ method.
- Save the file using the save() method in javascript.
Example: In this example, we will see the basic use of the jsPDF library with an example.
HTML
<!DOCTYPE html> < html > < head > < title >jsPDF Library</ title > <!--JSPDF CDN--> < script src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js" > </ script > < style > .container { position: fixed; top: 20%; left: 28%; margin-top: -65px; margin-left: -100px; border-radius: 7px; } #makepdf { box-sizing: content-box; width: 700px; height: 150px; padding: 30px; border: 1px solid black; font-style: sans-serif; background-color: #f0f0f0; } #button { background-color: #4caf50; border-radius: 5px; margin-left: 650px; margin-bottom: 5px; color: white; } h2 { text-align: center; color: #24650b; } </ style > </ head > < body > < div class = "container" > < button id = "button" >Generate PDF</ button > < div id = "makepdf" > < h2 >Welcome to w3wiki</ h2 > < ul > < li > < h4 > We are going to generate a pdf from the area inside the box </ h4 > </ li > < li > < h4 > This is an example of generating pdf from HTML during runtime </ h4 > </ li > </ ul > </ div > </ div > < script > let button = document.getElementById("button"); button.addEventListener("click", function () { let doc = new jsPDF("p", "mm", [300, 300]); let makePDF = document.querySelector("#makepdf"); // fromHTML Method doc.fromHTML(makePDF); doc.save("output.pdf"); }); </ script > </ body > </ html > |
Output:
How to design runtime generated PDF via HTML ?
Many times, we have faced the problem of saving a particular webpage or any online specific element that needs to save in the form of a PDF file while using the browser. In that case, either we have used the 3rd party extension or any app or tools to generate it into a PDF file. In this article, we will learn to design the runtime-generated pdf file via HTML.
Let’s understand all the 3 concepts one by one with the help of examples.
Table of Content
- Print the specific element and save it as a PDF
- Using jsPDF library
- Using html2pdf library