首页 > 解决方案 > 在 Vuejs 项目中使用 jsPDF 和 html2canvas(没有 webpack)

问题描述

我正在开发一个 Vuejs 项目中的功能,通过单击一个按钮,用户可以导出一个包含某些 Vuejs 组件的 pdf。一切都很顺利。我 npm 安装了 2 个包,jsPDF 和 html2canvas(这是一个依赖项)。我将 jsPDF 添加到组件中,如下所示:

import jsPDF from 'jspdf'

单击按钮时触发的功能是:

exportpdf() {
    let pdf = new jsPDF('p', 'px', 'a4')
    pdf.addHTML(this.$refs.userinfo, function() {
         pdf.save('web.pdf')
    })
}

单击按钮触发该功能时,出现以下错误:

Uncaught (in promise) Error: You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js...

因此,我在这里遇到了这个问题: Using jsPDF and html2canvas with es6,它解释了 jsPDF 需要 html2canvas 在窗口上。但这只是 Vuejs 中的一个巨大的禁忌(请参阅此处的文章): https ://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

所以,受这篇文章的启发,我在 main.js 中添加了 html2canvas 包:

import html2canvas from 'html2canvas'
...
Vue.use(html2canvas)

现在,当触发该功能时,我得到了这个:

Uncaught (in promise) Provided element is not within a Document

我也尝试了 document.querySelector('#userinfo') - 结果相同。所以现在我认为自己正式陷入困境 - 非常感谢任何帮助。

标签: javascriptvue.jsjspdfhtml2canvas

解决方案


html2canvas 不是一个 Vue 插件,所以你不能在它上面调用 use(...) 。

不过,您可以制作自己的插件。

import html2canvas from 'html2canvas'

let MyPlugin = {
  install(Vue, options) {
    window.html2canvas = html2canvas
  }
}

// ...
Vue.use(MyPlugin)

window.html2canvas = html2canvas如果另一个图书馆需要它,我不确定你为什么反对。


推荐阅读