1

一、安装mammoth.js
cnpm 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",


张旭超
1.4k 声望222 粉丝

精通 html+div+css jquery, vue, angularjs, angular2, angular4, ionic, ionic2