dom 转pdf 导出 加分页
转载自 ------------------此文章---------------- 作为备忘
import html2PDF from 'jspdf-html2canvas';
// 存储变化前的dom的边距
const originMarginTop = []
const pageHeight = 1810.286
let top = 0
// 为了自动分页,改变部分dom界面的上边距
// eslint-disable-next-line no-unused-vars
export function exportPdf(dom, fileName, success) {
top = dom.offsetTop
countPosition(dom)
setTimeout(() => {
html2PDF(dom, {
jsPDF: {
format: 'a4',
},
html2canvas: {
logging: true,
useCORS: true,
},
margin: {
top: 29.7,
right: 21,
bottom: 29.7,
left: 21,
},
imageType: 'image/jpeg',
output: fileName,
success: function (pdf) {
pdf.save(this.output);
// 恢复原来的边距
originMarginTop.forEach(item => {
item.dom.style.marginTop = item.marginTop
})
success && success()
}
});
},100)
}
function countPosition(dom ){
for (let i = 0; i < dom.childElementCount; i++){
const childItem = dom.children[i]
if(childItem.className.includes('pdf')){
countPosition(childItem)
}else{
const offsetTop = childItem.offsetTop - top
const offsetBottom = offsetTop + childItem.clientHeight
const splitPage = Math.floor(offsetTop / pageHeight) !== Math.floor(offsetBottom / pageHeight)
if (splitPage) {
const marginTop = Math.ceil(offsetTop / pageHeight) * pageHeight - offsetTop
top += marginTop
originMarginTop.push({
dom: childItem,
marginTop: childItem.style.marginTop
})
const newMarginTop = parseFloat(childItem.style.marginTop ||0) + marginTop + 'px'
childItem.style.marginTop = newMarginTop
}
}
}
}
<div class="pdf" :class="{exportIng}" ref="pdf">
...
</div>
exportPdf(
this.$refs.pdf,
`这里是文件名.pdf`,
() => {
this.exportIng = false
this.$toast('export success')
}
)
转载自https://blog.csdn.net/xiaozhi122/article/details/124940094