属性不懂直接看文档,写的很清楚vue-pdf-embed - npm (npmjs.com)
App.vue中
<template>
<div>
<PDFView :pdfUrl="demoPdf" />
</div>
</template>
<script setup>
import PDFView from './components/pdfPreview.vue';
import demoPdf from './Js.pdf'
</script>
<style scoped>
</style>
pdfPreview.vue组件中
<template>
<div class="pdf-preview">
<div class="pdf-wrap">
<vue-pdf-embed :source="state.source" :style="scale" class="vue-pdf-embed" :page="state.pageNum" />
<div class="page-tool">
<div class="page-tool-item" @click="lastPage">上一页</div>
<div class="page-tool-item" @click="nextPage">下一页</div>
<div class="page-tool-item">{{state.pageNum}}/{{state.numPages}}</div>
<div class="page-tool-item" @click="pageZoomOut">放大</div>
<div class="page-tool-item" @click="pageZoomIn">缩小</div>
</div>
</div>
</div>
</template>
<script setup>
import VuePdfEmbed from "vue-pdf-embed";
import { createLoadingTask } from "vue3-pdfjs";
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 > 1) {
state.scale -= 0.1;
}
}
onMounted(()=>{
const loadingTask = createLoadingTask(state.source);
loadingTask.promise.then((pdf) => {
state.numPages = pdf.numPages;
});
})
</script>
<style lang="css" scoped>
.pdf-preview {
position: relative;
height: 100vh;
padding: 20px 0;
box-sizing: border-box;
background: rgb(66, 66, 66);
}
</style>
npm install vue-pdf-embed
npm install vue3-pdfjs
唯一注意点就是,pdf如果没有正常渲染出来的话,将vue-pdf-embed版本回退到1.2.1,虽然不知道这是什么原因。。