vue实现预览word
Vue 实现预览 Word 文件
使用 mammoth.js 解析 Word 文档
安装 mammoth.js 依赖:
npm install mammoth
在 Vue 组件中引入并使用:
import mammoth from "mammoth";
methods: {
async previewWord(file) {
const arrayBuffer = await file.arrayBuffer();
const result = await mammoth.extractRawText({ arrayBuffer });
this.previewContent = result.value; // 获取纯文本内容
// 或转换为 HTML
const htmlResult = await mammoth.convertToHtml({ arrayBuffer });
this.previewContent = htmlResult.value;
}
}
使用 Office Online 在线预览
通过嵌入 Microsoft Office Online 的预览功能:

<iframe
:src="`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}`"
width="100%"
height="500px"
frameborder="0">
</iframe>
使用 PDF.js 间接预览(需先转换)
先将 Word 转换为 PDF(后端处理),再用 PDF.js 预览:
import * as pdfjsLib from 'pdfjs-dist';
methods: {
async previewPDF(pdfUrl) {
const loadingTask = pdfjsLib.getDocument(pdfUrl);
const pdf = await loadingTask.promise;
const page = await pdf.getPage(1);
// 渲染逻辑...
}
}
使用 docx-preview 库
专门针对 .docx 的预览库:

npm install docx-preview
实现方式:
import { renderAsync } from "docx-preview";
methods: {
async previewDocx(elementId, file) {
const container = document.getElementById(elementId);
const arrayBuffer = await file.arrayBuffer();
await renderAsync(arrayBuffer, container);
}
}
后端转换方案
通过后端将 Word 转为 HTML/PDF 再返回前端展示:
axios.post('/convert', formData)
.then(response => {
this.previewContent = response.data.html;
});
注意事项
- 纯前端方案对复杂格式(如表格、图片)支持有限
- 大文件建议采用分片加载或后端处理
- 在线预览方案需注意跨域问题
- 二进制文件(.doc)需要特殊处理,建议优先使用 .docx 格式
每种方案适用于不同场景,可根据项目需求选择合适的技术组合。






