我现在有一段vue打印页面的代码,代码如下printDomVal(record){ //获取要打印的Dom内容 // let newDomHtml = this.$refs.pdfDom.innerHTML; //获取页面中的数据 let newDomHtml = { detailList: record }; Vue.ls.set(PRINT_DOM, newDomHtml) let newPage = this.$router.resolve({ name: 'printDetail' }) window.open(newPage.href,'_blank') },请问如何把这段打印的页面转成pdf导出
时间: 2024-02-14 10:18:24 浏览: 419
要将Vue组件转换为PDF并导出到本地,可以使用jsPDF和html2canvas库。首先需要安装这两个库:
npm install jspdf html2canvas --save
然后在Vue组件中引入这两个库:
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
接下来,在printDomVal
方法中,使用html2canvas将要打印的DOM元素转换为canvas,然后将canvas转换为PDF并导出到本地:
printDomVal(record) {
// 获取要打印的 DOM 内容
let printDom = document.getElementById('printDom')
// 获取页面中的数据
let newDomHtml = {
detailList: record
}
Vue.ls.set(PRINT_DOM, newDomHtml)
// 转换为 canvas
html2canvas(printDom, {
allowTaint: true,
useCORS: true
}).then((canvas) => {
// 转换为 PDF
let pdf = new jsPDF('p', 'mm', 'a4')
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298)
// 导出到本地
pdf.save('print.pdf')
})
}
其中,printDom
需要根据实际情况替换为要打印的DOM元素的ID。allowTaint
和useCORS
参数用于解决html2canvas跨域问题。pdf.save('print.pdf')
用于将PDF保存到本地。
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)