-
安装:npm install jspdf
-
引入:import jsPDF from "jspdf"
-
jspdf,将一个图片列表导出为pdf文件,根据图片宽高计算在pdf中的位置
-
官网 地址:rawgit.com/MrRio/jsPDF…
// 接口获取需要导出的图片 downloadImg() { const params = { evtsn: this.formData.evtsn } api.queryImg(params).then(res => { this.handleDownload(res.data) }) }, handleDownload(data) { // 下载的pdf文件名 let title = '图片材料' // 实例 JsPDF let PDF = new JsPDF() // 获取没张图片 const imgUrlList = data.map(i => this.getImgInfo(i.url)) Promise.all(imgUrlList).then(res => { console.log(res) // 循环设置没张图片的宽高 res.forEach((item, index) => { const { img, ext, imgWidth, imgHeight } = item 调用JsPDF插件方法设置宽高(入参可查看JsPDF文档) PDF.addImage(img, ext, 0, 0, imgWidth, imgHeight, String(Date.now())) if (index < res.length - 1) { PDF.addPage() } }) // 下载pdf文件方法 PDF.save(title + '.pdf') }) } // pdf 图片尺寸计算(按照打印A4纸设定宽高) getImgInfo(src) { return new Promise(resolve => { // a4尺寸 210, 297 const pageGkb = 297 / 210 let imgWidth, imgHeight const img = new Image() img.src = src img.onload = () => { const imgGkb = img.height / img.width // 高 > 宽 if (imgGkb > pageGkb) { // 图片太高了 imgHeight = 297 imgWidth = 297 / imgGkb } else { imgWidth = 210 imgHeight = 210 * imgGkb } resolve({ img, ext: 'png', imgWidth, imgHeight }) } }) },