docx
Overview
docx (npm package, repository dolanmiu/docx, version 9.14.0 when checked on 2026-10-24) builds Word documents declaratively: you create a Document with sections, then serialise it with Packer. It writes new files; it does not edit existing ones. The examples below were run against 9.14.0 and produced a valid .docx.
Instructions
npm install docx
Use ES modules ("type": "module" in package.json) so top-level await works, or wrap the code in an async function.
- Build a
Document({ sections: [{ children: [...] }] }). Section content is Paragraph and Table objects.
- Serialise with
await Packer.toBuffer(doc) (Node), Packer.toBlob(doc) (browser) or Packer.toBase64String(doc).
- Write the buffer with
fs.writeFileSync.
Things that differ from older tutorials:
ImageRun needs type ("png", "jpg", "gif", "bmp" or "svg"; svg also needs a fallback image). Omitting it is a TypeScript error. Add altText for accessibility.
- Table cell colour is
shading: { type: ShadingType.CLEAR, fill: "1F4E79", color: "auto" }. fill is the cell background; this form was run and produced a valid file.
- Lists are not automatic: declare a
numbering.config entry (use LevelFormat.DECIMAL or LevelFormat.BULLET) and refer to it with numbering: { reference, level } on each paragraph.
- Use the
HeadingLevel enum (HeadingLevel.HEADING_2), never a string cast to any.
Examples
Example 1: "Generate a monthly report with a table and page numbers"
// report.ts
import {
Document, Packer, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell,
WidthType, ShadingType, Footer, PageNumber, AlignmentType,
} from "docx";
import fs from "node:fs";
const cell = (text: string, head = false) =>
new TableCell({
shading: head ? { type: ShadingType.CLEAR, fill: "1F4E79", color: "auto" } : undefined,
children: [new Paragraph({ children: [new TextRun({ text, bold: head, color: head ? "FFFFFF" : undefined })] })],
});
const doc = new Document({
sections: [{
footers: {
default: new Footer({
children: [new Paragraph({
alignment: AlignmentType.CENTER,
children: [new TextRun({ children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES] })],
})],
}),
},
children: [
new Paragraph({ heading: HeadingLevel.HEADING_1, text: "Monthly Report" }),
new Paragraph({ children: [new TextRun("Covers "), new TextRun({ text: "September 2026", bold: true }), new TextRun(". Figures are preliminary.")] }),
new Table({
width: { size: 100, type: WidthType.PERCENTAGE },
rows: [
new TableRow({ tableHeader: true, children: [cell("Plan", true), cell("Revenue", true), cell("Growth", true)] }),
new TableRow({ children: [cell("Starter"), cell("$45,000"), cell("+12%")] }),
new TableRow({ children: [cell("Growth"), cell("$32,000"), cell("+8%")] }),
],
}),
],
}],
});
fs.writeFileSync("report.docx", await Packer.toBuffer(doc));
Run npx tsx report.ts; the result is report.docx with a heading, a shaded header row that repeats on page breaks, and "Page 1 of 1" in the footer (Word fills the fields in when it opens the file).
Example 2: "Add a logo, a confidentiality header and a numbered action list"
// proposal.ts
import {
Document, Packer, Paragraph, TextRun, ImageRun, Header, AlignmentType, LevelFormat, HeadingLevel,
} from "docx";
import fs from "node:fs";
const doc = new Document({
numbering: {
config: [
{ reference: "actions", levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT }] },
{ reference: "bullets", levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT }] },
],
},
sections: [{
headers: {
default: new Header({
children: [new Paragraph({ alignment: AlignmentType.RIGHT, children: [new TextRun({ text: "Confidential", italics: true, color: "999999" })] })],
}),
},
children: [
new Paragraph({
children: [new ImageRun({
type: "png",
data: fs.readFileSync("logo.png"),
transformation: { width: 200, height: 60 },
altText: { name: "logo", title: "Company logo", description: "Northwind Studio logo" },
})],
}),
new Paragraph({ heading: HeadingLevel.HEADING_2, text: "Action items" }),
...["Review Q3 metrics", "Update pricing model", "Schedule team sync"].map(
(item) => new Paragraph({ text: item, numbering: { reference: "actions", level: 0 } }),
),
new Paragraph({ text: "Open question: renewal terms", numbering: { reference: "bullets", level: 0 } }),
],
}],
});
fs.writeFileSync("proposal.docx", await Packer.toBuffer(doc));
The output has the logo at the top, a right-aligned grey "Confidential" header on every page, a numbered list 1.-3. and one bullet.
Guidelines
- Pass real
Buffer data to ImageRun; to embed a remote image, download it first and check the response is an image.
- Page-number fields are computed by Word on open; a viewer that does not recalculate fields may show them blank.
- For many repeated items, generate the
Paragraph/TableRow arrays with map rather than building the XML by hand.
- To check output without Word, unzip the file (
unzip -p report.docx word/document.xml) or open it in LibreOffice.
- Do not use this library to edit an existing .docx or to read one; use a parser for reading and a template-filling tool for edits.
1---2name: docx3description: >-4 The docx library generates Word (.docx) files from Node.js or the browser in code, with no Word installation: paragraphs, tables, images, headers, footers, page numbers and numbered or bulleted lists. Use when someone asks to "generate a Word document from data", "create a .docx report in Node", "build a contract or proposal as docx", or "add page numbers to a generated Word file".5license: Apache-2.06compatibility: "Node.js 16+ or a modern browser; docx 9.x"7metadata:8 source: https://skillmd.com/skills/terminalskills/docx9 author: terminal-skills10 version: "1.1.0"11 category: documents12 repository: https://github.com/dolanmiu/docx13 tags: "docx, word, document, reports, office"14---1516# docx1718## Overview1920`docx` (npm package, repository dolanmiu/docx, version 9.14.0 when checked on 2026-10-24) builds Word documents declaratively: you create a `Document` with sections, then serialise it with `Packer`. It writes new files; it does not edit existing ones. The examples below were run against 9.14.0 and produced a valid .docx.2122## Instructions2324```bash25npm install docx26```2728Use ES modules (`"type": "module"` in package.json) so top-level `await` works, or wrap the code in an async function.29301. Build a `Document({ sections: [{ children: [...] }] })`. Section content is `Paragraph` and `Table` objects.312. Serialise with `await Packer.toBuffer(doc)` (Node), `Packer.toBlob(doc)` (browser) or `Packer.toBase64String(doc)`.323. Write the buffer with `fs.writeFileSync`.3334Things that differ from older tutorials:3536- `ImageRun` needs `type` (`"png"`, `"jpg"`, `"gif"`, `"bmp"` or `"svg"`; svg also needs a `fallback` image). Omitting it is a TypeScript error. Add `altText` for accessibility.37- Table cell colour is `shading: { type: ShadingType.CLEAR, fill: "1F4E79", color: "auto" }`. `fill` is the cell background; this form was run and produced a valid file.38- Lists are not automatic: declare a `numbering.config` entry (use `LevelFormat.DECIMAL` or `LevelFormat.BULLET`) and refer to it with `numbering: { reference, level }` on each paragraph.39- Use the `HeadingLevel` enum (`HeadingLevel.HEADING_2`), never a string cast to `any`.4041## Examples4243### Example 1: "Generate a monthly report with a table and page numbers"4445```typescript46// report.ts47import {48 Document, Packer, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell,49 WidthType, ShadingType, Footer, PageNumber, AlignmentType,50} from "docx";51import fs from "node:fs";5253const cell = (text: string, head = false) =>54 new TableCell({55 shading: head ? { type: ShadingType.CLEAR, fill: "1F4E79", color: "auto" } : undefined,56 children: [new Paragraph({ children: [new TextRun({ text, bold: head, color: head ? "FFFFFF" : undefined })] })],57 });5859const doc = new Document({60 sections: [{61 footers: {62 default: new Footer({63 children: [new Paragraph({64 alignment: AlignmentType.CENTER,65 children: [new TextRun({ children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES] })],66 })],67 }),68 },69 children: [70 new Paragraph({ heading: HeadingLevel.HEADING_1, text: "Monthly Report" }),71 new Paragraph({ children: [new TextRun("Covers "), new TextRun({ text: "September 2026", bold: true }), new TextRun(". Figures are preliminary.")] }),72 new Table({73 width: { size: 100, type: WidthType.PERCENTAGE },74 rows: [75 new TableRow({ tableHeader: true, children: [cell("Plan", true), cell("Revenue", true), cell("Growth", true)] }),76 new TableRow({ children: [cell("Starter"), cell("$45,000"), cell("+12%")] }),77 new TableRow({ children: [cell("Growth"), cell("$32,000"), cell("+8%")] }),78 ],79 }),80 ],81 }],82});8384fs.writeFileSync("report.docx", await Packer.toBuffer(doc));85```8687Run `npx tsx report.ts`; the result is `report.docx` with a heading, a shaded header row that repeats on page breaks, and "Page 1 of 1" in the footer (Word fills the fields in when it opens the file).8889### Example 2: "Add a logo, a confidentiality header and a numbered action list"9091```typescript92// proposal.ts93import {94 Document, Packer, Paragraph, TextRun, ImageRun, Header, AlignmentType, LevelFormat, HeadingLevel,95} from "docx";96import fs from "node:fs";9798const doc = new Document({99 numbering: {100 config: [101 { reference: "actions", levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT }] },102 { reference: "bullets", levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT }] },103 ],104 },105 sections: [{106 headers: {107 default: new Header({108 children: [new Paragraph({ alignment: AlignmentType.RIGHT, children: [new TextRun({ text: "Confidential", italics: true, color: "999999" })] })],109 }),110 },111 children: [112 new Paragraph({113 children: [new ImageRun({114 type: "png",115 data: fs.readFileSync("logo.png"),116 transformation: { width: 200, height: 60 },117 altText: { name: "logo", title: "Company logo", description: "Northwind Studio logo" },118 })],119 }),120 new Paragraph({ heading: HeadingLevel.HEADING_2, text: "Action items" }),121 ...["Review Q3 metrics", "Update pricing model", "Schedule team sync"].map(122 (item) => new Paragraph({ text: item, numbering: { reference: "actions", level: 0 } }),123 ),124 new Paragraph({ text: "Open question: renewal terms", numbering: { reference: "bullets", level: 0 } }),125 ],126 }],127});128129fs.writeFileSync("proposal.docx", await Packer.toBuffer(doc));130```131132The output has the logo at the top, a right-aligned grey "Confidential" header on every page, a numbered list 1.-3. and one bullet.133134## Guidelines135136- Pass real `Buffer` data to `ImageRun`; to embed a remote image, download it first and check the response is an image.137- Page-number fields are computed by Word on open; a viewer that does not recalculate fields may show them blank.138- For many repeated items, generate the `Paragraph`/`TableRow` arrays with `map` rather than building the XML by hand.139- To check output without Word, unzip the file (`unzip -p report.docx word/document.xml`) or open it in LibreOffice.140- Do not use this library to edit an existing .docx or to read one; use a parser for reading and a template-filling tool for edits.141-