• mammoth预览库的安装和使用
  • 发布于 1天前
  • 20 热度
    0 评论
与其说 mammoth 是预览库,不如说它是一个“语义提取工具”。它的目标不是还原 Word 的视觉样式,而是转换为干净的 HTML 结构,非常适合内容系统或富文本编辑器的输入源。

安装方式:
npm install mammoth
转换文档
import mammoth from 'mammoth';
// 堆代码 duidaima.com
mammoth.convertToHtml({ arrayBuffer: docxBuffer }).then(result => {
  document.getElementById('content').innerHTML = result.value;
});
样式映射:
可以自定义 Word 样式到 HTML 标签的映射:
styleMap: [
  "p[style-name='注意事项'] => div.warning",
  "p[style-name='提示'] => div.tip"
]
图片优化技巧:
默认图片是 base64 内嵌,可以手动改成 Blob URL:
convertImage: mammoth.images.imgElement(image =>
  image.readAsArrayBuffer().then(buffer => {
    const blob = new Blob([buffer], { type: image.contentType });
    return { src: URL.createObjectURL(blob) };
  })
)
这样可以避免 HTML 变得臃肿,提升页面加载性能。

实现内容管理系统中的 Word 内容提取器例子
<!-- 示例二:提取 Word 内容为 HTML(使用 mammoth) -->
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>mammoth 内容提取器</title>
<style>
    #content {
      border: 1px solid #aaa;
      padding: 20px;
      min-height: 200px;
    }
  </style>
</head>
<body>
<h2>📄 Word 内容提取(mammoth)</h2>
<input type="file" id="fileInput" accept=".docx" />
<div id="content">请上传 .docx 文件</div>

<script src="https://cdn.jsdelivr.net/npm/mammoth@1.9.1/mammoth.browser.min.js"></script>
<script>
    document.getElementById('fileInput').addEventListener('change', function () {
      const file = this.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.readAsArrayBuffer(file);

      reader.onload = function () {
        const arrayBuffer = reader.result;
        const options = {
          styleMap: [
            "p[style-name='注意事项'] => div.warning",
            "p[style-name='标题 1'] => h1"
          ],
          convertImage: mammoth.images.imgElement(function (image) {
            return image.readAsArrayBuffer().then(function (buffer) {
              const blob = new Blob([buffer], { type: image.contentType });
              return {
                src: URL.createObjectURL(blob),
                alt: "图片"
              };
            });
          })
        };

        mammoth.convertToHtml({ arrayBuffer }, options).then(function (result) {
          document.getElementById('content').innerHTML = result.value;
          console.log('✅ 提取成功', result.messages);
        }).catch(function (err) {
          console.error('❌ 提取失败', err);
        });
      };
    });
  </script>
</body>
</html>
更多 mammoth 高级配置参数汇总
参数名 类型 默认值 说明
styleMap string / array Word 样式到 HTML 的映射规则
includeEmbeddedStyleMap boolean true 是否包含文档内嵌样式映射
includeDefaultStyleMap boolean true 是否结合默认样式映射一起生效
convertImage function true 图片处理(默认 base64,可自定义为 Blob URL)
ignoreEmptyParagraphs boolean true 是否忽略空段落
idPrefix string "" 所有生成 ID 的前缀(如脚注)
transformDocument function 在 HTML 渲染前修改文档结构

用户评论