jsPDF is a javascript library to generate PDF files from your HTML content. Following are the steps to implement:
First, you should load the js either by using the cdn:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
or by locally downloading it from:
https://unpkg.com/jspdf@latest/dist/jspdf.min.js
Now let’s add the javascript code:
var pdf = new jsPDF();
var leftMargin = 15, topMargin = 15, width = 170;
pdf.fromHTML($('#pdfDiv').html(), leftMargin, topMargin, {
'width': width
});
pdf.save('html-to.pdf');
Above is the javascript part and following is your HTML div element:
<div id="pdfDiv">DIV's content to be saved as PDF</div>
This is all you need to save the content of your HTML element as a pdf file and download it on client-side. First we create an object of jsPDF class. In the above code, we just called the default constructor, jsPDF(), to generate the PDF file with default settings. The class supports following parameters:
orientation: The page orientation you need in your PDF file. Default value is ‘portrait‘. Can be changed to ‘landscape’ as needed. You can also use shortcuts, ‘p’ for portrait and ‘l’ for landscape.
unit: Denotes the units we want to use when coordinates are specified. Accepts ‘pt'(points), ‘mm'(millimeters), ‘cm'(centimeters) and ‘in'(inches). Default value is ‘mm‘.
format: The pageformat. Accepts ‘a3’, ‘a4’, ‘legal’, ‘letter’, etc. Default value is ‘a4‘.
jsPDF provides another feature of special element handlers. You can bypass any HTML element by mentioning its ID in elementHandlers section as following:
var specialElementHandlers = {
'#exclude': function (element, renderer) {
return true;
}
};
pdf.fromHTML($('#pdfDiv').html(), leftMargin, topMargin, {
'width': width,
'elementHandlers': specialElementHandlers
});
Your HTML code will look like:
<div id="pdfDiv">
DIV's content to be saved as PDF.
<div id="exclude">Bypass me</div>
</div>