最近有个项目有个需求,实现后台发送pdf的base64格式,前端处理数据并进行pdf的预览
看了很多解决方法 有pdfjs ,vue-pdf,iframe内嵌的方法,因为不需要太多功能所以选择了用iframe处理
先来看看MDN上对iframe的介绍
iframe常用属性:
1.frameborder:是否显示边框,1(yes),0(no)
2.height:框架作为一个普通元素的高度,建议在使用css设置。
3.width:框架作为一个普通元素的宽度,建议使用css设置。
4.name:框架的名称,window.frames[name]时专用的属性。
5.scrolling:框架的是否滚动。yes,no,auto。
6.src:内框架的地址,可以使页面地址,也可以是图片的地址。
7.srcdoc , 用来替代原来HTML body里面的内容。但是IE不支持, 不过也没什么卵用
8.sandbox: 对iframe进行一些列限制,IE10+支持
处理base64数据转换为blob
了解了iframe的一些知识现在就开始对后端返回数据进行处理
解码base64并返回blob对象
const base64ToBlob = (code) => {
code = code.replace(/[\n\r]/g, '')
// console.log(code);
// atob() 方法用于解码使用 base-64 编码的字符串。
const raw = 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' })
}
踩坑
Base64一行不能超过76字符,超过则添加回车换行符。因此需要把base64字段中的换行符,回车符给去掉。
code = code.replace(/[\n\r]/g, '')
如果返回的base64数据自带了前缀data:application/pdf;base64,
不去掉这个前缀 直接解码会报 failed to execute 'atob' on 'window': the string to be decoded is not correctly encoded. 这个错误。处理方式用字符串切割出我们想要的部分
let myBlob = base64ToBlob(code.substring(code.indexOf(',') + 1))
export const getblobUrl = (code) => {
let myBlob = base64ToBlob(code.substring(code.indexOf(',') + 1))
// let myUrl = URL.createObjectURL(myBlob)
let myUrl = URL.createObjectURL(myBlob)
return myUrl
}
const base64ToBlob = (code) => {
code = code.replace(/[\n\r]/g, '')
const raw = 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' })
}
export const getblobUrl = (code) => {
let myBlob = base64ToBlob(code.substring(code.indexOf(',') + 1))
// let myUrl = URL.createObjectURL(myBlob)
let myUrl = URL.createObjectURL(myBlob)
return myUrl
}
最后
使用base64传输pdf文件在pdf文件比较小的时候加载速度能够接收
如果pdf文件太大,加载速度会特别慢
建议还是使用对象存储服务