如何利用vue-pdf预览文件

现在我要对后台传过来的pdf文件流进行下载和预览,这里我用的是vue-pdf插件,我封装了一个PDF组件,这里直接引入了,下载功能已经完成,就是预览功能一直实现不了

下面是我封装的PDF组件

<template>
    <div style="height:0;overflow-y: auto;overflow-x: hidden;">
        <pdf :src="src"></pdf>
    </div>
</template>

<script>
import pdf from 'vue-pdf'
export default {
  components: {pdf},
  data() {
    return {
      src: ""
    };
  },
  methods: {
    //预览pdf
    previewPDF(url,fileData) {
      this.src = pdf.createLoadingTask(url);
    },
     //下载PDF
    downloadPDF(url,fileData, fileName) {
      this.$axios({
        method: "post",
        responseType: "arraybuffer",
        url: url,
        data:fileData
      })
        .then(
          function(res) {
            //调用下载方法,把后端传过来的流传给fileDownload方法
            this.fileDownload(res.data, fileName);
          }.bind(this)
        )
        .catch(
          function(error) {
            this.$Message.error("网络请求出错");
            //调试阶段可以看看报的什么错
            //console.log("error",error)
          }.bind(this)
        );
    },

    fileDownload: function(data, fileName) {
      let blob = new Blob([data], {
        //type类型后端返回来的数据中会有,根据自己实际进行修改
        type: "application/vnd.ms-excel"
      });
      let filename = fileName || "报表.xls";
      if (typeof window.navigator.msSaveBlob !== "undefined") {
        window.navigator.msSaveBlob(blob, filename);
      } else {
        var blobURL = window.URL.createObjectURL(blob);
        var tempLink = document.createElement("a");
        tempLink.style.display = "none";
        tempLink.href = blobURL;
        tempLink.setAttribute("download", filename);
        if (typeof tempLink.download === "undefined") {
          tempLink.setAttribute("target", "_blank");
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
      }
    }
  }
};
</script>

然后下面是我现在的页面

<template>
    <div>
        <PDF ref="pdf"></PDF>
        <el-button @click="previewFile(scope.row.fileId)">预览</el-button>
        <el-button @click="downloadFile(scope.row)">下载</el-button>
    </div>
</template>

<script>
import PDF from "../components/pdf.vue";
export default {
  components: {PDF},
  methods:{
    previewFile(id){
      this.$refs.pdf.previewPDF(后台的url接口,id) //id是预览要带给后台的,我怀疑就是这里出了问题,但是我不知道怎么解决。。。
    },
    downloadFile(obj){
      this.$refs.pdf.downloadPDF(后台的url接口,{ fileId: obj.id},obj.fileName)
    },
  }

下载的可以解决。。预览的话id传不过去
求解

回答:

感觉不想是传参数问题,我这边修改代码:

<template>
    <div >
        <pdf :src="src"></pdf>
    </div>
</template>

<template>
    <div>        
        <el-button @click="previewFile(scope.row.fileId)">预览</el-button>
        <el-button @click="downloadFile(scope.row)">下载</el-button>
        <PDF ref="pdf"></PDF>
    </div>
</template>

就可以正常显示。<PDF ref="pdf"></PDF>放在button之前好像有些异常(无法点击),原因不详

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注