最近项目增加docx、excel、pptx、pdf预览的需求,简单记录一下实现步骤
参考的是vue-office
1.安装依赖
npm install @vue-office/pptx vue-demi@0.14.6
我的node版本是v18.20.3,vue的版本3.2.13
"@vue-office/docx": "^1.6.2",
"@vue-office/excel": "^1.7.11",
"@vue-office/pdf": "^2.0.2",
"@vue-office/pptx": "^0.0.2",
2.我的写法是每个类型分别封装了一个vue组件,这里我以pptx为例:
我的需求时根据接口返回的流去渲染对应的类型文件,github的demo中pptx显示的时候样式是一个固定的宽高,这里我在页面上自己修改了需要的样式
<template>
<div>
<el-dialog v-model="state.dialogVisible" top="10" width="100vw" @close="closePdf">
<vue-office-pptx :src="state.pptx" style="height: 100vh;" @rendered="renderedHandler" @error="errorHandler" />
</el-dialog>
</div>
</template>
<script setup>
import { inject, onMounted, reactive, watch } from "vue";
//引入VueOfficeExcel组件
//import VueOfficeExcel from '@vue-office/excel'
//引入VueOfficePdf组件
// import VueOfficePdf from '@vue-office/pdf'
//引入VueOfficeDocx组件
//import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
// import '@vue-office/docx/lib/index.css'
//引入VueOfficePptx 组件
import VueOfficePptx from '@vue-office/pptx'
const emit = defineEmits(['closeDocx'])
const GlobalUrl = inject('GlobalUrl');
const props = defineProps({
model: {
type: Boolean,
default: false
},
viewItem: {
typr: Boolean,
default: () => { }
}
})
const state = reactive({
loading: true,
pptx:"",
fileList: [],
dialogVisible: false
})
watch(
() => [props.model],
(newVal) => {
state.dialogVisible = newVal[0]
if(newVal[0]){
beforeUpload()
}
}
)
const closePdf = () => {
emit("closeDocx")
}
const renderedHandler = () => {
state.loading = false;
console.log("渲染完成")
}
const beforeUpload = () => {
const loadingInstance = ElLoading.service({
lock: true,
text: 'Loading',
background: 'rgba(0, 0, 0, 0.7)',
})
fetch(GlobalUrl.DATA_LIST.getFileByPath(props.viewItem.filePath), {
method: 'get',
}).then(res => {
res.arrayBuffer().then(res => {
loadingInstance.close()
state.pptx= res
})
})
}
const errorHandler = () => {
state.loading = false;
console.log("渲染失败")
}
</script>
<style >
.pptx-preview-wrapper{
width: 100% !important;
height: 100% !important;
}
</style>