vue实现word预览
Vue 中实现 Word 文档预览的方法
使用 mammoth.js 解析 .docx 文件
安装 mammoth.js 库:
npm install mammoth
在 Vue 组件中解析并渲染 .docx 文件:
<template>
<div v-html="htmlContent"></div>
</template>
<script>
import mammoth from "mammoth";
export default {
data() {
return {
htmlContent: ""
};
},
methods: {
async previewWord(file) {
const arrayBuffer = await file.arrayBuffer();
const result = await mammoth.convertToHtml({ arrayBuffer });
this.htmlContent = result.value;
}
}
};
</script>
使用 docx-preview 库实现原生样式预览
安装 docx-preview:
npm install docx-preview
在 Vue 组件中使用:
<template>
<div ref="previewContainer"></div>
<input type="file" @change="handleFileChange" accept=".docx" />
</template>
<script>
import { renderAsync } from "docx-preview";
export default {
methods: {
async handleFileChange(e) {
const file = e.target.files[0];
if (!file) return;
const container = this.$refs.previewContainer;
const arrayBuffer = await file.arrayBuffer();
await renderAsync(arrayBuffer, container);
}
}
};
</script>
转换为 PDF 后预览(需后端配合)
安装 pdf-lib 用于前端 PDF 操作(可选):
npm install pdf-lib
通过接口将 Word 转换为 PDF:
async function convertToPdf(file) {
const formData = new FormData();
formData.append("file", file);
const response = await fetch("/api/convert-to-pdf", {
method: "POST",
body: formData
});
return await response.blob();
}
使用 Office 365 在线预览(商业方案)
嵌入 Office Online 预览功能:

<template>
<iframe
:src="`https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`"
width="100%"
height="600px"
frameborder="0"
></iframe>
</template>
<script>
export default {
computed: {
encodedUrl() {
return encodeURIComponent("https://your-domain.com/path/to/file.docx");
}
}
};
</script>
注意事项
.doc格式(Word 97-2003)需要先转换为.docx才能被大多数前端库处理- 复杂格式(如表格、图表)的渲染可能在不同方案中存在差异
- 大文件建议采用分片上传或后端转换方案
- 敏感文档建议使用后端转换方案避免前端暴露内容
以上方案可根据实际需求选择,纯前端方案适合简单文档预览,复杂场景建议结合后端处理。






