js 生成pdf 并上传文件

发布于:2025-05-01 ⋅ 阅读:(18) ⋅ 点赞:(0)

js 生成pdf 并上传文件

使用 JsPDF + html2Canvas 代码直接使用 注意注释

import JsPDF from 'jspdf'
import html2Canvas from 'html2canvas'
// 上传文件的方法
import { handleUploadImage } from '@/utils/uploadQuillEdit'

downPDF() {
	//	 要打印元素的id
      const cloneDom = document.getElementById('rentArea').cloneNode(true)
      document.getElementsByTagName('body')[0].appendChild(cloneDom)
      html2Canvas(
        cloneDom,
        { allowTaint: true }
      ).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 转换为 Blob 对象
        const pdfBlob = PDF.output('blob')
        // file对象
        const pdfFile = new File([pdfBlob], `面积、期限及租金${new Date().getTime()}.pdf`, {
          type: 'application/pdf',
          lastModified: new Date().getTime()
        })
		
		//上传文件
        handleUploadImage(pdfFile).then(data => {
          console.log(data)
        })
		
		//这里是直接保存pdf
        // PDF.save(`${this.dataForm.customerNameShow}项目智能分仓方案书(${timeToTime(new Date(), false)}).pdf`)
        document.getElementsByTagName('body')[0].removeChild(cloneDom)
      })
    }

网站公告

今日签到

点亮在社区的每一天
去签到