PDF file format is very useful to download bulk data within the web application. It helps the user to download dynamic content in file format for offline use. With export to PDF functionality, the HTML content is converted to PDF document and downloaded as a PDF file. Within the dynamic web application, a server-side script is used to convert HTML to PDF and generate PDF file using PHP.
If you would like a client-side solution to get PDF document, JavaScript is that the easiest method to convert HTML to PDF. There are various JavaScript library is out there for generating PDF from HTML. JSPDF is one of the best libraries to convert HTML to PDF using JavaScript. During this tutorial, we’ll show you ways to get PDF document and convert HTML to PDF using jquery and JSPDF library.
- Include jquery and JSPDF Library
- Include the jquery and JSPDF library files to use the JSPDF class.
Note that: You don’t have to download the JSPDF library separately; all the required files are included in our source code package.
Instantiate JSPDF Class
Use the following line of code to instantiate and use the JSPDF object in JavaScript.
Generate PDF using JavaScript
The following example shows how to use the JSPDF library to get PDF file using JavaScript.
- Specify the content in text() method of JSPDF object.
- Use the addpage() method to feature new page to PDF.
- Use the save() method to get and download PDF file.
Convert HTML Content to PDF using JavaScript
The following example shows the way to use the JSPDF library to convert HTML to PDF and generate PDF file from HTML content using JavaScript.
- Retrieve the HTML content from the specific element by ID or class.
- Convert HTML content of the specific a part of the online page and generate PDF.
- Save and download the HTML content as a PDF file.
HTML Code:
JavaScript Code:
Useful Configurations
The JSPDF library provides various methods and options to configure the PDF creation. A number of the useful methods of JSPDF class are given below that are commonly used to export HTML to PDF using jQuery.
Change Paper Orientation:
Use the orientation choice to set the paper orientation of the PDF.
Change Text Font:
Use setfont() and setfonttype() methods to line text font and font-style within the PDF.
Change Font Size:
Use setfontsize() method to line font size of the text within the PDF.
Change Text Color:
Use settextcolor() method to line the color of the text within the PDF.
Conclusion
Our example code helps you to convert HTML to PDF and generate PDF file using JavaScript. You’ll easily add the Export to PDF functionality on the online page without counting on the server-side script. The PDF creation functionality is enhanced with JSPDF configuration options as per your needs. Download our source code package to get all the required files including the JSPDF JavaScript library.