1. 前言
vue-pdf是对pdf.js的封装使用起来更加简单
2. 安装
npm install --save vue-pdf
3. 一个简单的示例
<template>
<pdf src="./static/relativity.pdf"></pdf>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: {
pdf
}
}
4. API
属性名 | 类型 | 默认值 | 说明 |
---|---|---|---|
src | String / Object | '' | pdf文件的网址 |
page | Number | 1 | 要显示的页码 |
rotate | Number | 0 | 页面旋转度数,只有90的倍数有效。 |
事件名 | 事件描述 |
---|---|
password (updatePassword, reason) | updatePassword:用pdf密码调用的功能 reason:此功能称为“ NEED_PASSWORD”或“ INCORRECT_PASSWORD”的原因 |
progress | 文件载入进度 |
loaded | 加载文档时触发。 |
page-loaded | 加载页面时触发。 |
num-pages | pdf的总页数。 |
error | 发生错误时触发。 |
5. 封装pdf预览组件
<template>
<div>
<div style="width: 100%">
<div v-if="loadedRatio > 0 && loadedRatio < 1" style="background-color: green; color: white; text-align: center" :style="{ width: loadedRatio * 100 + '%' }">{{ Math.floor(loadedRatio * 100) }}%</div>
<pdf v-if="show" ref="pdf" :src="src" :page="page" :rotate="rotate" @password="password" @progress="loadedRatio = $event" @error="error" @num-pages="numPages = $event" @link-clicked="page = $event"></pdf>
</div>
<div style="text-align:center">
{{page}} / {{numPages}}
</div>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
props:['pdfUrl'],
components: {
pdf
},
data () {
return {
show: true,
src:pdf.createLoadingTask(this.pdfUrl),
loadedRatio: 0,
page: 1,
numPages: 0,
rotate: 0,
}
},
methods: {
prevPage(){
this.page = this.page-1
if(this.page <= 0){
this.page = 1
}
},
nextPage(){
this.page = this.page+1
if(this.page >= this.numPages){
this.page = this.numPages
}
},
password: function(updatePassword, reason) {
updatePassword(prompt('password is "test"'));
},
error: function(err) {
console.log(err);
}
},
mounted(){
this.src.promise.then(pdf => {
this.numPages = pdf.numPages;
});
}
};
</script>
<style lang="less" scoped>
</style>