在 Web 项目中实现 Word 文档预览,一直是个让前端开发头大的问题。Word 文档的格式复杂、内容丰富、排版细节繁多,想要还原得像 Office 一样,还真不是件容易的事。
今天,我要安利两个宝藏级的开源库,它们几乎可以覆盖你所有的 Docx 预览场景 —— 不管你是要“原汁原味的展示”,还是“提取语义结构做内容编辑”,都能轻松搞定。
docx-preview VS mammoth
这两个库都能在浏览器端直接处理 .docx 文件,但实现思路完全不同。下面我就从使用方式、适用场景、优缺点三个维度带你快速了解它们。
docx-preview
像素级还原,真·预览利器
如果你正在开发一个在线文档预览器,或者希望用户可以在 Web 页面中“像在 Word 里一样看文档”,那 docx-preview 就是你要找的神兵利器。
安装方式:
npm install docx-preview
基本用法:
import { renderAsync } from 'docx-preview';
renderAsync(docBlob, document.getElementById('preview')).then(() => {
  console.log('文档渲染完成');
});
实现 Word 在线预览器例子
<!-- 示例一:Word 在线预览器(使用 docx-preview) -->
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>docx-preview 在线预览器</title>
<style>
    #preview {
      border: 1px solid #ccc;
      padding: 20px;
      height: 600px;
      overflow-y: auto;
    }
  </style>
</head>
<body>
<h2>📄 Word 在线预览器(docx-preview)</h2>
<input type="file" id="fileInput" accept=".docx" />
<div id="preview">请上传 .docx 文件</div>
<script type="module">
    import { renderAsync } from'https://cdn.jsdelivr.net/npm/docx-preview@0.3.6/+esm';
    document.getElementById('fileInput').addEventListener('change', async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      const container = document.getElementById('preview');
      container.innerHTML = '正在加载文档...';
      try {
        await renderAsync(file, container, null, {
          className: 'docx',
          inWrapper: true,
          breakPages: true,
          renderHeaders: true,
          renderFooters: true,
        });
        console.log('✅ 文档渲染成功');
      } catch (e) {
        console.error('❌ 渲染失败:', e);
        container.innerHTML = '文档加载失败,请检查文件格式';
      }
    });
  </script>
</body>
</html>
⚠️ 注意事项:
- 对复杂文档兼容性很好,但个别嵌入元素可能显示不完整
进阶配置示例:
renderAsync(docBlob, container, null, {
  breakPages: true,      // 分页展示
  renderHeaders: true,   // 页眉
  renderFooters: true,   // 页脚
  className: 'docx-viewer',
  useBase64URL: false,   // 资源处理方式
});
想要一页展示整篇文档?只需设置 breakPages: false 即可!
更多 docx-preview 高级配置参数汇总
|  |  |  |  | 
|---|
| className |  |  |  | 
| inWrapper |  |  |  | 
| ignoreWidth |  |  |  | 
| ignoreHeight |  |  |  | 
| ignoreFonts |  |  |  | 
| breakPages |  |  |  | 
| ignoreLastRenderedPageBreak |  |  |  | 
| renderHeaders |  |  |  | 
| renderFooters |  |  |  | 
| renderFootnotes |  |  |  | 
| renderEndnotes |  |  |  | 
| renderComments |  |  |  | 
| useBase64URL |  |  |  | 
| useMathMLPolyfill |  |  |  | 
| experimental |  |  |  | 
| trimXmlDeclaration |  |  |  | 
| debug |  |  |  | 
mammoth:极简 HTML 转换器,适合内容提取
与其说 mammoth 是预览库,不如说它是一个“语义提取工具”。它的目标不是还原 Word 的视觉样式,而是转换为干净的 HTML 结构,非常适合内容系统或富文本编辑器的输入源。
安装方式:
npm install mammoth
转换文档:
import mammoth from 'mammoth';
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 |  |  |  | 
| includeEmbeddedStyleMap |  |  |  | 
| includeDefaultStyleMap |  |  |  | 
| convertImage |  |  | 图片处理(默认 base64,可自定义为 Blob URL) | 
| ignoreEmptyParagraphs |  |  |  | 
| idPrefix |  |  |  | 
| transformDocument |  |  |  | 
选哪个?看场景!
|  |  |  | 
|---|
| 做在线预览器 | docx-preview | 高度还原 Word 格式,支持分页、样式、页眉页脚 | 
| 做内容管理系统 | mammoth |  | 
其他方案:微软 Office Online(不推荐)
可能你会想到微软官方的 Office Web Viewer:
<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=文档URL"></iframe>
虽然它的渲染质量是最强的,但有以下劣势:
所以对于可控性要求高的前端项目,还是推荐轻量又灵活的开源方案。
总结
如果你是第一次做 Word 文档预览,这里是我的建议:
- 追求“所见即所得”?选 docx-preview。
这两个库都是轻量纯前端实现,不依赖服务端转换,适合所有现代浏览器,能极大简化你的开发流程。
阅读原文:原文链接
该文章在 2025/8/4 18:03:10 编辑过