In this tutorial, we will learn how to convert HTML to PDF in Vue js for generating reports, invoices, or other printable documents. We achieve this using both methods with a library or without a library. Follow this tutorial and use the provided code in your project.
How can you generate a PDF from HTML code using Vue.js?
This code below generates a PDF from HTML content using Vue js and JavaScript. Feel free to use this code in your project.
Vue Js Convert HTML to PDF Example
<script type="module">
const app = Vue.createApp({
methods: {
async downloadPDF() {
const htmlContent = document.getElementById("pdf-content").outerHTML;
const iFrame = document.createElement("iframe");
iFrame.style.display = "none";
document.body.appendChild(iFrame);
const pdfBlob = await new Promise((resolve) => {
iFrame.onload = () => {
const iFrameWindow = iFrame.contentWindow;
iFrameWindow.print();
iFrameWindow.addEventListener("afterprint", () => {
const pdfBlob = iFrameWindow.Blob;
resolve(pdfBlob);
document.body.removeChild(iFrame);
}, { once: true });
};
iFrame.srcdoc = htmlContent;
});
},
},
});
app.mount("#app");
</script>
Output of Vue Js Pdf Generation
To generate a PDF from HTML code in Vue js, you can also use a library like jsPDF.
Vue JS Print Pdf using jsPDF | Example
<div id="app">
<div ref="pdfContent">
<h1>Print PDF from HTML code using Vue.js and jsPDF</h1>
<p>
This is some HTML content that will be converted to a PDF when you click the button below.
</p>
<button @click="printPDF">Print PDF</button>
</div>
</div>
<script type="module">
const app = Vue.createApp({
methods: {
printPDF() {
const pdf = new jsPDF();
const content = this.$refs.pdfContent.innerHTML;
pdf.fromHTML(content);
pdf.save('document.pdf');
}
}
});
app.mount("#app");
</script>