vue中预览PDF和下载PDF 完整代码
官网 GitHub - FranckFreiburger/vue-pdf: vue.js pdf viewer
首先下载插件
npm install vue-pdf
<template>
<div class="content">
<div class="pdf-tabbox" v-show="pageTotalNum">
<div class="pdf-tab">
<!-- <el-button type="primary" @click="prePage">上一页</el-button>
<div>{{ pageNum }} /{{ pageTotalNum }}</div>
<el-button type="primary" @click="nextPage">下一页</el-button> -->
<el-button type="primary" plain @click="pdfPrintAll">
在线打印
</el-button>
<el-button type="primary" @click="downLoad">下 载</el-button>
</div>
</div>
<div class="pdf-boxs">
<pdf
class="paf-box"
ref="pdf"
:src="url"
:page="pageNum"
:rotate="pageRotate"
@password="password"
@progress="loadedRatio = $event"
@page-loaded="pageLoaded($event)"
@num-pages="pageTotalNum = $event"
@error="pdfError($event)"
@link-clicked="page = $event"
>
</pdf>
</div>
</div>
</template>
<script>
import pdf from "vue-pdf";
import { ticketDownload, download } from "@/api/examinee";
export default {
data(){
return {
url: "", //文件地址
pdfs: "",
pageNum: 1,
pageTotalNum: 1,
pageRotate: 0,
// 加载进度
loadedRatio: 0,
curPageNum: 0,
userName: "", //考生姓名
};
},
created() {
this.getInfo();
},
methods:{
getInfo() {
var param = {
kcAvtId: this.$route.query.kcAvtId,
};
ticketDownload(param).then((res) => {
if (res.code == 200) {
this.url = res.data.pdfPath;
this.pdfs = res.data.pdfName;
this.userName = res.data.userName;
// this.url = pdf.createLoadingTask(this.url);
// console.log(this.url, "this.url");
}
});
},
//二进制流文件下载
downLoad() {
var param = {
fileName: this.pdfs,
delete: false,
};
download(param).then((res) => {
// if (res.code == 200) {
let pdfUrl = window.URL.createObjectURL(
new Blob([res.data], { type: `application/pdf` })
);
const fname = this.userName + "的准考证.pdf"; // 下载文件的名字
const link = document.createElement("a");
link.href = pdfUrl;
link.setAttribute("download", fname);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
},
prePage() {
var p = this.pageNum;
p = p > 1 ? p - 1 : this.pageTotalNum;
this.pageNum = p;
},
nextPage() {
var p = this.pageNum;
p = p < this.pageTotalNum ? p + 1 : 1;
this.pageNum = p;
},
password(updatePassword, reason) {
updatePassword(prompt('password is "123456"'));
console.log("...reason...");
console.log(reason);
console.log("...reason...");
},
pageLoaded(e) {
this.curPageNum = e;
},
pdfError(error) {
console.error(error);
},
pdfPrintAll() {
this.$refs.pdf.print();
},
pdfPrint() {
this.$refs.pdf.print(100, [1, 2]);
},
}
}
</script>