vue 将base64 的文件流转换成pdf 预览并下载
<el-tooltip placement="right-start" effect="light"><divslot="content"class="content"@click="downFile(photosList[index])">下载...
·
pdf显示布局,鼠标滑过pdf显示下载按钮
<el-tooltip placement="right-start" effect="light">
<div
slot="content"
class="content"
@click="downFile(photosList[index])"
>
下载
</div>
<div
@click="showPdfClick(index)"
class="pdfBox"
>
<Pdf :pdfSrc="photosList[index]"></Pdf>
</div>
</el-tooltip>
// pdf预览布局
<div v-if="showPdf" class="largePhotoBox">
<div style="width: 80%; margin-left: 10%">
<span @click="showPdf = false">x</span>
<Pdf :pdfSrc="photosList[photoIndex]"></Pdf>
</div>
</div>
这里是预览以及下载代码的一部分,传的base64根据自己需求直接在方法里面传值
data(){
return{
photoIndex: "",
showPdf
}
}
PDF的下载功能,这里是通过js中a标签实现的
// 下载
downFile(perfix64) {
this.downloadFile( this.realName,perfix64);
},
// 这里的filename自己定义
downloadFile(fileName, content) {
let aLink = document.createElement("a");
let blob = this.base64ToBlob(content);
let evt = document.createEvent("HTMLEvents");
console.log("点击下载", evt);
evt.initEvent("click", true, true);
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
},
// base64转blob
base64ToBlob(code) {
let parts = code.split(";base64,");
let contentType = parts[0].split(":")[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
},
// 预览显示pdf
showPdfClick(index) {
this.photoIndex = index;
this.showPdf = true;
},
pdf预览css
.largePhotoBox {
width: 100%;
height: 100%;
overflow: auto;
background: rgba(0, 0, 0, 0.6);
position: fixed;
top: 0;
left: 0;
z-index: 999;
&::-webkit-scrollbar {
display: none;
}
img {
width: 50%;
margin-left: 25%;
margin-top: 50px;
}
span {
font-size: 30px;
position: fixed;
color: #fff;
top: 30px;
right: 50px;
}
}
PDF的预览功能,这里单独写了个子组件,直接复制,很简单
<template>
<div>
<pdf v-for="i in numPages" :key="i" :page="i" :src="src"></pdf>
</div>
</template>
<script>
import pdf from "vue-pdf";
export default {
components: {
pdf,
},
props: {
pdfSrc: String,
},
data() {
return {
numPages: null,
src: "",
};
},
mounted() {
this.getNumPages(); // base64pdf 文件的预览
},
methods: {
// #计算pdf页码总数
getNumPages() {
let perfix64;
perfix64 =
"data:application/pdf;base64," + this.pdfSrc;
let CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/cmaps/";
this.src = pdf.createLoadingTask({
url: perfix64,
withCredentials: false,
cMapUrl: CMAP_URL,
cMapPacked: true,
});
this.src.promise
.then((pdf) => {
this.numPages = pdf.numPages;
console.log(this.numPages);
})
.catch((err) => {
console.error("pdf 加载失败", err);
});
},
}
};
</script>
注意
这个代码只适用于返回的base64只是pdf文件的base64码,如果返回的base64码的类型不确定,记得要加判断,传值的时候可以把想要传的base64码使用split切割传值
更多推荐
所有评论(0)