docxtemplater
Generate docx, pptx, and xlsx from templates (Word, Powerpoint and Excel documents), from Node.js or the browser. Demo: https://www.docxtemplater.com/demo. #docx #office #generator #templating #report #json #generate #generation #template #create #pptx #docx #xlsx #react #vuejs #angularjs #browser #typescript #image #html #table #chart
Top Related Projects
Use a docx as a jinja2 template
A pure PHP library for reading and writing word processing documents
Standalone Office Open XML files (Microsoft Office 2007 and later) generator for Word (docx), PowerPoint (pptx) and Excell (xlsx) in javascript. The output is a stream.
Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
Quick Overview
Docxtemplater is a powerful library for generating dynamic Word documents (.docx) and OpenOffice documents (.odt) using JavaScript. It allows users to create templates with placeholders and then fill those placeholders with data programmatically, making it ideal for generating reports, contracts, and other customized documents.
Pros
- Easy to use with a simple API for template creation and data injection
- Supports complex document structures, including tables, lists, and nested content
- Works with both Node.js and browser environments
- Extensible through modules for additional functionality (e.g., images, charts)
Cons
- Limited to .docx and .odt formats; doesn't support other document types
- Requires some knowledge of Office Open XML structure for advanced use cases
- Performance may degrade with very large documents or complex templates
- Documentation could be more comprehensive for advanced features
Code Examples
- Basic usage:
const Docxtemplater = require('docxtemplater');
const PizZip = require('pizzip');
const fs = require('fs');
// Load the docx file as a binary
const content = fs.readFileSync('input.docx', 'binary');
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true });
// Set the templateVariables
doc.setData({
firstName: 'John',
lastName: 'Doe',
phone: '0652455478',
description: 'New Website'
});
// Render the document (replace all occurences of {first_name}, {last_name}, etc.)
doc.render();
// Generate a buffer with the document
const buf = doc.getZip().generate({ type: 'nodebuffer' });
// Save the buffer to a file
fs.writeFileSync('output.docx', buf);
- Using loops in templates:
const data = {
products: [
{ name: 'Laptop', price: 1000 },
{ name: 'Smartphone', price: 500 },
{ name: 'Tablet', price: 300 }
]
};
doc.setData(data);
doc.render();
- Conditional rendering:
const data = {
isMember: true,
name: 'Alice'
};
doc.setData(data);
doc.render();
Getting Started
-
Install the package:
npm install docxtemplater pizzip
-
Create a template document (input.docx) with placeholders like
{firstName}
,{lastName}
, etc. -
Use the code from the first example above to generate your document.
-
Run your script:
node your-script.js
-
The generated document will be saved as
output.docx
.
Competitor Comparisons
Use a docx as a jinja2 template
Pros of python-docx-template
- Written in Python, making it easier to integrate with Python-based projects
- Supports more complex template structures, including loops and conditionals
- Better documentation and examples for Python developers
Cons of python-docx-template
- Limited to Python environment, while docxtemplater is JavaScript-based and can be used in browser or Node.js
- May have slower performance for large-scale document generation compared to docxtemplater
- Less active community and fewer updates compared to docxtemplater
Code Comparison
python-docx-template:
from docxtpl import DocxTemplate
doc = DocxTemplate("template.docx")
context = {'company_name': 'World Company'}
doc.render(context)
doc.save("generated_doc.docx")
docxtemplater:
const Docxtemplater = require('docxtemplater');
const fs = require('fs');
const doc = new Docxtemplater();
const template = fs.readFileSync('template.docx', 'binary');
doc.loadZip(template);
doc.setData({company_name: 'World Company'});
doc.render();
const buf = doc.getZip().generate({type: 'nodebuffer'});
fs.writeFileSync('generated_doc.docx', buf);
Both libraries offer similar functionality for template rendering, but with syntax and usage patterns specific to their respective languages. The choice between them often depends on the project's primary programming language and ecosystem.
A pure PHP library for reading and writing word processing documents
Pros of PHPWord
- More comprehensive library for creating and manipulating Word documents
- Supports a wider range of document elements and formatting options
- Better suited for generating complex documents from scratch
Cons of PHPWord
- Steeper learning curve due to its extensive feature set
- May be overkill for simple template-based document generation
- Slower performance when working with large documents
Code Comparison
PHPWord:
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello, World!');
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('helloWorld.docx');
docxtemplater:
const doc = new Docxtemplater();
doc.loadZip(zip);
doc.setData({ name: 'John' });
doc.render();
const output = doc.getZip().generate({ type: 'nodebuffer' });
fs.writeFileSync('output.docx', output);
PHPWord is more suitable for creating complex documents from scratch, offering extensive control over document structure and formatting. docxtemplater, on the other hand, excels at template-based document generation, providing a simpler API for filling in predefined templates with data. Choose PHPWord for comprehensive document creation and manipulation, or docxtemplater for efficient template-based document generation.
Standalone Office Open XML files (Microsoft Office 2007 and later) generator for Word (docx), PowerPoint (pptx) and Excell (xlsx) in javascript. The output is a stream.
Pros of officegen
- Supports multiple Office document types (Word, Excel, PowerPoint)
- Easier to generate documents from scratch without templates
- More flexible for creating dynamic content programmatically
Cons of officegen
- Less focused on template-based document generation
- May require more code for complex document structures
- Documentation is less comprehensive compared to docxtemplater
Code Comparison
officegen:
var officegen = require('officegen');
var docx = officegen('docx');
var pObj = docx.createP();
pObj.addText('Hello World!');
docxtemplater:
var DocxTemplater = require('docxtemplater');
var doc = new DocxTemplater().loadZip(zip);
doc.setData({
firstName: 'John',
lastName: 'Doe'
});
doc.render();
officegen is more suitable for generating Office documents from scratch with programmatic content creation, while docxtemplater excels in template-based document generation with data injection. officegen offers broader Office format support, but docxtemplater provides a more streamlined approach for working with existing templates and replacing placeholders with actual data.
Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
Pros of docx
- More comprehensive API for creating and manipulating Word documents
- Better documentation and examples
- Active development with frequent updates
Cons of docx
- Steeper learning curve due to more complex API
- Larger package size and potentially slower performance
- Limited template-based document generation capabilities
Code Comparison
docx:
const doc = new Document();
const paragraph = doc.createParagraph("Hello World");
paragraph.style("Heading1");
doc.addParagraph(paragraph);
docxtemplater:
const doc = new Docxtemplater();
doc.loadZip(zip);
doc.setData({ name: "John" });
doc.render();
The code examples highlight the different approaches: docx focuses on programmatic document creation, while docxtemplater emphasizes template-based generation. docx provides more granular control over document elements, but requires more code for basic tasks. docxtemplater offers a simpler API for template-based generation, making it easier to populate documents with data.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
docxtemplater
docxtemplater is a library to generate docx/pptx documents from a docx/pptx template. It can replace {placeholders} with data and also supports loops and conditions. The templates can be edited by non-programmers, for example your clients.
docxtemplater is very robust because of the many fixed issues over the years, and the high quality of tests and code.
Features
- Replace a {placeholder} by a value
- Use loops: {#users} {name} {/users}
- Use loops in tables to generate columns
- Use conditions (if users.length>3) with angular Parsing
- Insert custom XML {@rawXml} (for formatted text for example)
Quickstart
- Get started with docxtemplater on nodejs
- Get started with docxtemplater in the browser (react, angular, vue, nextjs)
Documentation
The full documentation of the latest version can be found here.
See CHANGELOG.md for information about how to migrate from older versions.
Modules
Functionality can be added with the following paid modules :
- Image module to add a given image with the syntax:
{%image}
; - Html Module to insert formatted text in a docx document with the syntax
{~html}
; - XLSX Module to be able to do templating on Excel files (xlsx extension), also with loops and conditions;
- Chart Module to replace a chart by using data from the JSON object that you give with the syntax
{$chart}
; - Html-Pptx Module to insert formatted text in a pptx document with the syntax
{~html}
; - Error Location Module to show the errors in the template using Word comments
- Slides Module to create multiple slides dynamically with the syntax
{:users}
; - Subtemplate Module to include an external docx file inside a given docx file with the syntax
{:include doc}
; - Subsection Module to include subsections (headers/footers) from an other document with the syntax
{:subsection doc}
; - Subtemplate-pptx Module to include an external pptx file inside a given pptx file with the syntax
{:include doc}
; - Word-Run Module to include raw runs (<w:r>) inside the document with the syntax
{r@wrun}
. This makes it possible to include styled text without having to remove the enclosing paragraph like in the {@rawXml} tag; - QrCode Module to replace an image, keeping any existing properties;
- Table Module to create tables from two dimensional data using the syntax
{:table data}
; - Meta Module to make a document readonly, add a text watermark or update the margins;
- Styling Module restyle a paragraph, a cell or a table depending on some data using the syntax
{:stylepar style}
; - Footnotes Module to be able to add footnotes to a document using the syntax
{:footnotes foot}
- Paragraph Placeholder Module to simplify conditions that should show or hide a given paragraph using the syntax
{?tag}
About docxtemplater
Docxtemplater is my main job, and has been maintained for over 8 years. Expect to get great support if you buy any modules, and also good support on the open-source version.
Top Related Projects
Use a docx as a jinja2 template
A pure PHP library for reading and writing word processing documents
Standalone Office Open XML files (Microsoft Office 2007 and later) generator for Word (docx), PowerPoint (pptx) and Excell (xlsx) in javascript. The output is a stream.
Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot