Welcome folks today in this blog post we will be exporting html with custom css styles to pdf document in browser using jspdf & html2canvas in javascript. All the full source code of the application is given below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.2.3/jspdf.plugin.autotable.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script> </head> <body> </body> </html> |
As you can see we are including the jspdf
and htm2canvas
library cdn in the above html file. And now we need to write the html inside the body as shown below
1 2 3 4 |
<div id="text"> <h1 style="color: yellow;background-color: black;">Hello This is a heading</h1> </div> <button id="downloadButton" onclick="downloadpdf()">Download PDF</button> |
As you can see we have the div inside it we have a simple h3
heading of text color yellow and it has a background color of black. And then we have the simple button to download the pdf document. And we have given the onclick event listener. Now we need to define the method which is downloadpdf()
as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
async function downloadpdf() { var doc = new jsPDF('l', 'pt'); await html2canvas(document.getElementById("text"), { //allowTaint: true, //useCORS: true, width: 520, }).then((canvas) => { doc.addImage(canvas.toDataURL("image/png"), "PNG", 5, 5, 500, 200); }); doc.save("file.pdf"); } |
In the above javascript code we are making the new constructor of jsPDF()
and then we are taking the screenshot of the div
section with css styles using the html2canvas library. And then inside the callback we got the canvas element and using this we are adding this image to the pdf document using addImage()
method. And for this we are first of all converting the canvas image to base64 data url using the toDataURL()
method. And then we are saving the pdf document using the save()
method.