vue实现word文档实现预览
使用 docx.js 解析并渲染文档
安装 docx.js 库用于解析 Word 文档内容:
npm install docx
创建解析组件,将 .docx 文件转换为 HTML 结构:
import { Document } from 'docx';
async function parseDocx(file) {
const arrayBuffer = await file.arrayBuffer();
const doc = await Document.load(arrayBuffer);
return doc.render(); // 返回HTML字符串
}
集成 mammoth.js 实现转换
mammoth.js 是专为浏览器设计的.docx转换工具:
npm install mammoth
在 Vue 组件中使用:

import mammoth from 'mammoth';
export default {
methods: {
async previewDocx(file) {
const result = await mammoth.extractRawText({ arrayBuffer: file });
this.content = result.value; // 获取纯文本
// 或使用带样式的HTML
const htmlResult = await mammoth.convertToHtml({ arrayBuffer: file });
this.htmlContent = htmlResult.value;
}
}
}
使用 Office Web 365 在线预览
通过 iframe 嵌入第三方服务实现完整功能预览:
<template>
<iframe
:src="`https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(fileUrl)}`"
frameborder="0"
/>
</template>
需要确保文档 URL 可公开访问,适用于企业级解决方案。

前端直接渲染方案
对于简单的文档展示,使用 FileReader API:
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
// 显示Base64编码内容或文本
};
reader.readAsDataURL(file); // 或 readAsText
样式处理技巧
当渲染 HTML 内容时,添加文档专用样式:
.docx-content {
font-family: "Times New Roman", serif;
line-height: 1.5;
padding: 20px;
}
.docx-content p {
margin-bottom: 12px;
}
.docx-content table {
border-collapse: collapse;
width: 100%;
}
完整组件示例
结合 mammoth.js 的 Vue 组件实现:
<template>
<div>
<input type="file" @change="handleFile" accept=".docx" />
<div v-html="htmlContent" class="docx-preview"></div>
</div>
</template>
<script>
import mammoth from 'mammoth';
export default {
data() {
return {
htmlContent: ''
};
},
methods: {
async handleFile(e) {
const file = e.target.files[0];
const result = await mammoth.convertToHtml({ arrayBuffer: await file.arrayBuffer() });
this.htmlContent = result.value;
}
}
};
</script>
注意:直接使用 v-html 需确保内容安全,避免 XSS 攻击。






