DOCX
导出
将文档导出为 buffer、blob、base64 或流
generateDocument() 函数根据选项生成 .docx 文件,并以指定格式返回结果。使用 generateDocumentSync() 进行同步生成,使用 generateDocumentStream() 进行流式生成。
generateDocument
默认返回 Buffer(Node.js 环境下)。适用于文件 I/O。
import { generateDocument } from "@office-open/docx";
import { writeFileSync } from "node:fs";
// 异步(非阻塞)
const buffer = await generateDocument({
/* options */
});
writeFileSync("output.docx", buffer);
输出类型
通过第二个参数控制输出格式:
// Uint8Array(跨平台)
const bytes = await generateDocument(opts, { type: "uint8array" });
// Blob(浏览器)
const blob = await generateDocument(opts, { type: "blob" });
// Base64 字符串(API 载荷)
const base64 = await generateDocument(opts, { type: "base64" });
// ArrayBuffer
const ab = await generateDocument(opts, { type: "arraybuffer" });
| type | 返回值 | 适用场景 |
|---|---|---|
| "nodebuffer" | Buffer | Node.js 文件 I/O |
| "uint8array" | Uint8Array | 跨平台原始字节 |
| "blob" | Blob | 浏览器下载 |
| "base64" | string | Data URL、API 载荷 |
| "arraybuffer" | ArrayBuffer | 内存处理 |
同步变体
使用 generateDocumentSync() 进行同步生成 — 阻塞主线程,但避免了异步开销:
import { generateDocumentSync } from "@office-open/docx";
const buffer = generateDocumentSync({
/* options */
});
流式生成
使用 generateDocumentStream() 处理大文档 — 返回 ReadableStream,无需在内存中缓冲整个文件:
import { generateDocumentStream } from "@office-open/docx";
import { createWriteStream } from "node:fs";
import { Readable } from "node:stream";
const stream = generateDocumentStream({
/* options */
});
Readable.fromWeb(stream).pipe(createWriteStream("output.docx"));
压缩选项
所有函数均支持压缩控制。默认行为与 Microsoft Office 一致:XML 使用 DEFLATE 级别 1(SuperFast);媒体按类型区分——已压缩格式(PNG/JPEG/GIF)使用 STORE,其余(EMF/WMF/BMP/TIFF)使用 DEFLATE 级别 1。
// 默认(MS Office 行为)
await generateDocument(opts);
// XML 最大压缩
await generateDocument(opts, { compression: { xml: 9 } });
// 不压缩
await generateDocument(opts, { compression: { xml: 0 } });
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| compression.xml | number | 1 | DEFLATE 级别 0–9 |
| compression.media | number | 1 | 仅可压缩媒体;PNG/JPEG/GIF 始终 STORE |
浏览器下载示例
const blob = await generateDocument(opts, { type: "blob" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "output.docx";
a.click();
URL.revokeObjectURL(url);