前言:

vue-pdf也可以预览pdf,但是有些情况下会预览不出来。。

本文主要介绍使用iframe预览pdf的功能,以及iframe预览报错问题和iframe未能加载PDF文档。
.
.
预览自带分页、下载、旋转、比例等功能。
.这里是引用


一、iframe是什么?

iframe的介绍:将src的内容规定在 中显示出。

iframe既可以用来预览本地static下的文档,也可以预览后端返回的文件流文档

二、使用步骤

1.使用与逻辑:

逻辑:就是将后端返回的看不懂的文件流,设置成responseType = 'blob'然后读取到返回的Blob,再使用createObjectURL读取出url即可
对于后缀名是大写的.PDF 没法直接预览,建议直接下载下来看

 <iframe  :src="url" style="border: none;width: 100%;height: 100%;">
     <p>您的浏览器不支持 iframe 标签,请从列表中下载预览</p>
 </iframe>



  data () {
    return {
      url: '',
      }
  },
  methods: {
   downLoadFileImg (fileUrl, fileName) {// 后端文件地址和名称
      

      // 可下载,名称也有效 -- 推荐
      const x = new window.XMLHttpRequest()
      x.open('GET', fileUrl, true)
      x.responseType = 'blob' // 选择返回格式为blob --- 一般后端返回的是看不懂的文件流 故需要转成blob
      x.onload = () => {
        this.url = window.URL.createObjectURL(x.response) //将后端返回的blob文件读取出url
		
		console.log('blob====',x.response)   //Blob {size: 38617, type: 'application/pdf'}
		console.log('url====',this.url)   //blob:http://localhost:7197/cb047277-e5e6-4905-bf8c-dbecd86a0105

		// url可以预览和下载------如果想要下载就把下方注释打开即可
        // const a = document.createElement('a')
        // a.href = this.url
        // a.download = fileName
        // a.click()
      }
      x.send()



      // // 或者下方的方式
      // axios({
      //   url: G_CGI_PHP.superOrder.upfile + "?id=" + this.rowData.id,
      //   method: 'get',
      //   timeout: 100000,
      //   responseType: 'blob',
      //   headers: {
      //     // "type": 'application/pdf'
      //   },
      // }).then(res => {
      //   console.log('res.data', res.data)
      //   this.url = window.URL.createObjectURL(res.data) //将后端返回的blob文件读取出url
      //   console.log('通过读取blob文件得到url地址===', this.url)
      // }).catch(error => {
      //   console.log(error)
      // })


    },

  }

2.图文详解:

1.后端返回的是文件流,如下:
在这里插入图片描述

2.调用后端接口,通过设置responseType: 'blob',得到的Blob和读取的url如下:
在这里插入图片描述

3.错误情况:

3.1 iframe报未能加载PDF文档。:
在这里插入图片描述

3.2 如果报错:Uncaught (in promise) TypeError: Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed.
at eval
在这里插入图片描述

原因:说明你createObjectURL读的不是设置responseType: 'blob'后获取的Blob,可能是直接读的后端返回的那个看不懂的文件流res

三、参考链接

vue中 预览pdf


总结

iframe的预览效果更好,使用也很简单!推荐!!!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐