Sometimes, we want to download a div in a HTML page as PDF using JavaScript.
In this article, we’ll look at how to download a div in a HTML page as PDF using JavaScript.
How to download a div in a HTML page as PDF using JavaScript?
To download a div in a HTML page as PDF using JavaScript, we can use the jsPDF library.
To install it, we run
npm install jspdf --save
Then we use it by writing
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
to create a jsPDF
object.
Then we call doc.text
to add the string to the object as its content.
Next, we call save
with the file name of the PDF to save the PDF.
We replace the string with the HTML string of the div that we get from the textContent
property.
Conclusion
To download a div in a HTML page as PDF using JavaScript, we can use the jsPDF library.