1. Mammoth——提取word文档
Github: GitHub - mwilliamson/mammoth.js: Convert Word documents (.docx files) to HTML
NPM: mammoth - npm
CDN: https://cdn.jsdelivr.net/npm/mammoth@1.4.8/mammoth.browser.min.js
* 优缺点:
缺点:只能转换.docx文档,转换过程中复杂样式被忽略。(居中、首行缩进、表格背景等)
*API
mammoth.convertToHtml(input, options) :把源文档转换为 HTML 文档
mammoth.convertToMarkdown(input, options) :把源文档转换为 Markdown 文档。
mammoth.extractRawText(input) :提取文档的原始文本。这将忽略文档中的所有格式。每个段落后跟两个换行符。
*使用
1.使用fileReader提取文档内容
2.使用mammoth的API将文档内容提取成html放到页面上
*demo示例
关键代码:
// 结构
<div class="container">
<h1>word转化html</h1>
<input id="document" type="file" />
<div class="row" style="width: 100%;">
<div class="span8">
<div id="output" class="well"></div>
</div>
</div>
</div>
// script
<script src="https://cdn.bootcss.com/mammoth/1.4.8/mammoth.browser.js"></script>
// 逻辑
const data = {
products: '测试项目',
price: "$99",
img: "https://docxtemplater.com/puffin.png"
}
// word转化html
document.getElementById("document")
.addEventListener("change", readFileInputEventAsArrayBuffer, false);
const transformProduct = (dataText) => {
dataText
}
function displayResult(result) {
let html = result.value;
let newHTML = html.replace(//g, '')
.replace('<h1>', '<h1 style="text-align: center;">')
.replace(/<table>/g, '<table style="border-collapse: collapse;">')
.replace(/<tr>/g, '<tr style="height: 30px;">')
.replace(/<td>/g, '<td style="border: 1px solid pink;">')
.replace(/<p>/g, '<p style="text-indent: 2em;">')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/products/g, `${data.products}`)
.replace(/price/g, `${data.price}`);
document.getElementById("output").innerHTML = newHTML;
document.getElementById("content").value = newHTML;
}
function readFileInputEventAsArrayBuffer(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function (loadEvent) {
var arrayBuffer = loadEvent.target.result;//arrayBuffer
mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
.then(displayResult)
.done();
};
reader.readAsArrayBuffer(file);
}
复制 |
参考:【js】Mammoth.js的使用:将.docx 文件转换成HTML_mammoth.converttohtml-CSDN博客