本文共 3126 字,大约阅读时间需要 10 分钟。
近期vue移动端项目中遇到了页面内,嵌套展示pdf内容。实现方法很多种,可以用iframe嵌套,但不利于引擎优化seo。所以在网上找到了vue-pdf这个插件,这个插件非常好用,其中封装的方法也很多,属性能进行功能扩展。
接下来开始使用
npm install --save vue-pdf
注意: 1、通过 import pdf from 'vue-pdf' 进行引入,components:{ pdf }进行注册
2、可能存在跨域问题,这里的src并不能实现jsonp的功能。(这里需要后端配合处理,或者自己写个代理服务器)
:src String/Object pdf的链接,可以是相对、绝对地址或者是一个pdf的加载任务
:page Number-default:1 需要展示pdf的第几页;
:rotate Number-default:0 pdf的旋转角度,‘90’的倍数才有效;
@password updatePassword,reason updatePassword:函数提示需要输入的密码;
reason:提示('NEED_PASSWORD' or 'INCORRECT_PASSWORD');
@progress Number pdf的页面的加载进度,Rang[0,1];
@page-loaded Number pdf某个页面加载成功回调,number为页面索引值;
@num-pages Number 监听pdf加载,获取pdf的页数;
@error Object pdf加载失败回调;
@link-clicked Number 单机内部链接时触发;
print(dpi,pageList)
调用浏览器打印功能;
createLoadingTask(src)
这个方法创建一个当前pdf的加载任务,可以作为:src使用或者公开的获取当前pdf的页面总数;
由于pdf文档可能有很多页,解析时不会当做一张大图进行处理,默认只会展示第一页内容,想要全部查看需要进行特殊处理
import pdf from "vue-pdf";export default { name: "inspectionPresentation", components: { pdf }, data() { return { currentPage: 0, // pdf文件页码 pageCount: 0, // pdf文件总页数 path: this.$route.params.path, scale: 100, //放大系数 idx: -1, clauseTitle: "", loadedRatio: 0 }; }, methods{ // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页 changePdfPage(val) { if(val === 0 && this.currentPage > 1) { this.currentPage--; } if(val === 1 && this.currentPage < this.pageCount) { this.currentPage++; } }, goBack() { this.$router.go(-1); }, // pdf加载时 loadPdfHandler(e) { this.currentPage = 1; // 加载的时候先加载第一页 }, //放大 scaleD() { this.scale += 5; // this.$refs.wrapper.$el.style.transform = "scale(" + this.scale + ")"; this.$refs.wrapper.$el.style.width = parseInt(this.scale) + "%"; }, //缩小 scaleX() { if(this.scale == 100) { return; } this.scale += -5; this.$refs.wrapper.$el.style.width = parseInt(this.scale) + "%"; // this.$refs.wrapper.$el.style.transform = "scale(" + this.scale + ")"; }, }翻页缩小:
这里写法注意点:
网上大部分写法是this.pdfSrc.then(),这种写法是不正确的,会报this.pdfSrc.then is not a function 错误
正确写法: this.pdfSrc = pdf.createLoadingTask(this.pdfSrc) this.pdfSrc.promise.then(pdf => { this.numPages = pdf.numPages })
import pdf from 'vue-pdf'components: { pdf}previewPdf(url){ this.pdfSrc=url this.pdfSrc = pdf.createLoadingTask(this.pdfSrc) this.pdfSrc.promise.then(pdf => { this.numPages = pdf.numPages }) },
转载地址:http://jgywk.baihongyu.com/