vue 批量导出pdf 压缩包 zip
使用插件
html2canvas
jspdf
jszip (百度ai搜出来的是zip-js 这个没法安装)
file-saver
思路:
1.使用 html2canvas+jspdf 将页面转图片转pdf(这个怎么转的可以网上搜下很多)
2.利用jszip+file-saver 结合promise.all 写入压缩包中
1.准备页面
<template><div><div :id="'id'+1">11111</div><div :id="'id'+2">2222</div><div :id="'id'+3">33333</div><div :id="'id'+4">44444</div></div>
</template>
<style lang="scss" scoped>
#id1{background: blue;color: #fff;line-height: 40px;font-size: 30px
}
#id3{background: rgb(0, 255, 128);color: #fff;line-height: 40px;font-size: 30px
}
#id2{background: rgb(255, 136, 0);color: #fff;line-height: 40px;font-size: 30px
}
#id4{background: rgb(255, 0, 106);color: #fff;line-height: 40px;font-size: 30px;
}
</style>
2.写js
<script>
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import { saveAs } from 'file-saver'
import Jszip from 'jszip'export default {// 提交handleSubmit() {// 创建一个zip实例const zip = new Jszip()//创建一个promises 容器const promises = []//生成pdf 得到一个含有pdf内容 跟 名称的promiselet p1 = this.generatePDF('id1', '填报记录1')let p2 = this.generatePDF('id2', '填报记录2')promises.push(p1)promises.push(p2)//批量执行promisePromise.all(promises).then(async(pdfs) => {for (let i = 0; i < pdfs.length; i++) {const { PDF, name } = pdfs[i]// 如果只是导出一个pdf,则导出pdf格式if (pdfs.length === 1) {//名称可以自己取PDF.save(`${name}-${new Date().getTime()}.pdf`)// this.allLoading = false// this.loadingText = '正在请求数据'} else {// 否则添加到压缩包里面await zip.file(`${name}-${new Date().getTime()}.pdf`, PDF.output('blob'))}}if (pdfs.length > 1) {zip.generateAsync({ type: 'blob' }).then(content => {//下载 zipsaveAs(content, 'xxxxxxx.zip')})}}).finally(() => {// this.allLoading = false// this.loadingText = '正在请求数据'})console.log(promises)},//将html转成 pdf 最后一步的时候别使用pdf.save。generatePDF(content, filename) {return new Promise((resolve, reject) => {const cloneDom = document.getElementById(content).cloneNode(true)document.getElementsByTagName('body')[0].appendChild(cloneDom)html2Canvas(cloneDom,{ allowTaint: false }).then((canvas) => {let contentWidth = canvas.widthlet contentHeight = canvas.height// a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高let 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()}}}// const blob = PDF.output('blob')// console.log(blob)//将pdf内容 跟名称 resolve出去resolve({ PDF, name: filename })// PDF.save(`关联OA申请单(${timeToTime(new Date(), false)}).pdf`)document.getElementsByTagName('body')[0].removeChild(cloneDom)})})}}
}
</script>
下载成功,代码可以直接用