一、安装mammoth.jscnpm i mammoth --save-dev
二、需要展示word文件的地方引入。import mammoth from "mammoth";
三、使用完整代码
<template>
<div class="word-wrap" v-loading="loading">
<div id="wordView" v-html="wordText"></div>
</div>
</template>
<script setup>
import mammoth from "mammoth";
const loading = ref(false);
const wordText = ref("");
const wordURL = new URL("@/assets/fonts/agree.docx", import.meta.url).href; //文件地址
const getWordText = () => {
loading.value = true;
const xhr = new XMLHttpRequest();
xhr.open("get", wordURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = () => {
if (xhr.status == 200) {
mammoth
.convertToHtml(
{ arrayBuffer: new Uint8Array(xhr.response) },
{ includeDefaultStyleMap: true }
)
.then((resultObject) => {
nextTick(() => {
// 这里可以局部修改获取html的样式和内容,resultObject.value就是word转成html的完整代码,如果不需要修改直接赋值给wordText.value 即可。
resultObject.value = resultObject.value.replace(
"<p><strong>引言</strong></p>",
"<p style='text-align:center;color: rgba(0, 0, 0, 0.65);margin-bottom: 40px'>引言</p>"
);
wordText.value =
"<div style='font-size: 16px; line-height: 28px'>" +
resultObject.value +
"</div>";
});
loading.value = false;
})
.catch((err) => {
loading.value = false;
});
}
};
xhr.send();
};
onMounted(() => {
getWordText();
});
</script>
<style scoped lang="scss">
.word-wrap {
padding: 80px;
width: 800px;
margin: 0 auto;
.header {
color: #000;
text-align: center;
font-size: 40px;
font-style: normal;
font-weight: 500;
line-height: 40px; /* 100% */
}
}
</style>
四、安装版本及完整配置
https://gitcode.com/gh_mirrors/ma/mammoth.js/overview?utm_sou..."mammoth": "^1.8.0",
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。