iframe处理pdf文件

最近有个项目有个需求,实现后台发送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文件太大,加载速度会特别慢

建议还是使用对象存储服务

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值