PDF Generator in Javascript - JSPDF Tutorial

26th OCT 2018

javascript








Welcome folks I am back with another blog post. In this post I will be introducing you guys about a cool library in Javascript. With the help of this library you can generate pdf documents instantly. We can also embed images in the PDF documents. The library name is called JSPDF.




First of all go to https://parall.ax/products/jspdf and either download the library JSPDF in a zip file and then include it into your project.







After download the zip file of the library. Just create a folder and create index.html file and after that include the jspdf.js file and also create another script.js file which will be the custom javascript file which we will create to generate the pdf for us.




<!DOCTYPE html>
<html>
<head>
<title>JSPDF Converter</title>
<body>
</body>
<script src="jspdf.min.js"></script>
</head>
</html>

var doc = new jsPDF()
doc.setFontSize(22)
doc.text(20,20,'This is a title')

doc.setFontSize(16)
doc.text(20,30,'This is some normal sized text underneath')
doc.save("file.pdf")



As you can see in the index.html file we have just included two files first the jspdf library script file and second one is the custom script file which we have written. Apart from that there is nothing to talk about.




In the script.js file we have written some lines of code which needs to be explained so the first line is getting the reference of the library in a doc variable. After that we are using the methods of library to set the font size and also the text to the pdf document and lastly in order to save the file in a pdf format we are using the method of doc.save which will download the file instantly for us when we run the script in the browser.











About Author

Gautam Sharma

Developer, Tech. Evangalist.