1.下载pdf.js库
下载后的文件解压结构是这样的
2. 放入项目中
在vue3中public文件夹下新建 lib/pdfjs 文件 , 将解压后的文件放入pdfjs文件夹下
3.新建pdf组件
在src/components新建pdf.vue组件
<template> <iframe :src="src" width="100%" :web.xmlheight="pdfh" style="width: 100%; height: 90%"></iframe> </template> <script setup lang='ts'> import { ref, nexttick, computed, onmounted } from 'vue' const props = defineprops({ src: { type: string, required: true } }) let src = computed(() => { // vue3的话 路径上不需要写public // 如果是vue2的话 要写public -> return `/public/lib/pdfjs/web/viewer.html?file=${props.src}` // 我这里是本地文件测试(props.src是本地文件,必须将这个文件放在public/lib/pdfjs/web下面才行) return `/lib/pdfjs/web/viewer.html?file=${props.src}` }) let pdfh = ref(100) nexttick(() => { pdfh.value = document.documentelement.clientheight - 68 }) onmounted(() => { }) </script>
4.在homeview.vue文件中使用pdf.vue
这里我使用了 打开新页面预览和弹窗预览 两种方式来预览
<script setup lang="ts"> import { ref } from 'vue'; import pdf from '@/components/pdf.vue' let dysrc = ref('') const dialogvisible = ref(false) //? 打开新页面预览 const showpdf = async () => { dysrc.value = '/lib/pdfjs/web/测试.pdf' //替换为实际的文档url const pdfurl = `lib/pdfjs/web/viewer.html?file=${dysrc.value}`; //pdfurl是当前页面的pdf文件的url,第二个参数'_blank'表示在新窗口中打开。 window.open(pdfurl, '_blank'); } //?在弹框中显示 const showdialogpdf = () => { dialogvisible.value = true dysrc.value = '/lib/pdfjs/web/测试.pdf' } </script> <template> <div> 文件名(新页面打开预览): <span @click="showpdf" style="color:rgb(0,174,236);cursor: pointer;">xxx.pdf</span> </div> <div> 文件名(弹窗打开预览): <span @click="showdialogpdf" style="color:rgb(0,174,236);cursor: pointer;">xxx.pdf</span> </div> <el-dialog v-model="dialogvisible" title="预览pdf"> <p-d-f :src="dysrc"></p-d-f> </el-dialog> </template> <style> .el-dialog { width: 1000px; height: 800px; } .el-dialog__body { height: 100%; } </style>
注意:
本地文件测试 必须将pdf文件放在public/lib/pdfjs/web下面才行
5.跨域问题
如果出现跨域问题,将 viewer.js文件中的以下代码注释掉就可以了
// if (fileorigin !== viewerorigin) { // throw new error("file origin does not match viewer's"); // }
6.总结
到此这篇关于vue3使用pdf.js来预览文件的操作步骤(本地文件测试)的文章就介绍到这了,更多相关vue3 pdf.js预览文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论