Export
The generateDocument() function generates a .docx file from options and returns the result in the requested format. Use generateDocumentSync() for synchronous generation and generateDocumentStream() for streaming.
generateDocument
Returns a Buffer (default in Node.js). Best for file I/O.
import { generateDocument } from "@office-open/docx";
import { writeFileSync } from "node:fs";
// Async (non-blocking)
const buffer = await generateDocument({
/* options */
});
writeFileSync("output.docx", buffer);
Output Types
Control the output format with the second argument:
// Uint8Array (cross-platform)
const bytes = await generateDocument(opts, { type: "uint8array" });
// Blob (browser)
const blob = await generateDocument(opts, { type: "blob" });
// Base64 string (API payloads)
const base64 = await generateDocument(opts, { type: "base64" });
// ArrayBuffer
const ab = await generateDocument(opts, { type: "arraybuffer" });
| type | Returns | Use Case |
|---|---|---|
| "nodebuffer" | Buffer | Node.js file I/O |
| "uint8array" | Uint8Array | Cross-platform raw bytes |
| "blob" | Blob | Browser downloads |
| "base64" | string | Data URLs, API payloads |
| "arraybuffer" | ArrayBuffer | Memory handling |
Sync Variant
Use generateDocumentSync() for synchronous generation — blocks the main thread but avoids async overhead:
import { generateDocumentSync } from "@office-open/docx";
const buffer = generateDocumentSync({
/* options */
});
Streaming
Use generateDocumentStream() for large documents — returns a ReadableStream without buffering the entire file:
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"));
Compression Options
All functions accept compression control. Default matches Microsoft Office: XML uses DEFLATE level 1 (SuperFast); media is split by type — already-compressed formats (PNG/JPEG/GIF) use STORE, the rest (EMF/WMF/BMP/TIFF/…) use DEFLATE level 1.
// Default (MS Office)
await generateDocument(opts);
// Maximum XML compression
await generateDocument(opts, { compression: { xml: 9 } });
// No compression
await generateDocument(opts, { compression: { xml: 0 } });
| Option | Type | Default | Description |
|---|---|---|---|
| compression.xml | number | 1 | DEFLATE level 0–9 |
| compression.media | number | 1 | compressible media only; PNG/JPEG/GIF always STORE |
Browser Download Example
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);