vue项目-pdf文件预览

本文介绍如何在Vue项目中利用vue-pdf组件轻松实现PDF文件的预览功能。通过npm安装vue-pdf,结合组件属性和方法,如:page、num-pages、page-loaded等,实现翻页和加载效果。在创建加载任务解决跨域问题,最终达到理想的预览体验。
摘要由CSDN通过智能技术生成

在网上找了找,大多推荐的是pdf.js,不过在Vue中还是想偷懒直接npm组件,最后找到了一个还不错的Vue-pdf 组件。结合好几篇文章,最后完美实现自己想要的效果。

引用:npm install --save vue-pdf

页面渲染:

<template>
    <div class="pages">
        <span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">
             <span style="margin-right:5px">&lt;</span> 
        </span>
        {{currentPage}} / {{pageCount}}
        <span @click="changePdfPage(1)" class="turn" 
              :class="{grey: currentPage==pageCount}">
             <span style="margin-left:5px">&gt;</span> 
        </span>
    </div>
    <pdf ref="pdf" 
         :page="currentPage" 
         @num-pages="pageCount=$event"
         @page-loaded="currentPage=$event"
         @loaded="loadPdfHandler"
         :src="pdfUrl" 
         style="width: 100%;height:96%;overflow:hidden" 
         class="myScroll"/>
</template>

js逻辑:

<script>
import pdf from 'vue-pdf'
export default {
    components:{
        pdf
    },
    data(){
        return{
            currentPage: 0, // pdf文件页码
            pageCount: 0, // pdf文件总页数
            pdfUrl: '',
            baseURL: process.env.VUE_APP_BASE_API,
            url:"",
        }
    },
    methods:{
        loadPdfHandler (e) {
            this.currentPage = 1 // 加载的时候先加载第一页
        },
        changePdfPage (val) {
            if (val === 0 && this.currentPage > 1) {
                this.currentPage--
            }
            if (val === 1 && this.currentPage < this.pageCount) {
                this.currentPage++
            }
        },
    },
    created(){
        this.file = this.$route.params.file
        this.url = this.baseURL + this.$route.params.file.filePath

        const path = this.url// 你获取到的pdf路径
        this.pdfUrl = pdf.createLoadingTask(path)// pdf.createLoadingTask解决文件件跨域问题
    }
}
</script>

实现效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

甜甜凉白开

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值