1. 程式人生 > 其它 >h5展示pdf

h5展示pdf

技術標籤:vantvue

h5 + vant + ts展示pdf

1、npm install [email protected]
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) {}
)