When Word updates a table of contents, it copies the formatting set on a heading's text, such as bold: true on a TextRun, onto the entry. That takes priority over the TOC1 style, so bold: false there can't remove it. Formatting from the heading's style isn't copied, so the fix is to make the heading style bold instead. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
17 KiB
Troubleshooting
This guide covers common issues and their solutions when working with docx.
Quick Index
| Symptom | Go to |
|---|---|
| File corrupt/won't open | Document Won't Open |
| Unreadable content with custom font | Document Won't Open |
| Images appear blank | Images Not Showing |
| Buffer not defined error | Browser Issues |
| Table cells misaligned | Table Issues |
| Styles not applying | Styling Issues |
| Embedded font charset ignored | Styling Issues |
| Memory errors | Memory Issues |
Document Won't Open
"The file is corrupt and cannot be opened"
Cause: The document was not written correctly, often due to not waiting for the document to finish generating.
Solutions:
- Ensure you're using
awaitor.then()withPackermethods:
// Correct - using await
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync("document.docx", buffer);
// Correct - using .then()
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("document.docx", buffer);
});
// Wrong - missing await
const buffer = Packer.toBuffer(doc); // Returns a Promise, not a buffer!
fs.writeFileSync("document.docx", buffer);
- In Express.js, ensure the response completes:
app.get("/download", async (req, res) => {
const doc = new Document({/* ... */});
const buffer = await Packer.toBuffer(doc);
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
res.setHeader("Content-Disposition", "attachment; filename=document.docx");
res.send(buffer);
});
"Word found unreadable content" with embedded fonts
Cause: In older versions of docx (< 9.x), embedded fonts whose family name contained spaces or non-ASCII characters produced zip entries with those characters in the path. Word expects embedded-font paths to be plain ASCII filenames.
Solution: Upgrade to docx 9.x or later. The library now writes embedded fonts as sequential filenames (font1.odttf, font2.odttf, …) which avoids the issue entirely. No code changes are needed — any name you pass to the fonts array continues to work as before.
"We're sorry. We can't open document.docx"
Cause: Invalid XML structure in the document.
Solutions:
- Check for invalid characters in text content:
import { Document, Paragraph, TextRun } from "docx";
const text = "Text pasted from somewhere else,\x07 with a control character in it";
// Remove control characters
const cleanText = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
const doc = new Document({
sections: [
{
children: [new Paragraph({ children: [new TextRun(cleanText)] })],
},
],
});
- Ensure all required properties are provided:
import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";
const buffer = fs.readFileSync("./demo/assets/images/dog.png");
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
// ImageRun requires type, data, and transformation
new ImageRun({
type: "png",
data: buffer,
transformation: { width: 100, height: 100 }, // Required!
}),
],
}),
],
},
],
});
Images Not Showing
Image appears as blank or broken
Cause: Incorrect image data or type.
Solutions:
- Verify the image type matches the file:
import { Document, ImageRun, Paragraph } from "docx";
import * as fs from "fs";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
// Match type to actual file format
new ImageRun({
type: "gif", // Must match the actual image format
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
transformation: { width: 100, height: 100 },
}),
],
}),
],
},
],
});
- In browsers, read the image as an
ArrayBufferand pass it straight in.datatakes anArrayBuffer,Uint8Array,Bufferor base64 string, but not aBlob, and browsers have noBuffer:
const response = await fetch(imageUrl);
const data = await response.arrayBuffer();
new ImageRun({
type: "png",
data,
transformation: { width: 100, height: 100 },
});
- Check image dimensions are specified:
// Both width and height are required
transformation: {
width: 100, // Required
height: 100, // Required
}
Browser Issues
"Buffer is not defined"
Cause: Node.js Buffer is not available in browsers.
Solutions:
- Use a polyfill (a library that provides missing browser functionality) like
buffer:
import { Buffer } from "buffer";
window.Buffer = Buffer;
-
Or configure your bundler (Webpack/Vite) to include polyfills
-
For Vite, use
vite-plugin-node-polyfills
Blob download not working
Cause: Incorrect blob handling.
Solution:
import { saveAs } from "file-saver";
Packer.toBlob(doc).then((blob) => {
saveAs(blob, "document.docx");
});
Table Issues
Table cells not aligning
Cause: Missing or inconsistent column widths.
Solution:
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
const doc = new Document({
sections: [
{
children: [
new Table({
width: { size: 100, type: WidthType.PERCENTAGE },
rows: [
new TableRow({
children: [
new TableCell({
width: { size: 50, type: WidthType.PERCENTAGE },
children: [new Paragraph("Cell 1")],
}),
new TableCell({
width: { size: 50, type: WidthType.PERCENTAGE },
children: [new Paragraph("Cell 2")],
}),
],
}),
],
}),
],
},
],
});
Merged cells not working
Cause: Incorrect merge configuration.
Solution:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [
new TableRow({
children: [
// Horizontal merge
new TableCell({
columnSpan: 2, // Span 2 columns
children: [new Paragraph("Merged horizontally")],
}),
],
}),
new TableRow({
children: [
// Vertical merge
new TableCell({
rowSpan: 2, // Span 2 rows
children: [new Paragraph("Merged vertically")],
}),
new TableCell({ children: [new Paragraph("Row 2")] }),
],
}),
new TableRow({
// The first column of this row is the merged cell above
children: [new TableCell({ children: [new Paragraph("Row 3")] })],
}),
],
}),
],
},
],
});
Styling Issues
Styles not applying
Cause: Style not defined in the document styles.
Solution:
import { Document, Paragraph } from "docx";
const doc = new Document({
styles: {
paragraphStyles: [
{
id: "MyStyle",
name: "My Custom Style",
basedOn: "Normal",
next: "Normal",
run: {
bold: true,
color: "FF0000",
},
},
],
},
sections: [
{
children: [
new Paragraph({
text: "Styled text",
style: "MyStyle", // Reference by id
}),
],
},
],
});
Font not displaying
Cause: Font not available on the target system.
Solution: Embed the font:
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
import * as fs from "fs";
const doc = new Document({
fonts: [
{
name: "Pacifico",
data: fs.readFileSync("./demo/assets/Pacifico.ttf"),
characterSet: CharacterSet.ANSI,
},
],
sections: [
{
children: [
new Paragraph({
children: [new TextRun({ text: "Written in the embedded font", font: "Pacifico" })],
}),
],
},
],
});
Embedded font characterSet ignored (non-Latin text renders incorrectly)
Cause: In versions prior to the fix in #3387, the characterSet option was accepted but not written to fontTable.xml. This caused the w:charset element to be missing, so Word would fall back to a default encoding.
Solution: Upgrade to the latest version of docx. The characterSet property is now correctly passed through to the font table. Ensure you specify the appropriate character set for your font:
import { CharacterSet, Document } from "docx";
const doc = new Document({
fonts: [
{
name: "MyJapaneseFont",
data: fs.readFileSync("./fonts/NotoSansJP.ttf"),
characterSet: CharacterSet.SHIFTJIS,
},
],
// ...
});
Headers and Footers
Header/footer not appearing on all pages
Cause: Multiple sections with different headers.
Solution:
import { Document, Footer, Header, Paragraph } from "docx";
const myHeader = new Header({ children: [new Paragraph("My header")] });
const myFooter = new Footer({ children: [new Paragraph("My footer")] });
const doc = new Document({
// Apply headers to each section
sections: [
{
headers: { default: myHeader },
footers: { default: myFooter },
children: [new Paragraph("The first section")],
},
{
// New section inherits headers unless overridden
headers: { default: myHeader }, // Repeat if needed
footers: { default: myFooter },
children: [new Paragraph("The second section")],
},
],
});
Different first page header not working
Cause: Missing titlePage property.
Solution:
import { Document, Header, PageBreak, Paragraph, TextRun } from "docx";
const normalHeader = new Header({ children: [new Paragraph("The header of every other page")] });
const firstPageHeader = new Header({ children: [new Paragraph("The header of the first page")] });
const doc = new Document({
sections: [
{
properties: {
titlePage: true, // Required for different first page
},
headers: {
default: normalHeader,
first: firstPageHeader, // Only shows with titlePage: true
},
children: [new Paragraph({ children: [new TextRun("The first page"), new PageBreak(), new TextRun("The second page")] })],
},
],
});
Page Numbers
Page numbers not updating
Cause: Page numbers are fields that update when the document opens.
Note: This is expected behavior. Page numbers will update when opened in Word.
Page X of Y not working
Solution:
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
const doc = new Document({
sections: [
{
footers: {
default: new Footer({
children: [
new Paragraph({
children: [
new TextRun("Page "),
new TextRun({
children: [PageNumber.CURRENT],
}),
new TextRun(" of "),
new TextRun({
children: [PageNumber.TOTAL_PAGES],
}),
],
}),
],
}),
},
children: [new Paragraph("The footer has the page number")],
},
],
});
Table of Contents
TOC entries are bold, though the TOC style isn't
Cause: When Word updates the table, it copies the formatting set on a heading's text, such as bold: true on a TextRun, onto its entry. That takes priority over the TOC1 to TOC9 styles, so bold: false in them doesn't remove it.
Solution: Make the heading style bold instead of the heading's text, such as with styles.default.heading1: { run: { bold: true } }. Formatting from the heading's style isn't copied onto the entries. See Styling the entries.
TOC has no page numbers
Cause: The page numbers depend on how the document is laid out, so docx writes the entries for the headings without them, and leaves them for Word to fill in when it updates the field.
Solution:
- Set
updateFields: truein document features, so Word asks to update the fields when the document is opened:
import { Document, HeadingLevel, Paragraph, TableOfContents } from "docx";
const doc = new Document({
features: {
updateFields: true,
},
sections: [
{
children: [
new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
new Paragraph({ text: "Introduction", heading: HeadingLevel.HEADING_1 }),
new Paragraph({ text: "Getting started", heading: HeadingLevel.HEADING_2 }),
],
},
],
});
-
Or, in Word, right-click the TOC and select "Update Field". In LibreOffice, right-click it and select "Update Index"
-
Or write the page numbers with the document, by giving it
pageNumbers: estimatePageNumbersfromdocx/layout, which lays out its pages as Word would. This also fills them in for applications that don't update fields, such as LibreOffice when it converts a document to PDF. See Layout:
import { Document, HeadingLevel, Paragraph, TableOfContents } from "docx";
import { estimatePageNumbers } from "docx/layout";
const doc = new Document({
pageNumbers: estimatePageNumbers,
sections: [
{
children: [
new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
new Paragraph({ text: "Introduction", heading: HeadingLevel.HEADING_1 }),
new Paragraph({ text: "Getting started", heading: HeadingLevel.HEADING_2 }),
],
},
],
});
Memory Issues
"JavaScript heap out of memory"
Cause: Processing very large documents or many images.
Solutions:
- Increase Node.js memory:
node --max-old-space-size=4096 script.js
- Process images before embedding:
// Resize images before adding to document
const sharp = require("sharp");
const resized = await sharp(imagePath).resize(800, 600).toBuffer();
- Generate documents in batches
TypeScript Errors
"Property does not exist on type"
Cause: Using incorrect property names or types.
Solution: Check the API documentation or TypeScript definitions:
import { Document, Paragraph } from "docx";
const doc = new Document({
sections: [
{
children: [
// Use IntelliSense to see available options
new Paragraph({
// Ctrl+Space in VS Code, or here once you click the code, to see options
text: "A paragraph",
}),
],
},
],
});
Getting Help
If you can't find a solution here:
- Check the Demo files for working examples
- Search GitHub Issues for similar problems
- Open a new issue with:
- docx version number
- Node.js version
- Minimal reproducible code example
- Expected vs actual behavior