After a few hours of research, I found some of exporting the content of divs to pdf, including all styles. According to this page, vue-html2pdf
does not work properly, so i used html2pdf
. It takes a div with ref
and converts it to pdf, downloading it at the same time:
<div ref="printable">Hello</div>
<button @click="export()">Export to PDF</button
export() {
html2pdf(this.$refs.document, {
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { dpi: 192, letterRendering: true },
jsPDF: { unit: 'in', format: 'letter', orientation: 'landscape' }
})
},
The problem is that it includes all the styles and i cannot export a hidden div. Is there any proper way to achieve this?
You can set a ref
for the hidden element and remove the hidden Attribute before pdf generation and set it again as soon as the generated function called. Here I edit the sandbox. You can see a heading in the pdf which is hidden in the page.
<template>
<div id="app" ref="document">
<img width="200" src="./assets/logo.png">
<router-view></router-view>
<h1 ref="hide" hidden>This is shown in pdf</h1>
<button @click="exportToPDF">Export to PDF</button>
</div>
</template>
<script>
import html2pdf from "html2pdf.js";
export default {
name: "app",
methods: {
exportToPDF() {
let data = Object.assign({}, this.$refs);
data.hide.removeAttribute("hidden");
html2pdf(data.document, {
margin: 1,
filename: "document.pdf",
image: {
type: "jpeg",
quality: 0.98
},
html2canvas: {
dpi: 192,
letterRendering: true
},
jsPDF: {
unit: "in",
format: "letter",
orientation: "landscape"
}
});
data.hide.setAttribute("hidden", "hidden");
}
}
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>