Vue Word プレビュー用の mammoth.js

1. Mammoth.js の概要

  Mammoth は、Microsoft Word で作成されたドキュメントなどの .docx ドキュメントを HTML に変換するように設計されています。Mammoth の目標は、ドキュメント内のセマンティック情報を使用し、その他の詳細を無視して、シンプルでクリーンな HTML を生成することです。たとえば、Mammoth は、見出しのスタイル (フォント、テキスト サイズ、色など) を正確に複製するのではなく、見出し 1 スタイルが適用されている段落を h1 要素に変換します。

2. Mammoth.js の例

バージョン: v1.4.8
Github: https://github.com/mwilliamson/mammoth.js
NPM: https://www.npmjs.com/package/mammoth
CDN: https://cdn.jsdelivr.net/npm/mammoth @1.4.8/mammoth.browser.min.js

3. インストール

npm install --save mammoth

4. コードの説明

<template>
  <div class="word-wrap">
    <div id="wordView" v-html="wordText" />
  </div>
</template>

<script>
// docx文档预览(只能转换.docx文档,转换过程中复杂样式被忽,居中、首行缩进等)
import mammoth from "mammoth";
export default {
    
    
  data() {
    
    
    return {
    
    
      wordText: "",
      wordURL: 'vue-mobile/media/word.docx'//文件地址
    };
  },
  created() {
    
    
    this.getWordText();
  },
  methods: {
    
    
    getWordText() {
    
    
      const xhr = new XMLHttpRequest();
      xhr.open("get", this.wordURL, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = () => {
    
    
        if (xhr.status == 200) {
    
    
          mammoth.convertToHtml({
    
     arrayBuffer: new Uint8Array(xhr.response) }).then((resultObject) => {
    
    
            this.$nextTick(() => {
    
    
              this.wordText = resultObject.value;
            });
          });
        }
      };
      xhr.send();
    }
  },
};
</script>

<style lang="less">
.word-wrap {
    
    
  padding: 15px;
  img {
    
    
    width: 100%;
  }
}
</style>

おすすめ

転載: blog.csdn.net/qq_42697806/article/details/125423742