vue 使用 vue-pdf 实现pdf在线预览
1、安装
npm install --save vue-pdf
2、引用
import pdf from 'vue-pdf'
export default {
components: {
pdf },
data() {
return {
pdfUrl: "pdf的路径" ,// 本地获取或者在线请求获取
};
},
};
3、页面使用
<div class="content">
<pdf
ref="pdf"
:src="pdfUrl"
></pdf>
</div>
4、发现问题,只能显示一页,显示所有页面
<div class="content">
<pdf
ref="pdf"
v-for="item in numPages"
:key="item"
:page="item"
:src="pdfSrc"
></pdf>
</div>
import pdf from 'vue-pdf'
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
export default {
components: {
pdf },
data() {
return {
numPages: "", // pdf 文件总页数
pdfSrc: "",
pdfUrl: "", // pdf 文件的路径,可以是本地路径,也可以是在线路径
};
},
mounted: {
this.getTitlePdfurl()
},
methods: {
getTitlePdfurl(){
this.pdfSrc = pdf.createLoadingTask({
url: this.pdfUrl},CMapReaderFactory);//解决中文乱码问题
this.pdfSrc.promise.then(pdf => {
this.numPages = pdf.numPages
}).catch(err => {
console.error('pdf 加载失败', err)
})
},
}
};
5、想一页一页的翻加载
<div class="content">
<pdf
ref="pdf"
:page="numPages"
:src="pdfUrl"
:rotate="pageRotate"
@progress="loadedRatio = $event"
@page-loaded="pageLoaded($event)"
@num-pages="pageTotalNum=$event"
@error="pdfError($event)"
@link-clicked="page = $event"
></pdf>
<div class="options-btn">
<el-button @click="prePage" > 上一页</el-button>
<el-button @click="nextPage" > 下一页</el-button>
<el-button @click="clockwise" > 顺时针</el-button>
<el-button @click="antiClockwise" > 逆时针</el-button>
</div>
</div>
import pdf from 'vue-pdf'
export default {
components: {
pdf },
data() {
return {
numPages: 1, // 当前页
pdfUrl: "http://....xx.pdf", //
pageRotate: 0, // 旋转的角度
loadedRatio: 0, // 加载进度
curnumPages: 0, // 加载时的回调当前页
pageTotalNum: 1, // 总的页数
};
},
methods: {
prePage() {
// 上一页
var page = this.numPages
page = page > 1 ? page - 1 : this.pageTotalNum
this.numPages = page
},
nextPage() {
//下一页
let page = this.numPages
page = page < this.pageTotalNum ? page + 1 : 1
this.numPages = page
},
clockwise() {
// 页面顺时针翻转90度。
this.pageRotate += 90
},
antiClockwise() {
// 页面逆时针翻转90度。
this.pageRotate -= 90
},
pageLoaded(e) {
// 加载时的回调
this.curnumPages = e
},
pdfError(error) {
// 错误的时候回调
console.error(error)
},
}
};
写在最后:
以上就是一般使用vue-pdf的一些使用写法,前端小弟正在努力记录ing~