前端vue导出pdf

一、分页

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export function getPdf(title, id) {
  html2Canvas(document.querySelector(`#${id}`), {
    allowTaint: true
  }).then(function(canvas) {
    const contentWidth = canvas.width
    const contentHeight = canvas.height
    const pageHeight = contentWidth / 592.28 * 841.89
    let leftHeight = contentHeight
    let position = 0
    const imgWidth = 595.28
    const imgHeight = 592.28 / contentWidth * contentHeight
    const pageData = canvas.toDataURL('image/jpeg', 1.0)
    const PDF = new JsPDF('', 'pt', 'a4')
    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, 'JPEG', 0, 0, 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(title + '.pdf')
  }
  )
}

二、不分页,整个页面导出一页pdf

js文件:

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export function getPdf(pdfName, ele) {
  const el = document.getElementById(ele)
  const eleW = el.offsetWidth // 获得该容器的宽
  const eleH = el.offsetHeight // 获得该容器的高
  const eleOffsetTop = el.offsetTop // 获得该容器到文档顶部的距离
  const eleOffsetLeft = el.offsetLeft // 获得该容器到文档最左的距离
  var canvas = document.createElement('canvas')
  var 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(el, {
    dpi: 96, // 分辨率
    scale: 2, // 设置缩放
    useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,
    bgcolor: '#ffffff', //  应该这样写
    logging: false // 打印日志用的 可以不加默认为false
  }).then((canvas) => {
    const contentWidth = canvas.width
    const contentHeight = canvas.height
    const pageData = canvas.toDataURL('image/jpeg', 1.0)
    const pdfX = ((contentWidth + 10) / 2) * 0.75
    const pdfY = ((contentHeight + 20) / 2) * 0.75
    const imgX = pdfX
    const imgY = (contentHeight / 2) * 0.75
    const pdf = new JsPDF('', 'pt', [pdfX, pdfY])
    pdf.addImage(pageData, 'JPEG', 0, 0, imgX, imgY)
    // 可动态生成
    pdf.save(pdfName)
  })
}

你可能感兴趣的:(前端,vue.js,pdf)