Learn jsdocuments in 5 minutes.
jsdocuments is a JavaScript library to work with DOCX documents using nodejs, web browsers, and other JavaScript projects.
Developed with TypeScript, jsdocuments is the best and most complete JavaScript library to generate DOCX documents from scratch and using DOCX templates.
Among its many features, the following can be highlighted:
To achieve the best possible compatibility with nodejs and web browsers, jsdocuments uses TypeScript with the following compiler options:
The following formats are included in the package:
in addition to map files and TypeScript type information.
To use jsdocuments it's not mandatory to develop with TypeScript, but it's recommended. Vanilla JavaScript can also be used with jsdocuments.
Creating a new DOCX is as simple as instance the CreateDocx class, add new contents using the available methods and save the document.
For example, to add a text and a list using TypeScript with nodejs:
fs.writeFileSync is available in nodejs File system.
The same sample using Vanilla JavaScript with nodejs and the ESM module:
The same sample using Vanilla JavaScript with nodejs and CommonJS:
The following sample (generateDocx.js) generates and downloads a new DOCX in a web browser with the ESM module:
saveAs, available in FileSaver.js is the easiest way to download the document in a web browser.
The same sample using the IIFE format:
The openTemplate method is used to open a DOCX template and replace, remove and add new contents.
For example, to open a DOCX template and replace text variables in the document target using TypeScript with nodejs:
fs.readFileSync is available in nodejs File system.
The same sample using Vanilla JavaScript with nodejs and the ESM module:
The following sample (generateDocxFromTemplate.js) opens a DOCX template, generates and downloads a new DOCX in a web browser:
Using FileReader API is the easiest approach to generate an ArrayBuffer from a local file (a File or a Blob object) in a web browser.
In addition to replacing contents, jsdocuments includes methods to delete contents, get existing variables, optimize templates, customise the symbols used to define variables, and add WordFragments.
External files such as images, DOCX templates and DOCX outputs in jsdocuments use ArrayBuffer objects for maximum compatibility. Any JavaScript function or library compatible with ArrayBuffer can be used.
For example, to load an image using TypeScript with nodejs:
The same sample using Vanilla JavaScript with nodejs and the ESM module:
Using the FileReader API is the easiest approach to generate an ArrayBuffer from a local file (a File or a Blob object) in a web browser:
The Fetch API can be used to fetch external files.
On the JavaScript API are available the documentation pages, with all methods, options and samples of use. In addition to this documentation, jsdocuments packages include many samples to illustrate how to use all methods.