vue前端导出pdf

发布时间 2023-09-22 15:28:35作者: 凹润之之之
function exportDataPdf(el, fileName, splitClassName) {
  // 防止页面数据被切割
  const A4_WIDTH = 595
  const A4_HEIGHT = 842
  el.style.height = 'initial'
  const pageHeight = el.scrollWidth / A4_WIDTH * A4_HEIGHT
  // 获取分割dom,此处为class类名为item的dom
  const domList = document.getElementsByClassName(splitClassName)
  // 进行分割操作,当dom内容已超出a4的高度,则将该dom前插入一个空dom,把他挤下去,分割
  let pageNum = 1 // pdf页数
  const eleBounding = el.getBoundingClientRect()
  for (let i = 0; i < domList.length; i++) {
    const node = domList[i]
    const bound = node.getBoundingClientRect()
    const offset2Ele = bound.top - eleBounding.top
    const currentPage = Math.ceil((bound.bottom - eleBounding.top) / pageHeight) // 当前元素应该在哪一页
    if (pageNum < currentPage) {
      pageNum++
      const divParent = domList[i].parentNode // 获取该div的父节点
      const newNode = document.createElement('div')
      newNode.className = 'emptyDiv'
      newNode.style.background = 'white'
      newNode.style.height = (pageHeight * (pageNum - 1) - offset2Ele + 10) + 'px' // +30为了在换下一页时有顶部的边距
      newNode.style.width = '100%'
      divParent.insertBefore(newNode, node) //在每一个节点前面插入一个空的新节点,防止内容被分割截断
    }
  }

  html2canvas(el, {
    allowTaint: true,
  }).then((canvas) => {
    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;
    // 一页pdf显示html页面生成的canvas高度;a4纸的尺寸[595.28,841.89],pageHeight是应有高度吗,leftHeight是实际高度吗
    const pageHeight = (canvasWidth / 592.28) * 841.89;
    // 未生成pdf的html页面高度
    let leftHeight = canvasHeight;
    // 页面偏移
    let position = 0;
    // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
    const imgWidth = 595.28;
    const imgHeight = (595.28 / canvasWidth) * canvasHeight;


    //toDataURL()方法是返回一个包含图片展示的数据URL。
    const pageData = canvas.toDataURL('image/jpeg', 1.0);
    const pdf = new jsPDF("", "pt", "a4");
    if (leftHeight < pageHeight) {
      // 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
      pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
    } else {
      // 分页
      while (leftHeight > 0) {
        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        // 避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    // 可动态生成
    pdf.save(`${fileName}.pdf`);
  })
}
 
const ele = document.getElementById('content_page');
 exportDataPdf(ele, "名称", 'el-table__row')