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 })
}
相关推荐
云水一下4 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing4 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
云水一下4 小时前
TypeScript 从零基础到精通(六):类型声明与模块化
javascript·typescript
copyer_xyf4 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香4 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角5 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf5 小时前
Python venv 虚拟环境
前端·后端·python
无聊的老谢5 小时前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript
xiaofeichaichai5 小时前
Map / Set / WeakMap / WeakSet
前端·javascript
李可以量化5 小时前
成交量的终极量化策略:价量共振指标完整实现(下篇)
前端·数据库·人工智能