vue文件流转换成pdf预览(pdf.js+iframe)

需求:后端返回文件流前端将文件流转为成blob地址预览pdf文件

两种方式:

1,PDFJS: https://mozilla.github.io/pdf.js/ 支持获取文件流到客户端,生成blob地址预览

2,Vue-pdf https://github.com/FranckFreiburger/vue-pdf 会出现空白页( 推荐使用iframe方法 )

一,官网(https://mozilla.github.io/pdf.js/getting_started/#download)下载PDFJS,注意放在static文件目录下,如果vue最新版本放在public文件中(本项目@vue/cli 4.4.6)

 在axios请求中设置响应类型,此方法是自己项目中封装的axios请求,可根据自己情况加这行代码

responseType: 'blob',

页面中

    <el-dialog title="PDF 预览" :visible.sync="viewVisible" width="70%" center>
      <template>
        <iframe class="prism-player" :src="pdfUrl" width="100%" height="800px"></iframe>
      </template>
    </el-dialog>
   data() {
      return {
        // pdfUrl:'http://image.cache.timepack.cn/nodejs.pdf',
        pdfUrl:'',
        viewVisible:false,
      }
  }

在返回的数据将文件流转为成blob地址预览pdf文件

            let urlPdf  = window.URL.createObjectURL(new Blob([res.data]))
            console.log('urlPdf',urlPdf) //blob:http://localhost:8080/e8451cb8-3238-4272-b490-0420df4a5b88
            this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(urlPdf)
            this.viewVisible = true

后台返回的文件流:

 pdf预览:

猜你喜欢

转载自www.cnblogs.com/duhui/p/13387077.html