1、发现了个更香更简单的方法(IE低版本可能不行)
<iframe src="./test.pdf" frameborder="0" style="width: 100%; height:900px"></iframe>
2、或者可以使用插件vue-pdf,具体页面见下
<template>
<div class="pdfPage">
<el-button-group class="btns">
<el-button type="primary" icon="el-icon-arrow-left" size="mini" @click="prePage">上一页</el-button>
<el-button class='mar-l-5' type="primary" size="mini" @click="nextPage"
>下一页<i class="el-icon-arrow-right el-icon--right"></i
></el-button>
</el-button-group>
<div style="marginTop: 10px; color: #409EFF;text-align:center">{{ pageNum }} / {{ pageTotalNum }}</div>
<pdf :page="pageNum" src="./test.pdf" @progress="loadedRatio = $event" @num-pages="pageTotalNum = $event"></pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
name: 'pdfPreview',
components: {
pdf
},
props: {
// url:{
// type:String
// }
},
data() {
return {
url: '',
pageNum: 1,
pageTotalNum: 1, //# 总页数
loadedRatio: 0 //# 当前页面的加载进度,范围是0-1 ,等于1的时候代表当前页已经完全加载完成了
}
},
methods: {
// getNumPages() {
// let loadingTask = pdf.createLoadingTask(this.url)
// loadingTask.promise
// .then(pdf => {
// this.pageTotalNum = pdf.numPages
// })
// .catch(err => {
// console.error('pdf 加载失败', err)
// })
// },
// 上一页
prePage() {
let page = this.pageNum
page = page > 1 ? page - 1 : this.pageTotalNum
this.pageNum = page
},
// 下一页
nextPage() {
let page = this.pageNum
page = page < this.pageTotalNum ? page + 1 : 1
this.pageNum = page
}
}
}
</script>
<style lang='scss' scoped >
.btns{
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.mar-l-5{
margin-left: 5px;
}
}
</style>
3、后台返回流文件转化为pdf的url,然后用1方法展示即可
const blob = new Blob([res.data], { type: 'application/pdf;charset=UTF-8' });
this.pdfUrl = URL.createObjectURL(blob);
4、流文件下载方式
export function saveStreamFile(res, config) {
//contentType: 'application/vnd.ms-excel;charset=UTF-8' excel
let opt = {
fileName: res.fileName || 'download',
contentType: 'application/zip;charset=UTF-8',
...config
};
const blob = new Blob([res.data], { type: opt.contentType });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `${opt.fileName}${opt.extName ? '.' + opt.extName : ""}`;
a.click();
URL.revokeObjectURL(a.href);
}
//用法
saveStreamFile(res, { contentType: 'application/vnd.ms-excel;charset=UTF-8' })
网友评论