licp
2024-04-03 ebafa0caac76450802535f0952457e86c4ea2962
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { convertToHtml } from 'mammoth';
import Vue from 'vue'
 
export default {
  async convertFileToHtml(url) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', Vue.prototype.javaApi+url, true);//获取文件流的接口
    xhr.send();
    xhr.responseType = "blob";//不能漏
    let xhrPromise = new Promise((resolve, reject) => {
      xhr.onload = async function () {
        if (this.status === 200) {
          // 返回的文件流,转换成blob对象
          var blob = new Blob([this.response],{ type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
          // 使用mammoth将Word转换为HTML
          let reader = new FileReader();
          reader.readAsArrayBuffer(blob);
          let htmlContentPromise = new Promise((resolve, reject) => {
            reader.onload = async function () {
              var arrayBuffer = xhr.response; //arrayBuffer
              const result = await convertToHtml({ arrayBuffer: arrayBuffer })
              let html = result.value.replace(//g, '')
              .replace('<h1>', '<h1 style="text-align: center;">')
              .replace(/<table>/g, '<table style="border-collapse: collapse;border: 1px solid #000;">')
              .replace(/<tr>/g, '<tr style="height: 30px;">')
              .replace(/<td>/g, '<td style="border: 1px solid #000;">')
              .replace(/<p>/g, '<p style="text-indent: 2em;">')
              .replace(/<a [^>]*>/g, "")
              .replace(/<\/a>/g, "")
              // .replace(/em/g, "cm");
              resolve(html)
            };
          })
          resolve(await htmlContentPromise)
        }
 
      }
    })
    return await xhrPromise
  },
};