word文档转html(mammoth )

前言

最近老有需要把协议Word转化为html纯预览展示的需求,为了后面方便摸鱼,用工具包脚本直接转化(手动狗头),主要使用的是 mammoth 。

Word 转 HTML 工具

使用 mammoth 将 Word 文档转换为 HTML,特别适用于协议文档的在线预览。

安装依赖

bash

复制代码
npm install mammoth

完整代码

javascript

javascript 复制代码
const mammoth = require('mammoth')
const fs = require('fs')
const path = require('path')

function getFileConfig() {
  const inputDir = path.resolve(__dirname, 'input');
  const files = fs.readdirSync(inputDir).filter(f => f.endsWith('.docx'));
  return files.map(f => {
    return {
      inputPath: path.join(__dirname, 'input',f),
      outputPath: path.join(__dirname, 'output', f.replace('.docx', '.html'))
    }
  });
}

function transformParagraph(element) {
  let styleName = "";
  if (element.alignment === "center") {
    styleName = "text-center";
  } else if (element.alignment === "right") {
    styleName = "text-right";
  }
  
  return {
      ...element,
      styleName
  };
}

const options = {
  styleMap: [
    "p[style-name='text-center'] => p.text-center:fresh",
    "p[style-name='text-right'] => p.text-right:fresh",
     "u => span.text-underline:fresh"
  ],
  transformDocument: mammoth.transforms.paragraph(transformParagraph)
}

const convertToHtml = (config) => {
  const { inputPath, outputPath } = config;
  return mammoth.convertToHtml({ path: inputPath }, options).then(function(result){
    const html = result.value
    const templatePath = path.join(__dirname, 'template.html')
    const tempHtml = fs.readFileSync(templatePath, 'utf8')
    const insertTag = '<div id="app">'
    const insertIndex = tempHtml.lastIndexOf(insertTag) + insertTag.length
    const resHtml = tempHtml.slice(0, insertIndex) + html + tempHtml.slice(insertIndex)
    fs.writeFileSync(outputPath, resHtml, 'utf8')
  }).catch(function(err){
    console.log(err);
  });
}

const allFileConfig = getFileConfig();
const allFileConfigLength = allFileConfig.length;
// 清空 output 目录
if (fs.existsSync(path.join(__dirname, 'output'))) {
  fs.rmdirSync(path.join(__dirname, 'output'), { recursive: true, force: true });
}
fs.mkdirSync(path.join(__dirname, 'output'));

let index = 0;
console.log(`开始转换,共 ${allFileConfigLength} 个文件`);
function runNext() {
  if (index >= allFileConfigLength) {
    console.log('文件转换完成,请查看 output 目录');
    return;
  }
  
  const config = allFileConfig[index];
  console.log(`${index + 1}: ${path.basename(config.inputPath)}`);
  
  convertToHtml(config).then(() => {
    index++;
    runNext();
  }).catch(err => {
    console.error(`Error processing file ${path.basename(config.inputPath)}:`, err);
    index++;
    runNext();
  });
}

runNext();

目录结构

text

css 复制代码
word-to-html/
├── input/                 # 存放要转换的 .docx 文件
│   ├── 协议1.docx
│   └── 协议2.docx
├── output/                # 转换后的 HTML 文件输出目录
├── template.html          # HTML 模板文件   
├──index.js

在package.json的scripts中添加命令行脚本

js 复制代码
  "convert-doc": "node ./bin/word-to-html/index.js",

使用方法

  1. 将 Word 文档 (.docx) 放入 input 目录
  2. 运行脚本:
  3. 查看 output 目录获取转换后的 HTML 文件

模板文件示例 (template.html)

xml 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>协议文档预览</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            line-height: 1.8;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        #app {
            background: white;
            padding: 40px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .text-underline { text-decoration: underline; }
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 15px 0;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div id="app"></div>
</body>
</html>

注意事项

  • 确保 Word 文档为 .docx 格式
  • 复杂表格样式可能需要额外调整
  • 脚本会自动覆盖 output 目录中的现有文件
  • 建议在转换前备份重要的 Word 文档
相关推荐
Highcharts.js25 分钟前
缺失数据可视化图表开发实战|Highcharts创建人员出生统计面积图表示例
开发语言·前端·javascript·信息可视化·highcharts·图表开发
LaughingZhu7 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
怕浪猫7 小时前
Electron 开发实战(一):从零入门核心基础与环境搭建
前端·electron·ai编程
小鹏linux8 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
前端若水9 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Bigger9 小时前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
涵涵(互关)9 小时前
Naive-ui树型选择器只显示根节点
前端·ui·vue
BY组态9 小时前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态9 小时前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态
SoaringHeart9 小时前
Flutter进阶:OverlayEntry 插入图层管理器 NOverlayZIndexManager
前端·flutter