1. Introducción a Mammoth.js
Mammoth está diseñado para convertir documentos .docx, como los creados por Microsoft Word, y convertirlos a HTML. El objetivo de Mammoth es generar HTML simple y limpio utilizando la información semántica del documento e ignorando otros detalles. Por ejemplo, Mammoth convertirá cualquier párrafo al que se le aplique el estilo Título 1 en un elemento h1, en lugar de intentar replicar exactamente el estilo del título (fuente, tamaño del texto, color, etc.).
2. Ejemplo de Mammoth.js
Versión: 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. Instalación
npm install --save mammoth
4. Descripción del código
<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>