因为平时经常会遇到各种pdf预览,所以封装了一个pdf预览组件,方便自己使用。
- 首先安装
vue-pdf-embed和vue3-pdfjs第三方库
npm install vue-pdf-embed --save
npm install vue3-pdfjs --save
2.预览组件的相关代码,支持分页、放大缩小功能。
<template>
<div class="center" v-if="loading">加载中。。。</div>
<div class="pdf-preview" v-else>
<div class="pdf-wrap">
<vue-pdf-embed :source="state.source" :style="scale" class="vue-pdf-embed" :page="state.pageNum" />
</div>
<div class="page-tool">
<div class="page-tool-item" @click="lastPage">
<StepBackwardOutlined />
</div>
<div class="page-tool-item" @click="nextPage">
<StepForwardOutlined />
</div>
<div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
<div class="page-tool-item" @click="pageZoomOut">
<ZoomInOutlined />
</div>
<div class="page-tool-item" @click="pageZoomIn">
<ZoomOutOutlined />
</div>
</div>
</div>
</template>
<script setup>
import { reactive, onMounted, computed, watch } from "vue";
import VuePdfEmbed from "vue-pdf-embed";
import { createLoadingTask } from "vue3-pdfjs/esm";
import { StepBackwardOutlined, StepForwardOutlined, ZoomInOutlined, ZoomOutOutlined } from "@ant-design/icons-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})`);
const lastPage = () => {
if (state.pageNum > 1) {
state.pageNum -= 1;
}
};
const nextPage = () => {
if (state.pageNum < state.numPages) {
state.pageNum += 1;
}
};
const pageZoomOut = () => {
if (state.scale < 2) {
state.scale += 0.1;
}
};
const pageZoomIn = () => {
if (state.scale > 0.1) {
state.scale -= 0.1;
}
};
const loading = ref(true);
onMounted(() => {
showPdf();
});
const showPdf = () => {
console.log(state.source);
if (!state.source) {
return;
}
loading.value = true;
const loadingTask = createLoadingTask(state.source);
loadingTask.promise.then((pdf) => {
state.numPages = pdf.numPages;
loading.value = false;
});
};
watch(
() => props.pdfUrl,
(newVal, oldVal) => {
if (newVal) {
state.source = JSON.parse(JSON.stringify(newVal));
showPdf();
}
},
{
immediate: true,
deep: true,
}
);
</script>
<style lang="css" scoped>
.pdf-preview {
position: relative;
height: calc(100vh - 50px);
padding: 20px 0;
box-sizing: border-box;
background-color: e9e9e9;
}
.pdf-wrap {
overflow-y: auto;
}
.vue-pdf-embed {
text-align: center;
width: 500px;
border: 1px solid #e5e5e5;
margin: 0 auto;
box-sizing: border-box;
}
.page-tool {
position: absolute;
bottom: 35px;
padding-left: 15px;
padding-right: 15px;
display: flex;
align-items: center;
background: rgb(66, 66, 66);
color: white;
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;
}
</style>