Mammoth.js 展示doc

引入

pnpm install mammoth

使用

import mammoth from "mammoth";

export default {
  name: "DocView",
  data() {
    return {
      docHtml: "",
    };
  },
  mounted() {
    this.initMammoth();
  },
  methods: {
    async initMammoth() {
      try {
        const response = await fetch(`${process.env.BASE_URL}docx.docx`);
        const arrayBuffer = await response.arrayBuffer();
        const result = await mammoth.convertToHtml({
          arrayBuffer,
          styleMap: [
            "p[style-name='Heading 1'] => h1:fresh",
            "p[style-name='Heading 2'] => h2:fresh",
            "p[style-name='Heading 3'] => h3:fresh",
            "r[style-name='Strong'] => strong",
            "r[style-name='Emphasis'] => em",
            "p[style-name='Normal'] => p"
          ],
          includeDefaultStyleMap: true
        });
        this.docHtml = result.value;
      } catch (error) {
        console.error('Error converting docx:', error);
      }
    },
  },
};

注意:

  1. 引入doc文件时

     const response = await fetch(`${process.env.BASE_URL}docx.docx`);
    1. 使fetch 获取文件

    2. 使process.env.BASE_URL 动态获取基础路径,确保在不同国开发环境下都能正确访问doc文件

  2. styleMap includeDefaultStyleMap 映射Word样式


Mammoth.js 展示doc
https://halo.jiangling.site/archives/mammoth
作者
你的降灵
发布于
2025年07月18日
许可协议