@yinyoudexing/xml2word
v0.1.6
Published
Convert WordprocessingML XML / HTML / text into a .docx file
Downloads
257
Maintainers
Readme
xml2word
把 WordprocessingML XML / HTML / 纯文本字符串转换成 .docx(本质是一个 zip 包)。
适用场景:后端 Node 生成 Word;前端直接传入长字符串(HTML 或纯文本)导出 Word。
安装
npm i @yinyoudexing/xml2word快速开始(前端)
1) 传入 HTML 字符串生成 docx 并下载
import { htmlToDocxBlob } from "@yinyoudexing/xml2word";
const html = `<div><h1>标题</h1><p style="text-align: justify;">正文</p></div>`;
const blob = await htmlToDocxBlob(html, { inputFormat: "html" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "out.docx";
a.click();
URL.revokeObjectURL(url);2) 传入“很长的字符串”(HTML 或纯文本)自动识别
import { htmlToDocxBlob } from "@yinyoudexing/xml2word";
const longString = getContentFromEditor(); // 可能是 HTML,也可能只是纯文本
const blob = await htmlToDocxBlob(longString, { inputFormat: "auto" });快速开始(Node)
1) 传入 HTML 文件内容生成 docx
import fs from "node:fs";
import { htmlToDocxBuffer } from "@yinyoudexing/xml2word";
const html = fs.readFileSync("文档.html", "utf8");
const buf = await htmlToDocxBuffer(html, { inputFormat: "html" });
fs.writeFileSync("out.docx", buf);2) 传入 WordprocessingML(document.xml 或 body 片段)生成 docx
import fs from "node:fs";
import { xmlToDocxBuffer } from "@yinyoudexing/xml2word";
// body 片段(库会自动包一层 <w:document><w:body>)
const bodyXml = `<w:p><w:r><w:t>Hello</w:t></w:r></w:p>`;
const buf = await xmlToDocxBuffer(bodyXml, { inputKind: "body" });
fs.writeFileSync("out.docx", buf);API
XML → DOCX
xmlToDocxUint8Array(xml, options?) => Promise<Uint8Array>
- 通用输出格式(Node/浏览器都能用)
options.inputKind:auto:自动判断(像<w:document>就当 document,否则当 body)document:你传的是完整<w:document>...body:你传的是<w:p>...等正文片段
options.validateXml:是否校验 XML(默认true)
xmlToDocxBlob(xml, options?) => Promise<Blob>
- 浏览器下载用
xmlToDocxBuffer(xml, options?) => Promise<Buffer>
- Node 写文件用
HTML / Text → DOCX
htmlToDocxUint8Array(input, options?) => Promise<Uint8Array>
- 支持前端“直接传入很长的字符串”
options.inputFormat:auto(默认):自动判断像不像 HTML;像就按 HTML 解析,否则当纯文本html:强制按 HTML 解析(推荐编辑器输出 HTML 的场景)text:强制按纯文本解析(按换行拆段)
options.validateXml:是否校验最终生成的word/document.xml是否为合法 XML(默认true)
htmlToDocxBlob(input, options?) => Promise<Blob>
- 浏览器下载用
htmlToDocxBuffer(input, options?) => Promise<Buffer>
- Node 写文件用
HTML 支持范围(当前版本)
- 支持:
div/p/span/strong/em/u/br、h1~h6、ul/ol/li、table/tr/td/th - 支持:
img(src=dataURL)、canvas(data-image=dataURL) - 支持:
text-align、vertical-align、font-size(pt/px)、color(rgb/#)、font-family - 支持:
background-color/background(段落/单元格底色)、white-space: nowrap(表格单元格) - 支持:表格边框(solid/dashed/dotted/double)、表格按内容估算列宽
- 支持分页标记(会插入 Word 分页符):
<div class="page-break"></div><hr class="page-break" />style="page-break-after: always"/break-after: always
- 会跳过:
canvas、编辑器辅助 DOM(如 ProseMirror widget)
限制(需要额外实现才能完全还原):
- CSS 选择器:不解析
<style>,只读取标签上的style=""行内样式 - 复杂 CSS:比如浮动/定位/复杂布局无法直接映射到 Word
- 精准“自动分页”:如果需要指定分页位置,请在 HTML 中插入分页标记
