先上代码
```
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
/**
* 导出PDF
* @param {导出后的文件名} title
* @param {要导出的dom,使用DOM的id} ele
*/
const exportPDF = async (title, ele, setLoading = () => {}) => {
setLoading(true)
// 根据dpi放大,防止图片模糊
const scale = window.devicePixelRatio > 1 ? window.devicePixelRatio : 2
// 下载尺寸 a4 纸 比例
const element = document.getElementById(ele)
const pdf = new jsPDF('p', 'pt', 'a4')
let width
let height
//判断是否有滚动,有滚动的情况下,先显示,等创建完元素后取消显示
if (hasScrolled(element, '')) {
element.style.overflowX = 'visible'
width = element.scrollWidth
} else {
width = element.offsetWidth
}
if (hasScrolled(element)) {
element.style.overflowY = 'visible'
height = element.scrollHeight
} else {
height = element.scrollHeight
}
const canvas = document.createElement('canvas')
canvas.width = width * scale
canvas.height = height * scale
const contentWidth = canvas.width
const contentHeight = canvas.height
//一页pdf显示html页面生成的canvas高度;
const pageHeight = (contentWidth / 592.28) * 841.89
//未生成pdf的html页面高度
let leftHeight = contentHeight
//页面偏移
let position = 0
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
const imgWidth = 595.28
const imgHeight = (592.28 / contentWidth) * contentHeight
const pdfCanvas = await html2canvas(element, {
useCORS: true,
canvas,
scale,
width,
height,
x: 0,
y: 0,
})
const imgDataUrl = pdfCanvas.toDataURL()
if (height > 14400) {
// 超出jspdf高度限制时
const ratio = 14400 / height
// height = 14400;
width = width * ratio
}
// 缩放为 a4 大小 pdfpdf.internal.pageSize 获取当前pdf设定的宽高
height = (height * pdf.internal.pageSize.getWidth()) / width
width = pdf.internal.pageSize.getWidth()
if (leftHeight < pageHeight) {
pdf.addImage(imgDataUrl, 'png', 0, 0, imgWidth, imgHeight)
} else {
// 分页
while (leftHeight > 0) {
pdf.addImage(imgDataUrl, 'png', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage()
}
}
}
//将滚动复原
element.style.overflowY = ''
element.style.overflowX = ''
// 导出下载
await pdf.save(`${title}.pdf`)
setLoading(false)
}
export default exportPDF
// 判断元素是否滚动,默认判断y轴方向
function hasScrolled(ele, dir = 'vertical') {
let eleScroll = dir === 'vertical' ? 'scrollTop' : 'scrollLeft'
let result = !!ele[eleScroll] // 判断scroll数值是否为0,还是其他值
// 如果是其他数值(非0)这表示有滚动条
// 如果是0,则尝试移动一下滚动条,判断是否能够移动
if (!result) {
ele[eleScroll] = 1 // 尝试移动滚动条
result = !!ele[eleScroll] // 再次确认数值
ele[eleScroll] = 0 // 恢复原位
}
return result // 得出结果
}
```
pdf导出原理 html2canvas2pdf
内容在盒子内滚动通过hasScrolled判断 。存在滚动时修改对应的overflow为visible,在数据导出完成后改为''