vue 实现word文档预览
Vue 实现 Word 文档预览的方法
使用 mammoth.js 库解析 .docx 文件
安装 mammoth.js:
npm install mammoth
在 Vue 组件中使用:
<template>
<div>
<input type="file" @change="handleFileUpload" accept=".docx" />
<div v-html="htmlContent"></div>
</div>
</template>
<script>
import mammoth from "mammoth";
export default {
data() {
return {
htmlContent: "",
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
mammoth
.extractRawText({ arrayBuffer: e.target.result })
.then((result) => {
this.htmlContent = result.value;
});
};
reader.readAsArrayBuffer(file);
},
},
};
</script>
使用 docx-preview 库渲染 .docx 文件
安装 docx-preview:
npm install docx-preview
在 Vue 组件中使用:
<template>
<div>
<input type="file" @change="handleFileUpload" accept=".docx" />
<div ref="docxContainer"></div>
</div>
</template>
<script>
import { renderAsync } from "docx-preview";
export default {
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const container = this.$refs.docxContainer;
renderAsync(file, container);
},
},
};
</script>
使用 Office Web Viewer 在线预览
直接嵌入 Office Web Viewer 的 iframe:
<template>
<iframe
:src="`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
fileUrl
)}`"
width="100%"
height="600px"
frameborder="0"
></iframe>
</template>
<script>
export default {
data() {
return {
fileUrl: "https://example.com/document.docx",
};
},
};
</script>
使用 pdf-lib 转换为 PDF 后预览
安装 pdf-lib 和 docx:
npm install pdf-lib docx
转换并预览:
<template>
<div>
<input type="file" @change="handleFileUpload" accept=".docx" />
<iframe v-if="pdfUrl" :src="pdfUrl" width="100%" height="600px"></iframe>
</div>
</template>
<script>
import { Document, Packer } from "docx";
import { PDFDocument } from "pdf-lib";
export default {
data() {
return {
pdfUrl: "",
};
},
methods: {
async handleFileUpload(event) {
const file = event.target.files[0];
const arrayBuffer = await file.arrayBuffer();
const docx = await Document.load(arrayBuffer);
const pdfDoc = await PDFDocument.create();
// 转换逻辑(示例,需根据实际需求实现)
const pdfBytes = await pdfDoc.save();
const blob = new Blob([pdfBytes], { type: "application/pdf" });
this.pdfUrl = URL.createObjectURL(blob);
},
},
};
</script>
注意事项
.doc文件(旧版 Word 格式)可能需要使用antiword或其他工具转换,浏览器端支持有限。- 大文件处理建议使用后端服务转换后返回预览链接。
- 敏感文档避免直接前端解析,可能存在安全隐患。







