后端返回文件流,前端vue渲染pdf文件

1.安装

npm install vue-pdf-signature

2.引入

// 引入pdf
import pdf from 'vue-pdf-signature';
import CMapReaderFactory from 'vue-pdf-signature/src/CMapReaderFactory';
 
 
components: {
    
     pdf,CMapReaderFactory }

3.tmplate

<template>
  <div>
        <iframe  ref="pdfRef"
              :src="wordDialog.pdfSrc"
              style="height: 740px;width: calc(100% - 38px);
              margin-left: 15px;" 
        frameborder="0"></iframe>
 
...
  </div>
</template>

3.method显示 ,res.data是接口返回值的BLOB

      openDetail(row) {
    
    
        this.resultDialogVisible = true;
        const params = {
    
    
          filePath: row.outputPath,
          contentType: ".pdf"
        };
        this.$axios({
    
    
          url: 'http://localhost:40822/api/xjtu/regClu/preview',
          method: 'get',
          params: params,
          responseType: 'blob'
        }).then(res => {
    
    
          console.log(res);
          const blob = new Blob([res.data], {
    
    type: 'application/pdf'});
          if (window.createObjectURL != undefined) {
    
     // basic
            this.pdfUrl = window.createObjectURL(blob);
          } else if (window.webkitURL != undefined) {
    
     // webkit or chrome
            try {
    
    
              this.pdfUrl = window.webkitURL.createObjectURL(blob);
            } catch (error) {
    
    
              console.log(error)
            }
          } else if (window.URL != undefined) {
    
     // mozilla(firefox)
            try {
    
    
              this.pdfUrl = window.URL.createObjectURL(blob);
            } catch (error) {
    
    
              console.log(error)
            }
          }
          console.log(this.pdfUrl)
        })
      },

后端方法

    public void preview(String filePath, String contentType, HttpServletResponse response) throws IOException {
    
    
        System.out.println("filePath" + filePath);
        //        读取的文件路径 filePath
        FileInputStream in = null;
        ServletOutputStream out = null;
        in = new FileInputStream(filePath);
        byte[] bytes = IOUtils.toByteArray(in);
        response.setContentType(contentType);
        response.setContentLength(bytes.length);
        response.setHeader("Content-Disposition", "attachment;filename=result");
        out = response.getOutputStream();
        out.write(bytes);
        out.close();
        in.close();
    }

猜你喜欢

转载自blog.csdn.net/weixin_42382758/article/details/126667471
今日推荐