简体   繁体   English

如何在vue3js中使用html2pdf从html中制作pdf文件?

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

I am trying to convert my html into .pdf with the use of html2pdf .我正在尝试使用html2pdf将我的 html 转换为 .pdf 。 I have no problems when it is a simple one file component with html and a <button> inside <template> and all the methods are inside this file, like below:当它是一个简单的单文件组件时,我没有问题,在<template>包含 html 和<button> <template>并且所有方法都在这个文件中,如下所示:

<template>
    <div ref="pdf">
        Hello, this is my awesome html converted into pdf
    </div>
    <button @click="generatePDF">
        make PDF
    </button>
</template>
<script>
import html2pdf from "html2pdf.js"
export default {
    methods: {
        generatePDF() {
            const doc = this.$refs.pdf
            html2pdf(doc)
        },
    },
}
</script>
<style></style>

The problem is, that the solution above takes space in the DOM.问题是,上面的解决方案占用了 DOM 中的空间。 So everything is visible to the user, which I would like to avoid.所以一切对用户都是可见的,我想避免这种情况。 Also, a parent-child relationship is a no-go (like I export the button to a parent component) because the whole html can still be seen.此外,父子关系是不可行的(就像我将按钮导出到父组件一样),因为仍然可以看到整个 html。 If I would use v-if or v-show , then I get a blank pdf file.如果我使用v-ifv-show ,那么我会得到一个空白的 pdf 文件。

Questions:问题:

  1. How can I make a pdf file while the html is not seen by the user?如何在用户看不到 html 的情况下制作 pdf 文件?
  2. Would like to take information (html) from different components and merge them into one pdf file.想从不同的组件中获取信息 (html) 并将它们合并到一个 pdf 文件中。 How is this possible?这怎么可能?

I ran into similar issue with Angular long time back.很久以前,我遇到了与 Angular 类似的问题。 What I have observe我所观察到的

  1. How can I make a pdf file while the html is not seen by the user?如何在用户看不到 html 的情况下制作 pdf 文件?

This can not be possible, because html2pdf uses canvas, that is created by html2pdf on the fly.这是不可能的,因为html2pdf使用由 html2pdf 动态创建的画布。

  1. Would like to take information (html) from different components and merge them into one pdf file.想从不同的组件中获取信息 (html) 并将它们合并到一个 pdf 文件中。 How is this possible?这怎么可能?

html2pdf is very limited in functionality, it is not rich as we need. html2pdf功能非常有限,没有我们需要的那么丰富。 This also doesn't possible.这也是不可能的。

After spending a week, I switched to JSpdf , that is much capable of doing these functionality.花了一周后,我切换到JSpdf ,它非常有能力完成这些功能。

It will be one time setup, once you create the format and template, it will be easy and more flexible.这将是一次性设置,一旦您创建了格式和模板,它将变得更加简单和灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM