<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>docx转html</title>
</head>
<body>
<input id="document" type="file" />
<div id="output" class="well"></div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/mammoth/1.4.17/mammoth.browser.min.js"></script>
<script type="text/javascript">
document.getElementById("document").addEventListener("change", readFileInputEventAsArrayBuffer, false);
function displayResult(result) {
let html = result.value;
console.log(html);
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;">');
document.getElementById("output").innerHTML = 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);
}
</script>
<!-- 参考:https://github.com/mwilliamson/mammoth.js/ -->
</html>