Skip to content

Builder API ​

The DocxBuilder class provides a fluent, chainable API for constructing Word documents.

Creating a Builder ​

ts
import { createDocx, defineStyles } from 'docx-kit/node'

const styles = defineStyles({
  title: { fontSize: 28, fontWeight: 'bold' },
  body: { fontSize: 12 },
})

const doc = createDocx({
  styles,
  page: { size: 'A4', margin: '20mm' },
})

Content Methods ​

Headings (h1–h6) ​

All six heading levels with optional style overrides:

ts
doc
  .h1('Main Title', { className: 'title' })
  .h2('Section 1', { id: 'section-1', style: { color: '#333' } })
  .h3('Subsection 1.1')
  .h4('Details')
  .h5('Minor Heading')
  .h6('Smallest Heading')

Paragraphs ​

Plain text or rich content with inline styling:

ts
doc
  .p('A simple paragraph.')
  .p('Centered bold text', {
    className: 'body',
    style: { textAlign: 'center', fontWeight: 'bold' },
  })
  .p('With an explicit id', {
    id: 'summary',
    style: { lineHeight: 1.8 },
  })

Rich Inline Content ​

Paragraphs can contain mixed inline content using span() and inlineImg() helpers:

ts
import { inlineImg, span } from 'docx-kit/node'

// Mixed text runs with per-span styles
doc.p([
  span('Hello '),
  span('world', { bold: true, color: '#e11d48' }),
  span(' — all in one paragraph.'),
])

// Inline image among text
doc.p([
  span('Click the icon: '),
  inlineImg({ data: iconDataUrl, width: 16, height: 16 }),
  span(' to continue.'),
])

See the Rich Content Example for a complete demonstration.

Images ​

Embed PNG, JPEG, GIF, or BMP images:

ts
import { readFileSync } from 'node:fs'

const imageBytes = readFileSync('./logo.png')

doc.image({
  data: imageBytes,
  width: 200,
  height: 100,
  alt: 'Company Logo',
})

// With floating layout
doc.image({
  data: imageBytes,
  width: 150,
  height: 150,
  floating: {
    wrap: 'square',
    x: 100,
    y: 50,
  },
})

Tables ​

Create data tables with typed columns:

ts
interface SalesRow {
  product: string
  revenue: number
  growth: string
}

doc.table<SalesRow>({
  columns: [
    { key: 'product', title: 'Product' },
    { key: 'revenue', title: 'Revenue', align: 'right' },
    { key: 'growth', title: 'YoY Growth', align: 'center' },
  ],
  data: [
    { product: 'Widget A', revenue: 120000, growth: '+15%' },
    { product: 'Widget B', revenue: 85000, growth: '+8%' },
    { product: 'Widget C', revenue: 45000, growth: '-3%' },
  ],
  bordered: true,
  striped: true,
  headerCellStyle: {
    fontWeight: 'bold',
    backgroundColor: '#f0f0f0',
  },
})

Page Breaks ​

Insert forced page breaks:

ts
doc
  .h1('Chapter 1')
  .p('Content for chapter 1...')
  .pageBreak()
  .h1('Chapter 2')
  .p('Content for chapter 2...')

Raw Nodes (add) ​

Add any raw DSL node directly:

ts
doc.add({ type: 'heading', level: 2, text: 'Raw Heading' })
doc.add({ type: 'paragraph', text: 'Raw paragraph' })
doc.add({ type: 'pageBreak' })

Plugins ​

Invoke registered plugins:

ts
import { qrcodePlugin } from 'docx-kit/node'

doc
  .use(qrcodePlugin())     // Register QRCode
  .plugin('qrcode', { text: 'https://example.com', size: 200 })

See the Plugins guide for more details.

Export Methods ​

MethodReturnsPlatformUse Case
.save(filename)Promise<void>Node.jsStream a .docx package to disk
.toStream()Promise<Readable>Node.jsStream a .docx package to another destination
.toBlob()Promise<Blob>BrowserDownload via URL.createObjectURL()
.toBuffer()Promise<Uint8Array>BothRaw bytes for any use case
.toBase64()Promise<string>BothHTTP transfer, DB storage
.toDocument()Promise<Document>BothAccess raw docx Document instance
.toJSON()objectBothSerialize builder state for debugging

Browser Download Example ​

ts
// In the browser
const blob = await doc.toBlob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'report.docx'
a.click()
URL.revokeObjectURL(url)

Node.js Save Example ​

ts
// In Node.js
import { createDocx } from 'docx-kit/node'

const doc = createDocx()
await doc.save('output.docx')

// Or pipe to another Node.js destination
const stream = await doc.toStream()
stream.pipe(uploadDestination)

Plugin Registration (use) ​

Register plugins before invoking them:

ts
import { createDocx, qrcodePlugin } from 'docx-kit/node'

const doc = createDocx()
  .use(qrcodePlugin())     // Register QRCode
  .h1('Document with Plugins')
  .plugin('qrcode', { text: 'https://example.com' })

Chaining & Immutability ​

All content methods return this, enabling indefinite chaining:

ts
const doc = createDocx()

doc
  .h1('Title')
  .p('Paragraph 1')
  .p('Paragraph 2')
  .pageBreak()
  .h2('Section')
  .p('More content...')
  .save('output.docx')

The builder is mutable — nodes accumulate in the internal array. If you need multiple documents from the same config, create separate createDocx() instances.

Released under the MIT License.