项目中遇到一个需要在线预览pdf以及图片功能,
在网上找了很多插件发现都达不到理想需求,所有自己通过iframe标签自己封装了一个内嵌pdf页面
通过判断当前文件流的后缀名来区分是pdf还是图片或者是其他类文档
组件如下,需要的自取直接可用
<template>
<div>
<el-dialog :title="pdfDialog.title" :visible.sync="pdfDialog.previewShow" append-to-body width="60%"
@close="closeDialog(false)" :close-on-click-modal="false">
<!-- PDF显示的地方 -->
<iframe ref="pdf" v-if="showPDF" :src="previewUrl" width="100%"></iframe>
<div style="margin:0 auto;height: 300px; overflow: auto;min-height: 400px;" v-else v-loading="loading">
<!-- <div style="margin:0 auto" v-else> -->
<!-- <img :src="previewUrl" style="width:100%" alt=""> -->
<el-image style="width:100%" :src="previewUrl">
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
</div>
<span slot="footer" class="dialog-footer">
<el-button type="primary" v-if="!showPDF" size="small" @click="handleDownload">下载图片</el-button>
<el-button type="primary" plain @click="closeDialog(false)" size="small">关 闭</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import { online } from '@/api/system/user.js'
export default {
props: {
pdfDialog: {
typeOf: Object,
default: () => {
return {}
}
}
},
components: {
},
data() {
return {
previewShow: false,
previewUrl: "",
showPDF: false,
imgType: ["png", "jpg", "jpeg", 'gif'],
loading:false
};
},
methods: {
// 直接传入一个地址
closeDialog(refreshParent) {
this.previewShow = false;
// 通知父组件销毁dialog,刷新父組件
this.$emit("onDialogDestory", refreshParent);
},
handlePreview() {
let a = this.imgType.indexOf(this.pdfDialog.type)
// 如果是pdf文件
if (this.pdfDialog.type === 'pdf') {
this.pdfOrImgShow(this.pdfDialog.id, true)
} else if (a !== -1) {
this.pdfOrImgShow(this.pdfDialog.id, false)
} else {
this.closeDialog()
}
},
pdfOrImgShow(fileId, type) {
this.loading = true
online(fileId).then(res => {
if (!type) {
this.previewUrl = window.URL.createObjectURL(res)
} else {
this.previewUrl = window.URL.createObjectURL(new Blob([res], { type: "application/pdf" }))
this.$nextTick(() => {
this.$refs.pdf.height = document.documentElement.clientHeight;
})
}
}).finally(()=>{
this.loading = false
})
},
handleDownload(){
console.log(123);
this.download("/file/download/" + this.pdfDialog.id, null, this.pdfDialog.title);
},
},
computed: {
},
watch: {
"pdfDialog.previewShow": {
handler(newVal, oldVal) {
this.previewShow = newVal;
this.handlePreview()
},
immediate: true,
},
"pdfDialog.type": {
handler(newVal, oldVal) {
// console.log(newVal);
if (newVal === 'pdf') {
this.showPDF = true
} else {
this.showPDF = false
}
// this.previewShow = newVal;
},
immediate: true,
}
},
created() {
},
mounted() {
},
};
</script>
<style scoped lang="scss">
::v-deep.el-dialog__body {
overflow: auto;
}
</style>