LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

做 DOCX 预览?这个神库别错过!

admin
2025年8月4日 8:49 本文热度 85

在 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 {
      border1px solid #ccc;
      padding20px;
      height600px;
      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',
          inWrappertrue,
          breakPagestrue,
          renderHeaderstrue,
          renderFooterstrue,
        });
        console.log('✅ 文档渲染成功');
      } catch (e) {
        console.error('❌ 渲染失败:', e);
        container.innerHTML = '文档加载失败,请检查文件格式';
      }
    });
  
</script>
</body>
</html>

⚠️ 注意事项:

  • 对复杂文档兼容性很好,但个别嵌入元素可能显示不完整
  • 大文档加载时间略长(毕竟是还原每一个像素)

进阶配置示例:

renderAsync(docBlob, container, null, {
  breakPagestrue,      // 分页展示
  renderHeaderstrue,   // 页眉
  renderFooterstrue,   // 页脚
  className'docx-viewer',
  useBase64URLfalse,   // 资源处理方式
});

想要一页展示整篇文档?只需设置 breakPages: false 即可!

更多 docx-preview 高级配置参数汇总

参数名
类型
默认值
说明
className
string
"docx"
自定义 CSS 类名前缀
inWrapper
boolean
true
是否包裹内容
ignoreWidth
boolean
false
忽略页面宽度
ignoreHeight
boolean
false
忽略页面高度
ignoreFonts
boolean
false
忽略字体定义
breakPages
boolean
true
是否分页
ignoreLastRenderedPageBreak
boolean
true
忽略分页标签
renderHeaders
boolean
true
渲染页眉
renderFooters
boolean
true
渲染页脚
renderFootnotes
boolean
true
渲染脚注
renderEndnotes
boolean
true
渲染尾注
renderComments
boolean
false
渲染批注
useBase64URL
boolean
false
base64 图片资源
useMathMLPolyfill
boolean
false
公式补丁
experimental
boolean
false
启用制表符实验功能
trimXmlDeclaration
boolean
true
去除 xml 声明头
debug
boolean
false
调试模式

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 {
      border1px solid #aaa;
      padding20px;
      min-height200px;
    }
  
</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 渲染前修改文档结构

选哪个?看场景!

目标场景
推荐方案
理由说明
做在线预览器docx-preview
高度还原 Word 格式,支持分页、样式、页眉页脚
做内容管理系统mammoth
生成结构化 HTML,利于编辑和再加工

其他方案:微软 Office Online(不推荐)

可能你会想到微软官方的 Office Web Viewer

<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=文档URL"></iframe>

虽然它的渲染质量是最强的,但有以下劣势:

  • 需要公网可访问的文档链接
  • 无法自定义样式或结构
  • 依赖外部服务,无法脱离微软生态

所以对于可控性要求高的前端项目,还是推荐轻量又灵活的开源方案。

总结

如果你是第一次做 Word 文档预览,这里是我的建议:

    • 追求“所见即所得”?选 docx-preview
    • 只想获取内容做二次处理?用 mammoth

    这两个库都是轻量纯前端实现,不依赖服务端转换,适合所有现代浏览器,能极大简化你的开发流程。


    阅读原文:原文链接


    该文章在 2025/8/4 18:03:10 编辑过
    关键字查询
    相关文章
    正在查询...
    点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
    点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
    点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
    点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
    Copyright 2010-2025 ClickSun All Rights Reserved