Sometimes, we want to save HTML page as PDF using JavaScript.
In this article, we’ll look at how to save HTML page as PDF using JavaScript.
How to save HTML page as PDF using JavaScript?
To save HTML page as PDF using JavaScript, we can use the html2pdf library.
We can add it with
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Then we use it by writing
const element = document.getElementById("element-to-print");
const opt = {
margin: 1,
filename: "myfile.pdf",
image: { type: "jpeg", quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: "in", format: "letter", orientation: "portrait" },
};
await html2pdf().set(opt).from(element).save();
in an async function to select the element with getElementById
.
Then we set some options in the opt
object.
We set the filename
of the PDF, image type and quality, scaling, margin and format.
Then we use html2pdf().set(opt).from(element).save()
to save the element’s content as a PDF.
save
returns a promise.
Conclusion
To save HTML page as PDF using JavaScript, we can use the html2pdf library.