vue2下显示pdf并实现分页、加载带token的url地址、手指缩放功能

2022-09-06 704点热度 0人点赞 0条评论

需求说明

需要在vue项目中的页面中显示PDF文件,经过一番查找,决定使用这个项目:https://github.com/FranckFreiburger/vue-pdf/

另外还有手指缩放功能,使用的是:https://github.com/drozhzhin-n-e/vue-pinch-zoom

实现

package.json中引入:

"dependencies": {
    "pdfjs-dist": "2.5.207",
    "vue-pdf": "4.2.0",
    "vue-pinch-zoom": "^0.2.5"
  }

最简单的使用方式如下:

<template>
  <pdf src="./path/to/static/relativity.pdf"></pdf>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: {
    pdf
  }
}

我的需求是要PDF分页、加载带访问限制的url的PDF地址(例如http请求中head里是带Token的),另外针对PDF页面可能是手机版本,还需要带手指缩放功能,

如下代码(使用的是pdf.createLoadingTask,就可以指定http的headers了;在需要手机缩放的地方,套上PinchZoom):

<template>
    <div style="text-align: center;">
        <!--加载中,我用的是vant的,根据实际情况修改-->
        <van-loading type="spinner" v-show="loading" />
        <PinchZoom style="background: transparent;" ref="myPinch">
            <div>
                <pdf
                    v-for="i in numPages"
                    :key="i"
                    :src="src"
                    :page="i"
                    style=""></pdf>
            </div>
        </PinchZoom>
    </div>
</template>

<script>
    //see https://github.com/FranckFreiburger/vue-pdf
    import pdf from 'vue-pdf';
    import PinchZoom from 'vue-pinch-zoom';

    export default {
        name: "PdfViewer",
        components: {
            pdf, PinchZoom
        },
        data() {
            return {
                loading: true, // 页面中带一个加载中的指示器
                page: 1,
                numPages: 0,
                errors: [],

                src: pdf.createLoadingTask({
                    url: 'https://xxx/xxx.pdf',
                    withCredentials: true,
                    httpHeaders: {
                        'X-Token': localStorage.getItem("token")
                    }
                }) 
            }
        },
        created() {
            if (this.numPages === 0) {
                this.loading = true;
            }
        },
        mounted() {
            if (this.src) {
                this.src.promise.then(pdf => {
                    this.loading = false;
                    this.numPages = pdf.numPages;
                    // this.$refs["myPinch"].toggleZoom();
                });
            } else {
                this.loading = false;
            }
        },
        watch: {},
        methods: {}
    }
</script>

<style lang="css" scoped>
</style>

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论