pdf.js实现pdf的预览与下载(vue+springboot+pdf.js)

xx,我们的pdf文档需要做一个预览功能,你今天加班做一下吧。。。

环境:
文件服务器: fdfs
前端:vue
后段:springboot

单纯的使用pdf.js进行预览出现了跨域问题,所以需要后端把文件流传给前端,然后前端进行展示。

1.下载pdf.js,如果无法打开,下载我存放的已经修改过的pdf.js

2. 将下载好的文件中的build和web拷贝到vue项目的public文件夹下

在这里插入图片描述

3. 上代码

3.1 vue前端
 <template>
  <div>
    <el-button @click="pdf">预览pdf</el-button>
    <el-button @click="downloadPdf()">模板下载</el-button>

  </div>
</template>

<script>
export default {
    
    
  name: "pdf",
  data(){
    
    
    return {
    
    
      fileUrl: 'http://file.clzn.sunline.cn:8283/group1/M00/00/00/ChZVMmBZm8CANMbbAE4a0Em_r80670.pdf',
      newUserId: null
    }
  },
  mounted() {
    
    
  },
  methods: {
    
    
    downloadClick(){
    
    
      var link = document.createElement('a');
      link.setAttribute("download", "");
      link.href = "./batchCaseUpdate.xlsx";
      link.click();
    },


    pdf() {
    
    
      console.log('预览pdf')
      this.axios({
    
    
        methods: 'get',
        url: '/api/readPdfFile',
        params: {
    
    
          fileUrl: this.fileUrl
        },
        responseType: 'blob',
        headers:{
    
    
          'Content-Type': 'application/json'
        }
      }).then(res => {
    
    
        let blob = new Blob([res.data], {
    
    type: 'application/pdf'})
        let href = URL.createObjectURL(blob)
        console.warn(href)
        window.open(`./pdf/web/viewer.html?file=${
    
    encodeURIComponent(href)}`);
      })
    },
    downloadPdf() {
    
    
      console.log('下载pdf')
      this.axios({
    
    
        methods: 'get',
        url: '/api/readPdfFile',
        params: {
    
    
          fileUrl: this.fileUrl
        },
        responseType: 'blob',
        headers:{
    
    
          'Content-Type': 'application/json'
        }
      }).then(res => {
    
    
        const link = document.createElement('a')
        let blob = new Blob([res.data], {
    
    type: 'application/pdf'})
        link.href = URL.createObjectURL(blob)
        link.style.display = 'none'
        link.style.target = '_blank'
        link.href = URL.createObjectURL(blob)
        console.warn(link.href)
        link.download = new Date().getTime() //下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    }
  }
}
</script>

<style scoped>

</style>


3.2 java后端

3.2.1 controller层

    /**
     * pdf 预览功能
     *
     * @param response
     * @param fileUrl
     */
    @GetMapping("/readPdfFile")
    public void previewPdf(HttpServletResponse response , String fileUrl){
    
    
        ExportFileUtil.preview(response, fileUrl);
    }

3.2.2 service层

		/**
     * 文件预览
     * @param response
     * @param filePath
     */
    public static void preview(HttpServletResponse response, String filePath) {
    
    
        ServletOutputStream out;
        BufferedInputStream buf;
        try {
    
    
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "inline;fileName=" + filePath.substring(filePath.lastIndexOf("/") + 1));
            URL url = new URL(filePath);
            //使用输入读取缓冲流读取一个文件输入流
            buf = new BufferedInputStream(url.openStream());
            //利用response获取一个字节流输出对象
            out = response.getOutputStream();
            //定义个数组,由于读取缓冲流中的内容
            byte[] buffer = new byte[1024];
            int n;
            //while循环一直读取缓冲流中的内容到输出的对象中
            while ((n = buf.read(buffer)) != -1) {
    
    
                out.write(buffer, 0, n);
            }
            //写出到请求的地方
            out.flush();
            buf.close();
            out.close();
        } catch (IOException e) {
    
    
            StaticLog.error("ExportFileUtil.download() IOException", e);
        } catch (Exception e) {
    
    
            StaticLog.error("Exception", e);
        }
    }

4.看效果

在这里插入图片描述

5.成功~~~
demo地址-github
demo地址-gitee

猜你喜欢

转载自blog.csdn.net/weixin_42551369/article/details/118527891