floodtide/dom-docx
GitHub: floodtide/dom-docx
将语义化 HTML 片段转换为原生可编辑 Word 文档的转换库,保留真实文档结构而非截图取巧。
Stars: 356 | Forks: 11
# dom-docx
将语义化 **HTML 片段**转换为原生、可编辑的 **Word 文档** (OOXML):段落、文本块、列表、表格、图片。非截图或布局取巧。
**在线演示:** [dom-docx.com](https://dom-docx.com/)。试用转换器,浏览展示案例,阅读学习指南。
采用视觉回归循环构建:在 Chromium 中渲染 HTML,转换为 docx,通过 LibreOffice 光栅化,根据人工验证的指标对布局和结构保真度进行评分,然后不断迭代。最新评分:[TEST-SCORES.md](./docs/TEST-SCORES.md) · 方法论:[SCORING.md](./docs/SCORING.md)。
## 安装
```
npm install dom-docx
```
需要 **Node.js ≥ 20**。默认的 **`inline`** 路径不需要浏览器或 Playwright。
### 什么时候需要 Playwright?
| 入口 | `styleSource: "inline"` | `styleSource: "computed"` | `rasterizeInPlace` |
| -------------------------------- | ----------------------- | ------------------------- | ------------------ |
| **Node** (`dom-docx`) | 纯 JS,无浏览器 | **Playwright + Chromium** | **Playwright + Chromium** (同一无头页面) |
| **浏览器** (`dom-docx/browser`) | 纯 JS,无实时 DOM | **实时页面**:原生 `getComputedStyle` | **实时页面**:canvas/SVG → PNG `
` 于标签页内 |
在 Node 上,`playwright` 是一个**可选的同级依赖**。`npm install dom-docx` 仅拉取 `docx`、`cheerio` 和 `fflate`,没有任何重量级内容。只有当你传入 `styleSource: "computed"` 或 `rasterizeInPlace` 时,它才会被延迟加载。要使用这些路径,请自行安装 Playwright 和 Chromium,只需一次:
```
npm install playwright
npx playwright install chromium
```
Playwright 也被**开发测试框架**使用(使用本库非必须)。贡献者:克隆后运行 `npm run setup`。
转换过程**不**需要 LibreOffice。它仅用于视觉测试框架。
## CLI
无需编写任何代码即可转换文件:
```
npx dom-docx input.html -o output.docx
npx dom-docx input.html # writes input.docx next to it
cat fragment.html | npx dom-docx - -o - # stdin → binary stdout (pipelines)
npx dom-docx input.html -s computed # stylesheet/class HTML (needs playwright installed)
npm install -g dom-docx # optional: install globally, then run "dom-docx" without npx
```
输入是一个 **HTML body 片段**,与 API 相同。使用 `--help` 查看所有选项。
## 快速开始
### 浏览器
```
import { convertHtmlToDocx } from "dom-docx/browser";
const html = `
Quarterly Report
Revenue grew 12% year over year.
- North America
- EMEA
Quarterly Report
Revenue grew 12% year over year.
- North America
- EMEA
- `/`
- ` 包括 `list-style-type`)、表格、链接、行内格式
- 块级背景色、引用块、`
`、简单的 flex 行(≤4 项) - `data:` 图片;通过你的 `imageResolver` 处理远程图片 - 页面大小/方向/边距、默认字体、元数据、页眉/页脚 HTML、页码、目录、语言/方向 - 低复杂度的行内 SVG(柱状图 + 文本) - 表格单元格内的 CSS 柱状 div(背景色 + 高度/宽度 → 原生色块条) **进阶(可选 `styleSource: "computed"`):** - 通过 `getComputedStyle` 解析 `