安装依赖
npm install vue-pdf-embed -S
封装组件:因为UI同事有设计预览样式,不能用默认,以及综合各种因素考虑,将PDF组件作为子组件套在弹窗父组件中。
父组件
<template> <!-- 预览弹窗 --> <Dialog :title="$t('message.preview')" :visible="showPDFPreviewDialog" @handleClose="switchPDFPreviewDialog" > <template v-slot:content> <p class="preview_title">{{ pdfTitle }}</p> <div class="pdf_centent" id="pdfCentent"> <PdfPreview :pdfSource="pdfSource" :isChangeToNextPage="isChangeToNextPage" :isChangeToPrePage="isChangeToPrePage" @clickDownloadBtn="previweClickDownBtn" @switchIsChangeToNextPage="switchIsChangeToNextPage" @switchIsChangeToPrePage="switchIsChangeToPrePage" /> </div> </template> <template v-slot:footer v-if="false"> </template> </Dialog> </template> <script setup> import { ref, defineAsyncComponent } from 'vue' //异步组件 const PdfPreview = defineAsyncComponent(() => import('@/components/pagecom/pdfPreview.vue')) const props = defineProps({ showPDFPreviewDialog: { //dialog是否展示 type: Boolean, default: false, }, switchPDFPreviewDialog: { // 切换对话框的显示状态 type: Function, default: () => {} }, previweClickDownBtn: { // 预览界面点击下载 type: Function, default: () => {} }, pdfSource: { // pft链接 type: String, default: '' }, pdfTitle: { // pdf标题 type: String, default: '' }, }) const isChangeToNextPage = ref(false) // 是否向下翻页 const isChangeToPrePage = ref(false) // 是否向上翻页 const switchIsChangeToNextPage = value => { // 滚动到当前页面底部时的操作 let pdfCentent = document.getElementById('pdfCentent') // 当滚动到底部且没有向下翻页过,此时子组件即将向下翻页,因为翻页之后滚动条的位置仍处于底部,再次向下滚动会出现连续翻页的问题,故而父组件将滚动条恢复至页面顶部,并修改状态 if (pdfCentent.scrollTop === 1363 && !isChangeToNextPage.value) { pdfCentent.scrollTop = 0 } isChangeToNextPage.value = value // 修改是否向下翻页的状态 } const switchIsChangeToPrePage = value => { // 滚动到当前页面顶部时的操作 let pdfCentent = document.getElementById('pdfCentent') // 当滚动到顶部且没有向上翻页过,此时子组件即将向上翻页,因为翻页之后滚动条的位置仍处于顶部,再次向上滚动会出现连续翻页的问题,故而父组件将滚动条恢复至页面底部,并修改状态 if (pdfCentent.scrollTop === 0 && !isChangeToPrePage.value) { pdfCentent.scrollTop = 1363 } isChangeToPrePage.value = value // 修改是否向上翻页的状态 } </script> <style lang="less" scoped> .preview_title { position: absolute;; top: 66px; left: 0px; width: 100%; padding-left: 24px; height: 50px; line-height: 50px; border-bottom: 1px solid #e7e7e7; background-color: #fff; z-index: 99; box-sizing: border-box; } .pdf_centent { width: calc(100% + 48px); height: calc(100% - 18px); margin-top: 42px; margin-left: -24px; padding-left: 24px; padding-bottom: 24px; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; background-color: #fff; overflow-y: auto; overflow-x: auto; box-sizing: border-box; } </style>
子组件
<template> <div style="margin-top: 20px;"> <template v-if="state.isLoading">{{ $t('message.pdfLoading') }}</template> </div> <div class="over_wrap" id="pdfWrap"> <VuePdfEmbed ref="pdfRef" :source="pdfSource" :page="state.page" :style="scaleFun" @rendered="handleDocumentRender" /> <div class="bottom_btns_wrap"> <!-- 上一页 --> <span :class="{btn_disabled: state.page <= 1}" @click="clickPageUp"></span> <!-- 页码信息 --> <span>{{state.page}}/{{ state.pageCount }}</span> <!-- <span><input type="text" :value="state.page" @input="replaceValue" @blur="changePage" />/<i>{{ state.pageCount }}</i></span> --> <!-- 下一页 --> <span :class="{btn_disabled: state.page >= state.pageCount}" @click="clickPageDown"></span> <!-- 分隔符 --> <span class="bar"></span> <!-- 缩小 --> <span :class="{btn_disabled: false}" @click="clickCanvaReduce"></span> <!-- 缩放信息 --> <span>{{ widthZoom }}</span> <!-- 放大 --> <span :class="{btn_disabled: false}" @click="clickCanvaAmplify"></span> <!-- 分隔符 --> <span class="bar"></span> <!-- 下载 --> <span @click="clickDownloadBtn"></span> </div> </div> </template> <script setup> import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'; import VuePdfEmbed from 'vue-pdf-embed' const props = defineProps({ pdfSource: { type: String, default: '' }, isChangeToNextPage: { type: Boolean, default: false }, isChangeToPrePage: { type: Boolean, default: false } }) const emit = defineEmits(['clickDownloadBtn', 'switchIsChangeToNextPage', 'switchIsChangeToPrePage']) const pdfRef = ref() const state = reactive({ isLoading: true, page: null, pageCount: 1, showAllPages: false, // 单页显示 scale: 1, canvaWidth: 0.5, }) const widthZoom = computed(() => `${(state.scale * 100).toFixed(0)}%`) const scaleFun = computed(() => { let scale = state.scale; return `transform:scale(${scale})`; }) watch(() => state.showAllPages, // 不能去除,去除监听后会默认显示所有页面 () => { state.page = state.showAllPages ? null : 1 }, {immediate: true} ) const clickDownloadBtn = () => emit('clickDownloadBtn') const handleDocumentRender = () => { // PDF加载 state.isLoading = false state.pageCount = pdfRef.value.pageCount } const clickPageUp = () => state.page <= 1 ? '' : state.page-- // 向前翻页 按钮 const clickPageDown = () => state.page >= state.pageCount ? '' : state.page++ // 向后翻页 按钮 const clickCanvaAmplify = () => { // 放大按钮 state.scale >= 1.5 ? '' : state.scale = Number((state.scale + 0.1).toFixed(1)) } const clickCanvaReduce = () => { // 缩小按钮 state.scale <= 0.5 ? '' : state.scale = Number((state.scale - 0.1).toFixed(1)) } const replaceValue = (event) => { // input输入限制 需求没有这个功能没用到 event.target.value = event.target.value.replace(/^(0+)|[^d]+/g,'') } const changePage = (event) => { // 输入翻页触发 if(event.target.value=='') { event.target.value = state.page } else if(event.target.value > state.pageCount) { event.target.value = state.page } else { state.page = event.target.value } } onMounted(() => { document.onmousewheel = event => { // 获取元素上边到视窗上边的距离 let _top = parseInt(document.getElementsByClassName('vue-pdf-embed')[0].getBoundingClientRect().top) if (event.wheelDelta > 0 || event.detail < 0) { // 向上滚 // 滚动到顶部,不是第一页,且没有向上滚动翻页过 if (_top === 220 && state.page !== 1 && !props.isChangeToPrePage) { // 在翻页前先触发父组件方法,将滚动条设置到底部 emit('switchIsChangeToPrePage', true) // 进行翻页 state.page -= 1 // 将向上翻页状态恢复至默认 emit('switchIsChangeToPrePage', false) } } else if (event.wheelDelta < 0 || event.detail > 0) { // 向下滚 // 滚动到底部,不是第最后一页,且没有向下滚动翻页过 if(_top === -1142 && state.page !== state.pageCount && !props.isChangeToNextPage) { // 在翻页前先触发父组件方法,将滚动条设置到顶部 emit('switchIsChangeToNextPage', true) // 进行翻页 state.page += 1 // 将向下翻页状态恢复至默认 emit('switchIsChangeToNextPage', false) } } } }) // 清空滚轮事件 onUnmounted(() => document.onmousewheel = null) </script> <style lang="less" scoped> .over_wrap { height: 100%;} .bottom_btns_wrap { position: absolute; left: 50%; bottom: 32px; transform: translateX(-50%); padding: 8px 21px; min-width: 337px; height: 44px; background: rgba(0,0,0,0.8); color: #fff; // opacity: 0.8; // background: #000; border-radius: 8px; box-sizing: border-box; span { display: inline-block; width: 28px; height: 28px; cursor: pointer; &:hover { border-radius: 4px; } } span:nth-child(2),span:nth-child(6) { position: relative; top: -8px;} span:nth-child(1) { background: url('@/assets/img/pdf_pgup.png') no-repeat center; &:hover { background: url('@/assets/img/pdf_pgup.png') no-repeat center #484848; } &:active { background: url('@/assets/img/pdf_pgup.png') no-repeat center #3d3d3d; } } span:nth-child(2) { margin: 0 11px ; width: 60px; line-height: 22px; height: 22px;user-select: none;text-align: center; input { display: inline-block;max-width: 26px; text-align: right;background-color: transparent;color: #fff;} } span:nth-child(3) { background: url('@/assets/img/pdf_pgdn.png') no-repeat center; &:hover { background: url('@/assets/img/pdf_pgdn.png') no-repeat center #484848; } &:active { background: url('@/assets/img/pdf_pgdn.png') no-repeat center #3d3d3d; } } span:nth-child(5) { background: url('@/assets/img/pdf_reduce.png') no-repeat center; &:hover { background: url('@/assets/img/pdf_reduce.png') no-repeat center #484848; } &:active { background: url('@/assets/img/pdf_reduce.png') no-repeat center #3d3d3d; } } span:nth-child(6) { margin: 0 11px; width: 42px;line-height: 22px;user-select: none;} span:nth-child(7) { background: url('@/assets/img/pdf_amplify.png') no-repeat center; &:hover { background: url('@/assets/img/pdf_amplify.png') no-repeat center #484848; } &:active { background: url('@/assets/img/pdf_amplify.png') no-repeat center #3d3d3d; } } span:nth-child(9) { background: url('@/assets/img/pdf_download.png') no-repeat center; &:hover { background: url('@/assets/img/pdf_download.png') no-repeat center #484848; } &:active { background: url('@/assets/img/pdf_download.png') no-repeat center #3d3d3d; } } .bar { width: 1px !important; height: 16px; background-color: #565657; margin: 5px 10.5px; } .btn_disabled { cursor: no-drop;} } ::v-deep .vue-pdf-embed { margin-top: 18px; // margin-right: 20px; overflow: auto; transform-origin: center; } ::v-deep .vue-pdf-embed>div { margin-bottom: 18px; } ::v-deep .vue-pdf-embed canvas { width: 98% !important; border: 1px solid #e7e7e7; box-shadow: 0px 2px 8px 0px rgba(0,0,0,0.10); } </style>
总结
分到这个需求时找了挺多依赖,被推荐最多的是vue-pdf,但用不了,依稀记得有样式不好调整,并且有不适用vue3的问题。写这篇文章的时间离需求开发过去应该有半年多了,记不太清了。总之,试了几个依赖后选择了vue-pdf-ebed,官网示例。
放大功能还有些缺陷,放很大时没有滚动条,暂时没有解决,所幸需求限制只能放大到150%,当下开发任务重就没有继续研究。
滚动翻页功能是最近的优化需求,在官网没有找到直接实现的方法,翻了翻网络,都是其他依赖的帖子,而且也没有滚动翻页的功能,思来想去,决定通过监听滚动距离来实现。
起初以切都还顺利,到了将滚动条设置到顶部 / 底部时,是通过子组件的pdf内容页来获取滚动距离,但是一直没有获取到,卡了半天突然想起项目中有个地方也修改过滚动距离,查看了下代码,才发现是获取的父容器的滚动距离。将这点解决,功能也就完成得差不多了,使用起来观感也算丝滑,虽然原理上感觉不那么丝滑,但总归实现了不是,目测也不会有什么大bug。
后来想了想,scrollTop为什么是父容器在改变,子组件一直都是零,个人思考结论是:滚动条是父容器的滚动条,不是子组件的。之前一直想的是子组件的内容在动,理应修改子组件的scrollTop,谁知一直是0。因此在修改scrollTop时需要获取父组件的,之前没有注意过这点。
结论正确性有待考究,先记录一下。