• 如何使用docx-preview实现Word文档预览功能
  • 发布于 1个月前
  • 371 热度
    0 评论
  • LoveC
  • 1 粉丝 60 篇博客
  •   
在 Web 项目中实现 Word 文档预览,一直是个让前端开发头大的问题。Word 文档的格式复杂、内容丰富、排版细节繁多,想要还原得像 Office 一样,还真不是件容易的事。今天,我要安利一个宝藏级的开源库,它们几乎可以覆盖你所有的 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>堆代码-duidaima.com</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 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 调试模式

用户评论