vue中使用 vue-pdf 实现PDF文件预览
<style lang="scss"> .PDFViewer{ background-color: #3a3a3a; font-size: 16px; height: 100%; overflow: scroll; a { text-decoration: none; } .PDFViewerHeader{ background-color:white; color: #3a3a3a; height: 60px; line-height: 60px; h1 { margin: 0; padding-left: 20px; font-size: 16px; height: 60px; line-height: 60px; } span { width: 100%; display: inline-block; text-align: center; } } .DownloadBtn{ float: right; } .PDFViewerBody{ padding: 40px; } .card { margin-bottom: 10px; } } </style> <template> <div class="PDFViewer" v-loading.fullscreen.lock="fullscreenLoading"> <header class="PDFViewerHeader"> <el-row> <el-col :span="8"> <h1>{{name}}</h1> </el-col> <el-col :span="8"> <span>{{numPages}}页</span> </el-col> <el-col :span="8"> <el-menu background-color="#fff" text-color="#3a3a3a" height="100%"> <el-menu-item index="1" class="DownloadBtn"> <a :href="this.url" download="">下载</a> </el-menu-item> </el-menu> </el-col> </el-row> </header> <div class="PDFViewerBody"> <el-card class="card" v-for="i in numPages" :key="i" shadow="always"> <pdf :src="src" :page="i" :key="i" style="display: inline-block; width: 100%; height: 100%;" ></pdf> </el-card> </div> <el-backtop target=".PDFViewer" :right="80"> <div style=" { height: 100%; width: 100%; background-color: #3a3a3a; border-radius: 20px; box-shadow: 0 0 6px rgba(0,0,0, 1); text-align: center; line-height: 40px; color: #ffffff; }"> <em class="el-icon-caret-top"></em> </div> </el-backtop> </div> </template> <script> import pdf from 'vue-pdf' export default { components:{ pdf }, data() { return{ fullscreenLoading: true, name:'', url: '', src: undefined, currentPage: 0, numPages: 0 } }, created() { this.name = 'STJ0704195A_M091101.pdf_3.pdf'; //this.url = this.$route.query.url; this.url = 'STJ0704195A_M091101.pdf_3.pdf'; this.src = pdf.createLoadingTask(this.url); }, mounted() { this.src.promise.then(pdf => { this.numPages = pdf.numPages; this.fullscreenLoading = false; }).catch(err => { console.log(err) this.$message.error(`${err.message}: 加载PDF文件失败`); }) }, methods: { } } </script>
使用vue-pdf会出现跨域问题,所以在开发的时候先可以使用本地文件。将PDF放到在vue项目工程目录下的public文件中,使用‘localhost:8080/’+PDF文件名即可访问。
关于跨域问题,如果后端同学不能帮忙解决,你可以使用跨域代理转发来解决,我在另一篇随笔有提到大概方法。链接
效果如下:
我们还可以使用浏览器自带的功能来实现预览。
<a href="http://xxxx.pdf" target="_blank"><span>预览</span></a>