js 生成pdf 并上传文件
js 生成pdf 并上传文件
使用 JsPDF + html2Canvas 代码直接使用 注意注释
import JsPDF from 'jspdf'
import html2Canvas from 'html2canvas'
// 上传文件的方法
import { handleUploadImage } from '@/utils/uploadQuillEdit'downPDF() {// 要打印元素的idconst cloneDom = document.getElementById('rentArea').cloneNode(true)document.getElementsByTagName('body')[0].appendChild(cloneDom)html2Canvas(cloneDom,{ allowTaint: true }).then((canvas) => {let contentWidth = canvas.widthlet contentHeight = canvas.heightlet pageHeight = contentWidth / 592.28 * 841.89let leftHeight = contentHeightlet position = 0let imgWidth = 595.28let imgHeight = 592.28 / contentWidth * contentHeightlet 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 -= pageHeightposition -= 841.89if (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)})}