vue实现预览word文档
使用mammoth.js库解析Word文档
mammoth.js是一个流行的JavaScript库,专门用于将.docx文件转换为HTML。它可以直接在浏览器端运行,无需后端支持。
安装mammoth.js:
npm install mammoth
组件中使用:
import mammoth from "mammoth";
methods: {
async handleFileUpload(event) {
const file = event.target.files[0];
const arrayBuffer = await file.arrayBuffer();
mammoth.extractRawText({arrayBuffer})
.then(result => {
this.previewContent = result.value;
})
.catch(err => console.error(err));
}
}
使用docx-preview库渲染文档
docx-preview提供更接近原生Word的渲染效果,支持样式保留。
安装:
npm install docx-preview
使用示例:
import { renderAsync } from 'docx-preview';
methods: {
async renderDocx(file) {
const container = this.$refs.previewContainer;
try {
await renderAsync(file, container);
} catch (error) {
console.error('渲染失败:', error);
}
}
}
后端转换方案(Node.js)
对于需要更复杂处理的场景,可以使用后端转换:
const express = require('express');
const fileUpload = require('express-fileupload');
const mammoth = require('mammoth');
app.post('/convert', async (req, res) => {
const result = await mammoth.convertToHtml({
buffer: req.files.file.data
});
res.send(result.value);
});
纯前端实现注意事项
- 大文件处理需要分片读取
- 样式支持有限,复杂格式可能丢失
- 移动端兼容性需要测试
- 考虑添加加载状态提示
完整组件示例
<template>
<div>
<input type="file" @change="handleFileChange" accept=".docx"/>
<div ref="previewContainer" class="preview-area"></div>
</div>
</template>
<script>
import { renderAsync } from 'docx-preview';
export default {
methods: {
async handleFileChange(event) {
const file = event.target.files[0];
if (!file) return;
try {
await renderAsync(file, this.$refs.previewContainer, {
className: "docx",
style: "height: 100vh"
});
} catch (error) {
console.error('预览失败:', error);
}
}
}
}
</script>






