<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>
这里是预览以及下载代码的一部分,传的base64根据自己需求直接在方法里面传值
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的预览功能,这里单独写了个子组件,直接复制,很简单
<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切割传值
|