1、首先安装vue-pdf
npm install --save vue-pdf
2、在 vue.config.js中配置能加载pdf 的loader
module.exports = { configureWebpack: { module: { rules: [ { test: /\.(png|jpe?g|gif|pdf)$/i, loader: 'file-loader', options: { name: '[path][name].[ext]', }, }, ], }
}}
第三步:
第四步:在pdffile.vue 中写如下代码即可全部显示PDF
<template> <div class="about"> <pdf v-for="i in pdfinfo['numPages']" :src="pdfinfo['src']" :page="i" ></pdf> </div></template><script> import pdf from 'vue-pdf' import bps from "../assets/PDfFile/bps.pdf" export default { name: "PDFFile", components: { pdf }, data() { return { numPages: 1, pdfinfo:{ src: bps, numPages:1, }, } }, mounted() { this.handelPdf() }, methods: { async handelPdf() { this.pdfinfo['numPages'] = await pdf.createLoadingTask(this.pdfinfo["src"]).promise.then(pdf => { return pdf.numPages }) } } }</script>
效果如下:
如果想一页一页显示可修改第四步中的代码如下:
<template> <div > <div class="wrap_button"> <div @click="beforePage">上一页</div> <div @click="nextPage">下一页</div> </div> <div class="pdf"> <pdf ref="pdf" :page="page" @progress="pdfProcess" @page-loaded="overReload" @num-pages="numPages" @error="errorReload" :src="bps"> </pdf> </div> </div></template><script> import bps from "../../assets/PDFFile/bps.pdf" import pdf from 'vue-pdf' export default { name: 'Pdf', components: { pdf }, data() { return { bps, page:1, totalPage:1, } }, methods:{ beforePage:function(){ if(this.page>1){ this.page-- } }, nextPage:function(){ if(this.page<this.totalPage){ this.page++ } }, pdfProcess:function (number) { console.log("pdfProcess",number) }, overReload:function(number){ console.log("overReload",number) }, numPages:function (number) { this.totalPage = number console.log("numPages",number) }, errorReload:function (obj) { console.log("obj",obj) } }, }</script><style> .wrap_button{ width: 100%; height: 50px; display: flex; justify-content: space-between; } .wrap_button>div{ width: 100px; background-color: deeppink; height: 100%; }</style>
点击上一页和下一页翻页