vue-office-preview-lite
v0.0.4
Published
preview office file in vue , with out compile office lib
Downloads
39
Maintainers
Readme
Vue Office 文件预览组件
一个基于 Vue 2 的 Office 文件在线预览组件,支持 PDF、Word、Excel、PowerPoint 等常见办公文档的在线预览。
目标
@vue-office是一个非常方便的文件预览组件,但是依赖也很大,如果直接在项目中依赖,则增加了很多额外依赖,相对应带来的问题:
- 浏览器加载需要优化,如何分包,如何懒加载
webpack或vite需要配置对应的文件,相对会降低开发时的构建工具的处理速度
解决方案
采用 iframe 隔离方案:
- 将
@vue-office的代码编译到 iframe 中,打包到office-preview目录下 vue组件通过iframe和office-preview下的代码交互- 使用
copy-webpack-plugin或vite-plugin-static-copy实现开发时动态代理iframe
架构设计
graph TD
A[Vue 主应用] -->|postMessage| B[iframe 容器]
B -->|加载| C[office-preview 应用]
C -->|文件类型判断| D[文件类型判断模块]
D -->|PDF| E[PDF 预览]
D -->|Word| F[Word 预览]
D -->|Excel| G[Excel 预览]
D -->|PPT| H[PPT 预览]
subgraph 主应用
A
end
subgraph 预览应用
B
C
D
E
F
G
H
end核心模块说明
主应用模块
- Vue 组件封装
- iframe 通信管理
- 文件 URL 处理
预览应用模块
- 文件类型判断
- 预览组件加载
- 文件内容渲染
通信模块
- postMessage 消息处理
- 状态同步
- 错误处理
功能特点
- 📄 支持多种文件格式预览
- PDF 文件(.pdf)
- Word 文档(.doc, .docx)
- Excel 表格(.xls, .xlsx)
- PowerPoint 演示文稿(.ppt, .pptx)
- 🔍 智能文件类型识别
- 通过文件扩展名快速判断
- 通过文件内容(magic number)精确判断
- 支持新旧版 Office 文件格式
技术栈
- Vue 2
- TypeScript
- vue-office 系列组件
- @vue-office/pdf
- @vue-office/docx
- @vue-office/excel
- @vue-office/pptx
安装使用
- 安装依赖
npm install vue-office-preview-lite- 引入组件
<template>
<file-preview :fileUrl="fileUrl" />
</template>
<script setup>
import FilePreview from 'vue-office-preview-lite'
</script>组件属性
| 属性名 | 类型 | 必填 | 默认值 | 说明 | |--------|--------|------|--------|----------------| | fileUrl | String | 是 | - | 文件访问地址 | | fileType | String | 否 | null | 文件类型,可选值:'pdf'、'word'、'excel'、'ppt' | | frameUrl | String | 否 | ./office-preview/index.html | 预览 iframe 的地址 |
文件类型判断逻辑
扩展名判断(快速)
- 通过文件 URL 后缀快速判断文件类型
- 支持常见文件扩展名
内容判断(精确)
- PDF:
%PDF文件头 - DOCX/XLSX/PPTX: ZIP 文件头 + 内容类型判断
- 旧版 Office 文件: 复合文档格式判断
- PDF:
示例代码
<template>
<div class="preview-container">
<file-preview
:fileUrl="fileUrl"
:fileType="fileType"
frameUrl="./office-preview/index.html"
/>
</div>
</template>
<script setup>
import { ref } from 'vue'
import FilePreview from 'vue-office-preview-lite'
const fileUrl = ref('https://example.com/document.pdf')
const fileType = ref('pdf') // 可选,不传则自动判断
</script>
<style scoped>
.preview-container {
width: 100%;
height: 800px;
}
</style>