0
点赞
收藏
分享

微信扫一扫

Vue3 使用pdf.js 预览pdf

Hyggelook 2022-03-12 阅读 72

Vue3 使用pdf.js 预览pdf

非专业 如有语术错误请谅解

写在前面:vue-pdf 好像并不支持Vue3 参考https://segmentfault.com/a/1190000039858927

本样例是基于后端返回的是文件流

直接上样例

首先下载pdf.js
注意:将解压后的文件放在static下
在这里插入图片描述

1.使用ifame嵌套

 <iframe
      id='pdf'
      ref='pdf'
      height='100%'
      :src='pdfUrl'
      width='100%' /> 


//可附带token请求,如果不需要则删掉
const Token = store.getters['user/token']
//fileUrl为返回的文件流
let url = fileUrl
//iframe中的src
this.pdfUrl = '/static/pdf/web/viewer.html?file=' + encodeURIComponent(url)
//如果不需要带token则到这一步就结束了


//下面是带token的处理
const res = await fetch(url, {
  method: 'GET',
  headers: {
  //如果不需要token则删掉
    'Authorization': Token,
  },
})
const blob = await res.blob()
let arr = []
arr.push(blob)
//转化为可预览的格式
let pdfUrl = URL.createObjectURL(new Blob(arr, { type: 'application/pdf' }))
//iframe中的src
this.pdfUrl = '/static/pdf/web/viewer.html?file=' + encodeURIComponent(pdfUrl)


//后续如果需要等待pdf加载后所触发的事件,  
//如本人遇到的则为加载完成后自动打印,
const iframe = document.querySelector('#pdf')
// 处理兼容行问题
if (iframe.attachEvent) {
  iframe.attachEvent('onload', function() {
    //dosomething
  })
} else {
  iframe.onload = function() {
    //dosomething
  }
}

最后:如果用上了记得点个??

举报

相关推荐

0 条评论