Open and Save Word documents in JavaScript Word

7 Oct 202617 minutes to read

The JavaScript Word Library enables you to open existing Word documents, modify their content, and save the updated documents. This guide demonstrates how to open a Word document from supported input types and save it as a browser download, a Uint8Array, or a Base64 string.

The Word Library works with Office Open XML .docx packages. The open and load methods do not read a filesystem path directly. In Node.js, read the file by using the host filesystem API and pass the resulting bytes to the library.

Opening an existing Word document

Open an existing Word document by passing its data to WordDocument.open. The method accepts a Uint8Array, an ArrayBuffer, or a Base64-encoded string. To open a browser File or Blob, use the asynchronous WordDocument.openAsync method.

Using Uint8Array

Open an existing Word document by passing the document data as a Uint8Array.

import { WordDocument } from '@syncfusion/ej2-docx';

// Loads the Word document from the specified path.
const response: Response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data: Uint8Array = new Uint8Array(await response.arrayBuffer());
// Opens the Word document.
const document: WordDocument = WordDocument.open(data);
// Loads the Word document from the specified path.
const response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data = new Uint8Array(await response.arrayBuffer());
// Opens the Word document.
const document = ej.docx.WordDocument.open(data);

Using ArrayBuffer

Open an existing Word document by passing the document data as an ArrayBuffer.

import { WordDocument } from '@syncfusion/ej2-docx';

// Loads the Word document from the specified path.
const response: Response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Gets the document data as an ArrayBuffer.
const data: ArrayBuffer = await response.arrayBuffer();
// Opens the Word document.
const document: WordDocument = WordDocument.open(data);
const response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Gets the document data as an ArrayBuffer.
const data = await response.arrayBuffer();
// Opens the Word document.
const document = ej.docx.WordDocument.open(data);

Using a Base64 string

Open an existing Word document from a Base64-encoded string by passing { format: 'base64' } to WordDocument.open. A Base64 data URL prefix is optional.

import { WordDocument } from '@syncfusion/ej2-docx';

// Sample Base64-encoded DOCX data.
const data: string = 'UEsDBBQAAAAI...';
// Opens the Word document.
const document: WordDocument = WordDocument.open(data, { format: 'base64' });
// Sample Base64-encoded DOCX data.
const data = 'UEsDBBQAAAAI...';
// Opens the Word document.
const document = ej.docx.WordDocument.open(data, { format: 'base64' });

A string passed without { format: 'base64' } is not treated as a file path. Direct filesystem-path loading is not supported.

Using a browser File or Blob

Use WordDocument.openAsync to open a browser File or Blob. The following example opens a File selected through an HTML file input. The method reads the object by using its arrayBuffer() method.

<input type="file" id="file-input" accept=".docx" />
import { WordDocument } from '@syncfusion/ej2-docx';

const input: HTMLInputElement = document.getElementById('file-input') as HTMLInputElement;

input.addEventListener('change', async (): Promise<void> => {
    const file: File | undefined = input.files?.[0];
    if (!file) {
        return;
    }

    const wordDocument: WordDocument = await WordDocument.openAsync(file);
});
const input = document.getElementById('file-input');

input.addEventListener('change', async () => {
    const file = input.files?.[0];
    if (!file) {
        return;
    }
    // Opens the Word document.
    const wordDocument = await ej.docx.WordDocument.openAsync(file);
});

Opening a document asynchronously

Use WordDocument.openAsync when a Promise-based API is required. It accepts a Uint8Array, an ArrayBuffer, a Base64 string with { format: 'base64' }, or a browser File or Blob.

import { WordDocument } from '@syncfusion/ej2-docx';

// Loads the Word document from the specified path.
const response: Response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Gets the document data as an ArrayBuffer.
const data: ArrayBuffer = await response.arrayBuffer();
// Opens the Word document asynchronously.
const document: WordDocument = await WordDocument.openAsync(data);
// Loads the Word document from the specified path.
const response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Gets the document data as an ArrayBuffer.
const data = await response.arrayBuffer();
// Opens the Word document asynchronously.
const document = await ej.docx.WordDocument.openAsync(data);

Opening a document with resource limits

Use LoadOptions to override resource limits while opening a document. Resource limits help restrict the total uncompressed package size and the uncompressed size of an individual package part.

import { WordDocument, type LoadOptions } from '@syncfusion/ej2-docx';

// Loads the Word document from the specified path.
const response: Response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data: Uint8Array = new Uint8Array(await response.arrayBuffer());
// Configures the resource limits for loading the document.
const options: LoadOptions = {
    limits: {
        totalUncompressedSize: 50 * 1024 * 1024,
        singlePartUncompressedSize: 25 * 1024 * 1024
    }
};

// Opens the Word document with the specified load options.
const document: WordDocument = WordDocument.open(data, options);
// Loads the Word document from the specified path.
const response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data = new Uint8Array(await response.arrayBuffer());
// Configures the resource limits for loading the document.
const options = {
    limits: {
        totalUncompressedSize: 50 * 1024 * 1024,
        singlePartUncompressedSize: 25 * 1024 * 1024
    }
};

// Opens the Word document with the specified load options.
const document = ej.docx.WordDocument.open(data, options);

Editing an opened Word document

After opening a document, access its sections and body to add or modify content.

import { WordDocument } from '@syncfusion/ej2-docx';

// Loads the Word document from the specified path.
const response: Response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}
// Converts the response content to a Uint8Array.
const data: Uint8Array = new Uint8Array(await response.arrayBuffer());
// Opens the Word document.
const document: WordDocument = WordDocument.open(data);

// Access the first section and a paragraph.
const paragraph = document.sections[0].body.paragraphs[0];
// Appends text to the paragraph.
paragraph.appendText('Appended after opening the document.');
// Loads the Word document from the specified path.
const response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data = new Uint8Array(await response.arrayBuffer());
// Opens the Word document.
const document = ej.docx.WordDocument.open(data);

// Access the first section and a paragraph.
const paragraph = document.sections[0].body.paragraphs[0];
// Appends text to the paragraph.
paragraph.appendText('Appended after opening the document.');

Saving and downloading a Word document in the browser

Save and download a Word document in the browser by passing a file name to the asynchronous save method.

import { WordDocument } from '@syncfusion/ej2-docx';

// Loads the Word document from the specified path.
const response: Response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data: Uint8Array = new Uint8Array(await response.arrayBuffer());
// Opens the Word document.
const document: WordDocument = WordDocument.open(data);

// To-Do: Modify the document.

// Save and download the document in the browser.
await document.save('output.docx');
// Loads the Word document from the specified path.
const response = await fetch('/input.docx');
if (!response.ok) {
    throw new Error(`Unable to load input.docx (${response.status})`);
}

// Converts the response content to a Uint8Array.
const data = new Uint8Array(await response.arrayBuffer());
// Opens the Word document.
const document = ej.docx.WordDocument.open(data);

// To-Do: Modify the document.

// Save and download the document in the browser.
await document.save('output.docx');

Passing a file name to save starts a browser download. It does not write to a Node.js filesystem path.

Saving a Word document as a Uint8Array

Save the document to memory as a Uint8Array by using saveSync or the parameterless save method. Use the returned bytes to upload the document, store it, process it further, or write it by using the host application’s file APIs.

Saving synchronously

import { WordDocument } from '@syncfusion/ej2-docx';

// Creates a new Word document.
const document: WordDocument = WordDocument.create();
// Appends text to the last paragraph.
document.lastParagraph.appendText('Generated in memory.');

// Saves the document as a Uint8Array.
const data: Uint8Array = document.saveSync();
// Creates a new Word document.
const document = ej.docx.WordDocument.create();
// Appends text to the last paragraph.
document.lastParagraph.appendText('Generated in memory.');

// Saves the document as a Uint8Array.
const data = document.saveSync();

Saving asynchronously

import { WordDocument } from '@syncfusion/ej2-docx';
// Creates a new Word document.
const document: WordDocument = WordDocument.create();
// Appends text to the last paragraph.
document.lastParagraph.appendText('Generated in memory.');

// Saves the document as a Uint8Array.
const data: Uint8Array = await document.save();
// Creates a new Word document.
const document = ej.docx.WordDocument.create();
// Appends text to the last paragraph.
document.lastParagraph.appendText('Generated in memory.');

// Saves the document as a Uint8Array.
const data = await document.save();

Saving a Word document as a Base64 string

Pass { format: 'base64' } to saveSync or save to serialize the document as a Base64-encoded string. Both synchronous and asynchronous save methods support this format.

import { WordDocument } from '@syncfusion/ej2-docx';

// Creates a new Word document.
const document: WordDocument = WordDocument.create();
// Appends text to the last paragraph.
document.lastParagraph.appendText('Generated as Base64.');

// Save synchronously as Base64.
const syncBase64: string = document.saveSync({ format: 'base64' });

// Save asynchronously as Base64.
const asyncBase64: string = await document.save({ format: 'base64' });
// Creates a new Word document.
const document = ej.docx.WordDocument.create();
// Appends text to the last paragraph.
document.lastParagraph.appendText('Generated as Base64.');

// Save synchronously as Base64.
const syncBase64 = document.saveSync({ format: 'base64' });

// Save asynchronously as Base64.
const asyncBase64 = await document.save({ format: 'base64' });

Reading and writing Word documents in Node.js

The Word Library does not open or save filesystem paths directly. In Node.js, use the host filesystem APIs to read a .docx file, pass its bytes to WordDocument.open, and write the bytes returned by save or saveSync.

import { readFile, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { WordDocument } = require('@syncfusion/ej2-docx');

// Read the DOCX package using the Node.js filesystem API.
const input: Uint8Array = await readFile('./input.docx');
// Opens the Word document.
const document = WordDocument.open(input);

// To-Do: Modify the document.

// Serialize and write the DOCX package using the Node.js filesystem API.
const output: Uint8Array = await document.save();
await writeFile('./output.docx', output);
import { readFile, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { WordDocument } = require('@syncfusion/ej2-docx');

// Read the DOCX package using the Node.js filesystem API.
const input = await readFile('./input.docx');
// Opens the Word document.
const document = WordDocument.open(input);

// To-Do: Modify the document.

// Serialize and write the DOCX package using the Node.js filesystem API.
const output = await document.save();
await writeFile('./output.docx', output);

Alternative load methods

The library also provides load, loadSync, and loadAsync as aliases for open, openSync, and openAsync, respectively. The alias methods support the same corresponding input types. Use either the open naming style or the load naming style consistently within an application.