实现功能需要安装jspdf库
yarn add jspdf
或者
npm install jspdf
// 1. 安装并引入 jspdf
import JsPDF from 'jspdf'
// 2. 定义生成 PDF 文件的函数
function generatePDF(imgUrls) {
// 3. 利用 Canvas API 转换图片 URL 为图片数据
const promises = imgUrls.map(url => {
return new Promise(resolve => {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const img = new Image()
//浏览器的同源限制
//这句一定要有
img.setAttribute("crossOrigin", 'Anonymous')
img.onload = function() {
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img, 0, 0)
resolve(canvas.toDataURL('image/png'))
}
img.src = url
})
})
// 4. 生成 PDF 文件
Promise.all(promises).then(images => {
const pdf = new JsPDF()
images.forEach((image, i) => {
pdf.addImage(image, 'PNG', 0, 0)
if (i !== images.length - 1) {
pdf.addPage()
}
})
// 5. 下载 PDF 文件
pdf.save('images.pdf')
})
}
以上代码可以直接复制粘贴使用