js生成pdf并自动上传

1.生成pdf前要让js选中生成pdf部分的dom

pdf内容区

2.使用两个插件,import到项目里,然后是获取dom进行生成pdf操作

import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
function createPdf() {
  html2canvas(document.getElementById('printPageFirst'), {
    allowTaint: true,
    taintTest: false,
    useCORS: true,
    dpi: window.devicePixelRatio * 4,
    scale: 4
  }).then(canvas => {
    let contentWidth = canvas.width
    let contentHeight = canvas.height
    let pageHeight = (contentWidth / 592.28) * 841.89
    let leftHeight = contentHeight
    let position = 0
    let imgWidth = 595.28
    let imgHeight = (592.28 / contentWidth) * contentHeight
    let pageData = canvas.toDataURL('image/jpeg', 1.0)
    let 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() 此方法可以将pdf直接保存本地
    let pdfData = PDF.output('datauristring') // 获取base64Pdf
    let files = dataURLtoFile(pdfData, props.title + '封面.pdf') // 将base64文件转化为流,上传oss
    uploadFiles(files)
  })
}
function uploadFiles(files) {
  let formData = new FormData()
  formData.append('file', files)
  request
    .post('/api/oss/img', formData, { timeout: 20000 })
    .then(res => {
      let fileUrl = res.fileUrl
      // 拿到pdf在服务器的地址后,再自己做后续操作
    })
    .catch(() => {
    })
}
function dataURLtoFile(dataurl, filename) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

你可能感兴趣的:(javascript,pdf,前端)