怎么在vue中多个echarts图形使用jsPdf.js+html2Canvas.js被强行截断的问题,如何让每一页不够放下echarts图时自动放到下一页,给一个完整的.js
时间: 2024-03-20 22:43:19 浏览: 27
这个问题的解决方案比较复杂,需要结合html2canvas和jsPdf两个库进行处理。下面是一个完整的.js文件,供参考:
```javascript
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default {
methods: {
downloadPDF () {
let contentWidth = 0
let contentHeight = 0
const imgWidth = 210
const imgHeight = 297
const pageHeight = 295
let leftHeight = 0
let position = 0
const pdf = new jsPDF('p', 'mm', 'a4')
const domList = document.querySelectorAll('.pdf-export')
const domListArr = Array.from(domList)
domListArr.forEach((dom) => {
html2canvas(dom)
.then(canvas => {
const contentDataURL = canvas.toDataURL('image/png')
if (position === 0) {
contentWidth = canvas.width * 0.264583333
contentHeight = canvas.height * 0.264583333
leftHeight = contentHeight
} else {
leftHeight = contentHeight % pageHeight
}
if (leftHeight < pageHeight) {
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 295
if (leftHeight > 0) {
pdf.addPage()
}
}
}
position -= 295
if (position <= -contentHeight) {
pdf.save('download.pdf')
}
})
})
}
}
}
```
这个方法的主要思路是:先用html2canvas将需要导出的dom元素转换为canvas,然后将canvas转换为base64格式的图片,如果一页能放下这个图片就直接添加到pdf中;如果一页放不下,就分页添加图片,直到全部添加完成。最后调用pdf.save()方法将pdf文件保存到本地。
需要注意的是,这个方法只适用于导出多个echarts图形的情况,如果只需要导出一个echarts图形,可以直接使用echarts提供的toDataURL()方法将图形转换为base64格式的图片,然后添加到pdf中即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)