I have a vue as below which I want to download as PDF when I click on a button in main_component. Please help me find a way around to do so.
download.vue
<template> <div> This file includes a set of instructions to finish this process </div> </template>
main_file.vue
<template> <div> *Button to download the above file as PDF* </div> </template>
Advertisement
Answer
You can use the Javascript window.print document method and import your download.vue component into main_file.vue component and then pass the innerHTML of download.vue component by using $refs.
Method 1: Save as PDF without any plugin.
Here is the code snippet that will give you a dialog of print, where you can print or save PDF.
main_file.vue
<template> <div> <button @click="printDownload">Print Download</button> <Download v-show="false" ref="DownloadComp" /> </div> </template> <script> import Download from './Download' export default { components: { Download, }, methods: { printDownload () { let w = window.open() w.document.write(this.$refs.DownloadComp.$el.innerHTML) w.document.close() w.setTimeout(function () { w.print() }, 1000) } }, } </script>
UPDATE
Method 2: Generate PDF of Any Component with CSS: To generate pdf and auto-download with all inner HTML and CSS, use the VueHtml2pdf npm package; it has many customization options and can help you download your component into PDF.
Here is working example with your code:
<template> <div> <button @click="downloadPDF">Print Download</button> <VueHtml2pdf :manual-pagination="true" :enable-download="true" ref="DownloadComp"> <section slot="pdf-content"> <Download /> </section> </VueHtml2pdf> </div> </template> <script> import VueHtml2pdf from 'vue-html2pdf' import Download from './Download' export default { components: { Download, VueHtml2pdf }, methods: { downloadPDF () { this.$refs.DownloadComp.generatePdf() } }, } </script>