我使用vueHtml2Pdf生成我的页面到pdf,但是当我在VueHtml2pdf标签中包装我的内容时,页面上没有任何呈现,但是当我单击“下载”按钮时,它就会下载。(Nuxt)
methods: {
downloadPDF() {
this.$refs.html2Pdf.generatePdf()
},
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<ArticleActions @download="downloadPDF()" />
<client-only>
<vue-html2pdf
ref="html2Pdf"
:show-layout="false"
:enable-download="true"
:pdf-quality="2"
:manual-pagination="true"
pdf-content-width="100%"
:html-to-pdf-options="htmlToPdfOptions"
>
<section slot="pdf-content">
<!-- content -->
<div
v-interpolation="{ newWindow: true }"
class="articleContent__content"
v-html="article.content"
></div>
<!-- /content -->
</section>
</vue-html2pdf>
</client-only>
发布于 2022-11-06 17:00:53
我有一个Nuxtv3的工作解决方案(服务器端呈现)。在尝试了一系列不同的特定于vue的包(包括vue-html2pdf
)之后,我意识到大多数包都是为Vue2编写的。
相反,我选择直接使用html2pdf
。
在组件中直接导入html2pdf
时,需要添加将html转换为pdf的功能,Nuxt抛出以下错误:ReferenceError: self is not defined
。这在本质上是因为导入库的行也运行在服务器端,并且在导入库时,它尝试访问服务器端未定义的变量。
我的解决方案是创建一个只在客户端运行的自定义插件。在Nuxtv3中这样做非常简单,只需用.client.ts
来结束文件名,而不是只使用.ts
。下面是plugins/html2pdf.client.ts
的样子:
import html2pdf from 'html2pdf.js'
export default defineNuxtPlugin(() => {
// had to make a plugin because directly importing html2pdf.js in the component
// where I need to use it was causing an error as the import would run on the server
// side and html2pdf.js is a client-side-only library. This plugin runs on the
// client side only (due to the .client extension) so it works fine.
return {
provide: {
html2pdf: (element, options) => {
return html2pdf(element, options)
}
}
}
})
现在,我可以在我的组件中安全地使用它:
const { $html2pdf } = useNuxtApp()
function downloadPDF() {
if (document) {
const element = document.getElementById('html2pdf')
// clone the element: https://stackoverflow.com/questions/60557116/html2pdf-wont-print-hidden-div-after-unhiding-it/60558415#60558415
const clonedElement = element.cloneNode(true) as HTMLElement
clonedElement.classList.remove('hidden')
clonedElement.classList.add('block')
// need to append to the document, otherwise the downloading doesn't start
document.body.appendChild(clonedElement)
// https://www.npmjs.com/package/html2pdf.js/v/0.9.0#options
$html2pdf(clonedElement, {
filename: 'filename.pdf',
image: { type: 'png' },
enableLinks: true
})
clonedElement.remove()
}
}
html2pdf
的基本用法:https://www.npmjs.com/package/html2pdf.js/v/0.9.0#usage
html2pdf
:https://www.npmjs.com/package/html2pdf.js/v/0.9.0#options的配置
https://stackoverflow.com/questions/70243553
复制相似问题