javascript - 在 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') - 结果相同。所以现在我认为自己正式陷入困境 - 非常感谢任何帮助。
解决方案
html2canvas 不是一个 Vue 插件,所以你不能在它上面调用 use(...) 。
不过,您可以制作自己的插件。
import html2canvas from 'html2canvas'
let MyPlugin = {
install(Vue, options) {
window.html2canvas = html2canvas
}
}
// ...
Vue.use(MyPlugin)
window.html2canvas = html2canvas
如果另一个图书馆需要它,我不确定你为什么反对。
推荐阅读
- c# - 如何在引导模式中绑定 ViewComponent
- python - 如何使注册页面只接受一个电子邮件地址
- xml - 与 XPath 一起使用时,如何在 xmlstarlet 更新命令中正确添加 xml 命名空间
- here-api - HERE Map Tile Labels 仅在某些缩放级别使用指定语言?
- c# - 如何在 C# 中限制下载 HTML 文档字符串的大小?
- python - 正确使用生成器类型
- nativescript - Nativescript 6 - 环境特定文件不起作用
- python - 查找具有名称模式的文件
- apache-kafka - KafkaConsumer 位置(TopicPartition)永无止境
- vba - Excel 中是否存在在应用程序打开时和计算单元格之前运行的事件?