vue 将base64 的文件流转换成pdf 预览并下载

时间:2025-02-15 22:23:20

pdf显示布局,鼠标滑过pdf显示下载按钮

 <el-tooltip placement="right-start" effect="light">
      <div
        slot="content"
        class="content"
        @click="downFile(photosList[index])"
      >
          下载
      </div>
      <div
          @click="showPdfClick(index)"
          class="pdfBox"
       >
           <Pdf :pdfSrc="photosList[index]"></Pdf>
      </div>
 </el-tooltip>
// pdf预览布局
 <div v-if="showPdf" class="largePhotoBox">
      <div style="width: 80%; margin-left: 10%">
        <span @click="showPdf = false">x</span>
        <Pdf :pdfSrc="photosList[photoIndex]"></Pdf>
      </div>
 </div>

这里是预览以及下载代码的一部分,传的base64根据自己需求直接在方法里面传值

data(){
  return{
    photoIndex: "",
    showPdf
 }
}

PDF的下载功能,这里是通过js中a标签实现的

// 下载
 downFile(perfix64) {
      ( ,perfix64);
  },
  // 这里的filename自己定义
  downloadFile(fileName, content) {
      let aLink = ("a");
      let blob = this.base64ToBlob(content);
      let evt = ("HTMLEvents");
      ("点击下载", evt);
      ("click", true, true);
       = fileName;
       = (blob);
      ();
    },
    // base64转blob
    base64ToBlob(code) {
      let parts = (";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = (parts[1]);
      let rawLength = ;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = (i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },
    // 预览显示pdf
     showPdfClick(index) {
       = index;
       = true;
    },

pdf预览css

.largePhotoBox {
  width: 100%;
  height: 100%;
  overflow: auto;
  background: rgba(0, 0, 0, 0.6);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  &::-webkit-scrollbar {
    display: none;
  }
  img {
    width: 50%;
    margin-left: 25%;
    margin-top: 50px;
  }
  span {
    font-size: 30px;
    position: fixed;
    color: #fff;
    top: 30px;
    right: 50px;
  }
}

PDF的预览功能,这里单独写了个子组件,直接复制,很简单

<template>
  <div>
    <pdf v-for="i in numPages" :key="i" :page="i" :src="src"></pdf>
  </div>
</template>
<script>
import pdf from "vue-pdf";
export default {
  components: {
    pdf,
  },
  props: {
    pdfSrc: String,
  },
  data() {
    return {
      numPages: null,
      src: "",
    };
  },
  mounted() {
    (); // base64pdf 文件的预览
  },
  methods: {
    // #计算pdf页码总数
    getNumPages() {
      let perfix64;     
        perfix64 =
          "data:application/pdf;base64," + ;
      let CMAP_URL = "/pdfjs-dist@2.0.943/cmaps/";
       = ({
        url: perfix64,
        withCredentials: false,
        cMapUrl: CMAP_URL,
        cMapPacked: true,
      });
      
        .then((pdf) => {
           = ;
          ();
        })
        .catch((err) => {
          ("pdf 加载失败", err);
        });
    },
    
  }
};
</script>

注意

这个代码只适用于返回的base64只是pdf文件的base64码,如果返回的base64码的类型不确定,记得要加判断,传值的时候可以把想要传的base64码使用split切割传值