问题描述:接口返回的数据是base64格式的图片,如果想通过js方法下载成pdf格式的文件
1.可以jsPDF,
npm install jspdf
2.引入工具jspdf
import jsPDF from 'jspdf';
3.将接口返回的base64数据解码成二进制,再将二进制数据添加到PDF中
downPDF(){
// 将接口返回的base64图片资源赋值base64Url
let base64Url = 'data:image/png;base64,iVBORw...'
// 创建一个新的jsPDF实例
const pdf = new jsPDF();
// 将图片转换为二进制数据并添加到PDF中
const blob = this.base64ToBlob(base64Url, 'image/png');
const img = new Image();
img.onload = function() {
// 在PDF中添加图片
// 参数分别是:x坐标, y坐标, 宽度, 高度
pdf.addImage(img, 'PNG', 0, 0, 210, 100);
// 保存生成的PDF
pdf.save('导出文件名称' +'.pdf');
}.bind(this);
img.src = URL.createObjectURL(blob);
},
base64ToBlob(base64, mime) {
const parts = base64.split(';base64,');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: mime });
},
1776

被折叠的 条评论
为什么被折叠?



