dom 转pdf 导出 加分页

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')
          }
        )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值