h5 + vant + ts展示pdf

h5 + vant + ts展示pdf

1、npm install vue-pdf@4.2.0
2、组件中引用 import pdf from “vue-pdf”;

pdf 与 van-popup 封装

<template>
  <div class="view-pdf">
    <!-- 预览pdf -->
    <van-popup v-model="showPop"
               round
               position="bottom"
               :style="{ height: '90%' }">
      <pdf v-for="i in numPages"
           :key="i"
           :src="src"
           :page="i"
          ></pdf>
    </van-popup>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Emit } from "vue-property-decorator";
// 引入pdf
import pdf from "vue-pdf";
// 解决部分文字不显示的问题
// import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
import axios from "axios";
@Component({
  components: {
    pdf,
  },
})
export default class index extends Vue {
  @Prop() data: any;

  src: any = "";
  numPages: number = 0;
  page: number = 1;
  currentPage: number = 0;
  showPop: boolean = false;
  isWX: boolean = true;

  created() {
    var ua: any = window.navigator.userAgent.toLowerCase();
    // 判断是否是微信打开
    this.isWX = ua.match(/MicroMessenger/i) == "micromessenger";
  }

  handleSee() {
    if (this.data.content) {
      if (this.data.type == "pdf") {
        // 如果后端返回数据是base64
        //let da = dataURLtoBlob(this.data.content)
        let da = this.data.content;
        let _this = this
        let win: any = window
        if (win.createObjectURL != undefined) { // basic
          _this.src = win.createObjectURL(da)
        } else if (win.webkitURL != undefined) { // webkit or chrome
          try {
            _this.src = win.webkitURL.createObjectURL(da)
          } catch (error) {

          }
        } else if (win.URL != undefined) { // mozilla(firefox)
          try {
            _this.src = win.URL.createObjectURL(da)
          } catch (error) {
          }
        }
        let loadingTask = pdf.createLoadingTask(_this.src)
        this.showPop = true;
        loadingTask.promise.then((pdf: any) => {
          _this.numPages = pdf.numPages
          }).catch((err: any) => {
          console.error('pdf 加载失败', err)
        })
      } 
    } else {
      this.$toast.fail("内容不存在");
    }
  }

  //base64 转换 blob
  dataURLtoBlob(dataurl: any) {
    var bstr = atob(dataurl);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: "pdf" });
  }
}
</script>

<style scoped lang="less">
.btn-group {
  padding: 24px;
}
</style>

对封装popup引用

<van-button type="info" @click='handleViewPdf'>查看</van-button>
<view-pdf :data="currentPdfInfo" ref="view-pdf" />

此案例返回为blob


// 查看按钮点击方法
handleViewPdf() {
  this.$toast.loading({
     duration: 0,
        message: "正在加载",
     });
     let config: any = {
        url: "/admin/pdf/download",
        method: 'get',
        baseURL: process.env.VUE_APP_URL + "/credit",
        responseType: "blob",
        headers: {
           "X-Access-Token": getStore("token") ? getStore("token") : "",
        },
        params: {
           type: '2',
             entryId: this.orderDetail[0].orderId
           },
        };
        axios(config).then((response: any) => {  
            this.$toast.clear();
            if (response.status == 200) {
                const content: any = response.data;
                const blob = new Blob([content], { type: "application/pdf" });
                this.currentPdfInfo = {
                    content: blob,
                    type: "pdf",
                };

                this.$nextTick(() => {
                    let ele: any = this.$refs["view-pdf"];
                    ele.handleSee();
                });
            }
        })
    }

ps:
需要注意的点,自己一直卡了很久
关于axios封装 拦截器需要对 blob单独设置。

axios.interceptors.response.use(
    function(response) {
        console.log("Response", response)
        if (response.status == 200) {
            let responseData = response.data
            if (response.config.responseType == "blob") {
                return response;
            }
            return responseData
        } else {
            return {}
        }
    },
    function(error) {}
)

版权声明:本文为weixin_43918803原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。