PdfPreview.vue 2.33 KB
<!--
 * @Date: 2024-01-17
 * @Description: PDF预览组件
-->
<template>
    <van-popup v-if="show" :show="show" @update:show="emit('update:show', $event)" position="right"
        :style="{ height: '100%', width: '100%' }">
        <div id="pdf-container"></div>
        <van-button class="close-btn" type="default" icon="cross" round @click="emit('update:show', false)" />
    </van-popup>
</template>

<script setup>
import { ref, nextTick, onMounted, computed } from 'vue';
import { initPdfView, configPdfApiOptions } from "@sunsetglow/vue-pdf-viewer";
import "@sunsetglow/vue-pdf-viewer/dist/style.css";

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    url: {
        type: String,
        default: ''
    },
    title: {
        type: String,
        default: ''
    }
});

const emit = defineEmits(['update:show']);

// PDF Worker路径
const loading = ref(false);
const pdfPath = new URL("@sunsetglow/vue-pdf-viewer/dist/libs/pdf.worker.min.js", import.meta.url).href;

// 监听show属性变化
watch(() => props.show, (newVal) => {
    if (newVal && props.url) {
        initPdfViewer();
    }
});

// 初始化PDF预览
// 查看文档 https://www.npmjs.com/package/@sunsetglow/vue-pdf-viewer
const initPdfViewer = () => {
    nextTick(() => {
        initPdfView(document.querySelector("#pdf-container"), {
            loadFileUrl: props.url,
            pdfPath: pdfPath,
            loading: (load, fileInfo) => {
                loading.value = load;
            },
            pdfOption: {
                search: false,
                scale: true,
                pdfImageView: true,
                page: true,
                navShow: true,
                navigationShow: false,
                pdfViewResize: true,
                toolShow: true,
                download: true,
                clearScale: 1.5,
                fileName: props.title,
                lang: "en",
                print: false,
                watermarkOptions: undefined
            }
        });
    });
};
</script>

<style scoped>
#pdf-container {
    width: 100%;
    padding: 0px;
    height: 100%;
}

.close-btn {
    position: fixed;
    right: 20px;
    bottom: 20px;
    z-index: 100;
    width: 40px;
    height: 40px;
    padding: 0;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
}
</style>