使用html2canvas将网页内容转换成canvas,canvas内容写入到pdf,并实现pdf分页

var imageToFile = this.$refs.imageTofile
html2canvas(imageToFile, { x: window.scrollX })
.then(canvas => {
  // 未生成pdf的html页面高度
  var leftHeight = canvas.height

  var a4Width = 595.28
  var a4Height = 841.89
  // 一页pdf显示html页面生成的canvas高度;
  var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height)
  // pdf页面偏移
  var position = 0
  var pdf = new JsPDF('x', 'pt', 'a4')
  var canvas1 = document.createElement('canvas')
  var height
  pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen')

  var pdfName = '图表数据'
  function createImpl(canvas) {
    if (leftHeight > 0) {
      var checkCount = 0
      if (leftHeight > a4HeightRef) {
        var i = position + a4HeightRef
        // 默认取pdf标准所在canvas网页高度,倒着循环,推断分页位置
        // 推断canvas.width 整行是否有内容如果有内容直接退出,checkCount为0,如果整行没有内容则累加checkCount值,直到checkCount值大于等于约定分页的留白缝隙,则认为这里是分页的地方,并作出位置纪录
        for (i = position + a4HeightRef; i >= position; i--) {
          var isWrite = true
          for (var j = 0; j < canvas.width; j++) {
            var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

            if (c[0] !== 0xff || c[1] !== 0xff || c[2] !== 0xff) {
              isWrite = false
              break
            }
          }
          if (isWrite) {
            checkCount++
            if (checkCount >= 25) {
              break
            }
          } else {
            checkCount = 0
          }
        }
        height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef)

        if (height <= 0) {
          height = a4HeightRef
        }
      } else {
        height = leftHeight
      }

      canvas1.width = canvas.width
      canvas1.height = height
      var ctx = canvas1.getContext('2d')
      ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height)

      if (position !== 0) {
        pdf.addPage()
      }
      pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, a4Width, a4Width / canvas1.width * height)
      leftHeight -= height
      position += height
      if (leftHeight > 0) {
        createImpl(canvas)
      } else {
        pdf.save(pdfName + '.pdf')
        that.loadingBtnStatus = false
      }
    }
  }

  // 当内容未超过pdf一页显示的范围,无需分页
  if (leftHeight < a4HeightRef) {
    var pageData = canvas.toDataURL('image/jpeg', 1.0)
    pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight)
    pdf.save(pdfName + '.pdf')

    that.loadingBtnStatus = false
  } else {
    createImpl(canvas)
  }
})

html2canvas 在某些情况下导出图表不全,错位,建议将需要导出的元素直接至于body层

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值