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) {}
)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值