vue项目实现将前端页面生成pdf文档,解决分页截断问题

1. 安装html2canvas, jspdf插件

npm install html2canvas jspdf --save

2. 使用新建一个js文件htmlToPdf.js

import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
class PdfLoader {
  //  ele:dom节点
  //  pdfFileName: 文件名
  //  splitClassName: 避免分段截断的类名,例如table中的tr的类名<tr class="itemClass"></tr>
  constructor(ele, pdfFileName, splitClassName) {
    this.ele = ele
    this.pdfFileName = pdfFileName
    this.splitClassName = splitClassName
    this.A4_WIDTH = 595
    this.A4_HEIGHT = 842
  }

  async getPDF(resolve) {
    const ele = this.ele
    const pdfFileName = this.pdfFileName
    const eleW = ele.offsetWidth// 获得该容器的宽
    const eleH = ele.scrollHeight// 获得该容器的高
    const eleOffsetTop = ele.offsetTop// 获得该容器到文档顶部的距离
    const eleOffsetLeft = ele.offsetLeft// 获得该容器到文档最左的距离
    const canvas = document.createElement('canvas')
    let abs = 0
    const win_in = document.documentElement.clientWidth || document.body.clientWidth// 获得当前可视窗口的宽度(不包含滚动条)
    const win_out = window.innerWidth// 获得当前窗口的宽度(包含滚动条)
    if (win_out > win_in) {
      abs = (win_out - win_in) / 2// 获得滚动条宽度的一半
    }
    canvas.width = eleW * 2// 将画布宽&&高放大两倍
    canvas.height = eleH * 2
    const context = canvas.getContext('2d')
    context.scale(2, 2) // 增强图片清晰度
    context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
    html2Canvas(ele, {
      useCORS: true// 允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
    }).then(async canvas => {
      const contentWidth = canvas.width
      const contentHeight = canvas.height
      // 一页pdf显示html页面生成的canvas高度;
      const pageHeight = (contentWidth / this.A4_WIDTH) * this.A4_HEIGHT // 这样写的目的在于保持宽高比例一致 pageHeight/canvas.width = a4纸高度/a4纸宽度// 宽度和canvas.width保持一致
      // 未生成pdf的html页面高度
      let leftHeight = contentHeight
      // 页面偏移
      let position = 0
      // a4纸的尺寸[595,842],单位像素,html页面生成的canvas在pdf中图片的宽高
      const imgWidth = this.A4_WIDTH - 10 // -10为了页面有右边距
      const imgHeight = (this.A4_WIDTH / contentWidth) * contentHeight
      const pageData = canvas.toDataURL('image/jpeg', 1.0)
      const pdf = JsPDF('', 'pt', 'a4')
      // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
      // 当内容未超过pdf一页显示的范围,无需分页
      if (leftHeight < pageHeight) {
        // 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
        pdf.addImage(pageData, 'JPEG', 5, 0, imgWidth, imgHeight)
        // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
      } else {
        // 分页
        while (leftHeight > 0) {
          pdf.addImage(pageData, 'JPEG', 5, position, imgWidth, imgHeight)
          leftHeight -= pageHeight
          position -= this.A4_HEIGHT
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage()
          }
        }
      }
      pdf.save(pdfFileName + '.pdf', { returnPromise: true }).then(() => {
        // 去除添加的空div 防止页面混乱
        const doms = document.querySelectorAll('.emptyDiv')
        for (let i = 0; i < doms.length; i++) {
          doms[i].remove()
        }
      })
      this.ele.style.height = ''
      resolve()
    })
  }
  //此方法是防止(图表之类)内容因为A4纸张问题被截断
  async outPutPdfFn(pdfFileName) {
    return new Promise((resolve, reject) => {
      this.ele.style.height = 'initial'
      pdfFileName ? this.pdfFileName = pdfFileName : null
      const target = this.ele
      const pageHeight = target.scrollWidth / this.A4_WIDTH * this.A4_HEIGHT
      // 获取分割dom,此处为class类名为item的dom
      const domList = document.getElementsByClassName(this.splitClassName)
      // 进行分割操作,当dom内容已超出a4的高度,则将该dom前插入一个空dom,把他挤下去,分割
      let pageNum = 1 // pdf页数
      const eleBounding = this.ele.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 + 30) + 'px' // +30为了在换下一页时有顶部的边距
          newNode.style.width = '100%'
          divParent.insertBefore(newNode, node) //在每一个节点前面插入一个空的新节点,防止内容被分割截断
        }
      }
      // 异步函数,导出成功后处理交互
      this.getPDF(resolve, reject)
    })
  }
}

3. 页面上使用,

let pdf = new PdfLoader(ele, 'pdf' ,'itemClass');

pdf.outPutPdfFn(fileName);// outPutPdfFn方法返回一个promise 可以使用then方法处理pdf生成后的逻辑

<template>
  <div id="reviewForm" ref="contenxtPage" class="formWrapper" v-loading="loading">
    <div class="btnBox">
      <el-button type="primary" plain size="small" @click="download_pdf" v-loading="btnLoading">下载</el-button>
    </div>
    <div class="form">
      <div class="title">申请审核单</div>

      <el-table class="myTable" :data="field_info" stripe border style="width: 100%">
        <el-table-column prop="listing_name" label="清单名称"></el-table-column>
        <el-table-column prop="field_name" label="字段名"></el-table-column>
        <el-table-column prop="field_alias" label="字段注释"></el-table-column>
        <el-table-column prop="security_name" label="共享属性"></el-table-column>
        <el-table-column prop="dept_name" label="字段所属部门名称" width="160"></el-table-column>
        <el-table-column label="勾选栏" width="90">
          <template>
            <div class="right"></div>
          </template>
        </el-table-column>
      </el-table>

    </div>
  </div>
</template>
<script>
import PdfLoader from '@/utils/htmlToPdf.js
export default {
  data() {
    return {
      field_info: []
    }
  },
  methods: {
    download_pdf() {
      $('.btnBox').addClass('none') // 隐藏不需要的操作按钮
      this.btnLoading = true
      let container = document.getElementById('reviewForm')
      let pdf = new PdfLoader(container, '数据申请审核单' ,'el-table__row')
      pdf.outPutPdfFn('数据申请审核单').then(() => {
        $('.btnBox').removeClass('none') // 恢复操作按钮
        this.btnLoading = false
      })
    },
  }
}

</script>

  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值