绵阳动力网站建设

vue3框架中在线预览pdf文件的方法和代码

时间:2023-11-13

最近在用VUE3框架做网站建设时需要有大量的PDF文件上传,同时要在前台供用户在线浏览。通过查看官方的文档和搜索资料,最终选择用vue3+vite的组合方式来实现,现将相关代码分享出来供大家参考。

首先我们来看实际浏览效果:


vue3框架中在线预览pdf文件的方法和代码

接着我们来看具体代码内容:

<template>
    <div>
        <div>
            <vue-pdf-embed :source="state.source" :style="scale" :page="state.pageNum" />
        </div>
        <div>
            <div @click="lastPage()">上一页</div>
            <div @click="nextPage()">下一页</div>
            <div>{{state.pageNum}}/{{state.numPages}}</div>
            <div @click="pageZoomOut()">放大</div>
            <div @click="pageZoomIn()">缩小</div>
            <div @click="$emit('close')">关闭</div>
        </div>
    </div>
</template>
<script setup>
import VuePdfEmbed from "vue-pdf-embed";
//import { createLoadingTask } from "vue3-pdfjs/esm/vue-pdf.js";
import * as pdfjsLib from "pdfjs-dist";
import { reactive, onMounted, computed } from "vue";

const props = defineProps({
    pdfUrl: {
        type: String,
        required: true
    }
})


const state = reactive({
    source: props.pdfUrl, //预览pdf文件地址
    pageNum: 1, //当前页面
    scale: 1, // 缩放比例
    numPages: 0, // 总页数
});
const scale = computed(() => `transform:scale(${state.scale})`)
function lastPage() {
    if (state.pageNum > 1) {
        state.pageNum -= 1;
    }
}
function nextPage() {
    if (state.pageNum < state.numPages) {
        state.pageNum += 1;
    }
}
function pageZoomOut() {
    if (state.scale < 2) {
        state.scale += 0.1;
    }
}
function pageZoomIn() {
    if (state.scale > 0.8) {
        state.scale -= 0.1;
    }
}
onMounted(() => {
    pdfjsLib.GlobalWorkerOptions.workerSrc = "./pdf.worker.js";
    const loadingTask = pdfjsLib.getDocument(state.source);
    loadingTask.promise.then((pdf) => {
        state.numPages = pdf.numPages;
    });
});

</script>
<style scoped>
.pdf-preview {
    position: fixed;
    height: 100vh;
    width: 100vw;
    padding: 20px 0;
    box-sizing: border-box;
    background-color: #e9e9e9;
    left: 0;
    top: 0;
    z-index: 99999999;
    overflow-y: auto;
}

.pdf-wrap {
    overflow-y: auto;
}

.vue-pdf-embed {
    text-align: center;
    width: 60vw;
    border: 1px solid #e5e5e5;
    margin: 0 auto;
    box-sizing: border-box;
}

.page-tool {
    position: fixed;
    bottom: 35px;
    padding-left: 15px;
    padding-right: 15px;
    display: flex;
    align-items: center;
    background: rgb(66, 66, 66);
    border-radius: 19px;
    z-index: 100;
    cursor: pointer;
    margin-left: 50%;
    transform: translateX(-50%);
}

.page-tool-item {
    padding: 8px 15px;
    padding-left: 10px;
    cursor: pointer;
    color: #fff !important;
}
</style>

好了,通过以上代码就可以实现我们今天为大家分享的关于在vue3框架中在线预览pdf文件的功能了,如果你看完后喜欢的记得收藏哦。

Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号

客服微信
客服微信
0816-6339181
客服微信
my_dongli