vue通过文件流预览pdf文件,并导出pdf文件

首先下载vue-pdf

npm install --save vue-pdf

然后直接看代码吧

完整代码如下

<template>
  <div>
  <el-button
            class="grid-button"
            type="success"
            plain
            size="small"
            @click="exportdata"
            >导出el-button
          >
     <div class="inform">
      <div class="browse">
        <pdf
          ref="pdf"
          v-for="i in numPages"
          :key="i"
          :src="src"
          :page="i"
        >pdf>
      div>
    div>
  div>
template>

<script>
//引入vue-pdf
import pdf from "vue-pdf";
export default {
  data() {
    return {
       src: "",
       numPages: 1, // pdf 总页数
    };
  },
  components: {
   pdf
  },
  methods: {
 //下载pdf文件
    exportdata(){
        url
        .接口名({ 数据})
        .then((res) => {
        let blob = new Blob([res.data], {
              type: "application/pdf;charset-UTF-8"
            });
            let link = document.createElement("a");
            let fileName = "文件名"; //文件命和后缀
             link.style.display = 'none'
            link.href = window.URL.createObjectURL(blob);
            link.download = decodeURIComponent(fileName);
            link.click();
        })
        .catch((err) => {
          console.log(err, "失败");
        });
    },
  
    
    //预览
    lookFile() {
       url
        .接口名字({ 数据 })
        .then((res) => {
         this.src = this.getObjectURL(res.data);
        })
        .catch((err) => {
          console.log(err, "失败");
        });
    },
     // 将返回的流数据转换为url
    getObjectURL(file) {
      let src = null;
      if (window.createObjectURL) {
        // basic
        src = window.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        try {
          src = window.webkitURL.createObjectURL(file);
        } catch (error) {}
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        try {
          src = window.URL.createObjectURL(file);
        } catch (error) {}
      }
    //   console.log(src, "我是src");
      this.getNumPages(src);
      return src;
    },
  //  # 计算pdf页码总数
    getNumPages(src) {
      let loadingTask = pdf.createLoadingTask(src);
    //   console.log(loadingTask, "我是计算页码");
      loadingTask.promise
        .then(pdf => {
          this.numPages = pdf.numPages;
        })
        .catch(err => {
          console.error("pdf 加载失败", err);
        });
    }
  },
  mounted() {
    this.lookFile();
  },
};
script>

<style scoped>

style>


注意点

接口请求时需要携带axios下载文件(responseType: “blob”)


getData.接口名= data => {
  return http.get(接口链接, { params: data,responseType: "blob" });
};

你可能感兴趣的:(vue)