[Vuejs]-How to make a pdf file out of html using html2pdf in vue3js?

2πŸ‘

βœ…

I ran into similar issue with Angular long time back. What I have observe

  1. How can I make a pdf file while the html is not seen by the user?

This can not be possible, because html2pdf uses canvas, that is created by html2pdf on the fly.

  1. Would like to take information (html) from different components and merge them into one pdf file. How is this possible?

html2pdf is very limited in functionality, it is not rich as we need. This also doesn’t possible.

After spending a week, I switched to JSpdf, that is much capable of doing these functionality.

It will be one time setup, once you create the format and template, it will be easy and more flexible.

πŸ‘€Abhinav Kumar

1πŸ‘

This is how I solved downloading a PDF with html2pdf without showing the HTML to the user.

I’m using tailwind so the css classes might not make sense for you.

The short explanation is that I’m wrapping the PDF inside a teleport and then a div with display: absolute, z-index: -1 to hide it from the user.

<script setup lang="ts">
import { onMounted } from 'vue';
import html2pdf from 'html2pdf.js';

onMounted(() => {
    // I've not fine tuned these values.
    setTimeout(() => exportToPDF(), 1000)
    // close will unmount this component
    setTimeout(() => emit('close'), 1500)
})

function exportToPDF() {
    html2pdf(document.getElementById('pdf'), {
        filename: 'myFilename.pdf',
    });
}
</script>


<template>
    <teleport :to="'#modal-target'">
        <div class=" absolute">
            <div id="pdf" class="w-[803px]">
              PDF CONTENT
            </div>
        </div>
    </teleport>
 </template>

Leave a comment