第一步将后端返回的base64转化为URL地址
// 将base64文件流转换为url地址
let code = res.body.imgObject.content.substring(
res.body.imgObject.content.indexOf(",") + 1
);
let bstr = atob(code);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
//确定解析格式
let blob = new Blob([u8arr], {
type: "application/pdf;chartset=UTF-8",
});
let url = window.URL.createObjectURL(blob);
第二步 下载插件进行预览,页面进行应用
<template>
<pdf
v-for="currentPage in numPages"
:key="currentPage"
:src="pdfsrc"
:page="currentPage"
@loaded="loadPdfHandler"
></pdf>
</template>
<script>
import pdf from "vue-pdf";
data() {
return {
pdfsrc: "",
pageCount: 1, // pdf文件总页数
currentPage: 1, // pdf文件页码
}
}
components: { pdf },
methods:{
fn() {
// 发请求之后将base64文件流转换为url地址
let code = res.body.imgObject.content.substring(
res.body.imgObject.content.indexOf(",") + 1
);
let bstr = atob(code);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
//确定解析格式
let blob = new Blob([u8arr], {
type: "application/pdf;chartset=UTF-8",
});
let url = window.URL.createObjectURL(blob);
this.pdfsrc = url;
this.pdfsrc = pdf.createLoadingTask({ url: this.pdfsrc });
this.loadPdfHandler();
},
loadPdfHandler() {
this.pdfsrc.promise
.then((pdf) => {
// 获取pdf文件相关信息,页码等
this.numPages = pdf.numPages;
})
.catch((err) => {
// console.log(err, "打印失败");
});
this.currentPage = 1; // 加载的时候先加载第一页
// 强制刷新
this.$forceUpdate();
},
}
</script>