2024.03.17 10:46
最近做数据导出的时候,需要将 Base64 文件转换成 PDF 并下载保存到本地,做个记录😆,方便以后直接拿来用。
直接上代码:
//content是base64格式
exportPdf(content) {
const blob = this.base64ToBlob(content)
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob)
} else {
const fileURL = URL.createObjectURL(blob)
// window.open(fileURL);//(1)弹出ppf文件(预览)
// (2)直接下载pdf (创建个a标签,添加链接地址,及名称,再模拟点击下载)
let downloadLink = document.createElement('a')
downloadLink.href = fileURL
downloadLink.download = '托运单.pdf';
downloadLink.click();
}
}
// base64文件转 blob
base64ToBlob(code) {
code = code.replace(/[\n\r]/g, '')
// atob() 方法用于解码使用 base-64 编码的字符串。
const raw = window.atob(code)
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: 'application/pdf' })
}
Tips:图片转换保存方法类似。
获取 Base64 文件类型:
// base 是base64格式,如'data:image/webp;base64,UklGRuTFAQBXRUJQVlA4IN....'
getFileType(base) {
const arr = base.split(','), mime = arr[0].match(/:(.*?);/)[1]
return mime
}