js生成pdf并自动上传

1.生成pdf前要让js选中生成pdf部分的dom
<div id="printPageFirst"> pdf内容区 </div>

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

javascript 复制代码
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 })
}
相关推荐
倔强的石头10613 分钟前
【C++指南】inline内联函数详解
java·前端·c++
小鹿( ﹡ˆoˆ﹡ )15 分钟前
Python中的“打开与关闭文件”:从入门到精通
linux·前端·python
gopher951115 分钟前
qml ComboBox 组合框
开发语言·前端
敲代码的小菜鸡18 分钟前
java根据html生成pdf
前端·后端
小白求学120 分钟前
HTML引用CSS
前端·css·html
ikunlxx21 分钟前
网页设计html心得
前端·html
scimence21 分钟前
html中为div添加展开与收起功能2(div隐藏与显示)
前端·javascript·html·隐藏div·div显示与隐藏
格瑞@_@25 分钟前
分享开源且强大的HTML5网页视频播放器
前端·音视频·html5
sailiss26 分钟前
html实现黑白棋
前端·javascript·html
傻啦嘿哟26 分钟前
邮件发送高级功能详解:HTML格式、附件添加与SSL/TLS加密连接
开发语言·前端·javascript