You are currently offline, serving cached version

Get Started (Node)

Installation

npm install --save docxtemplater pizzip

Usage

First, download the input.docx file and place it in the same folder as your JavaScript file.

Then, copy the following code which will allow you to generate an output document from the above template.

This code uses sample data for the {first_name} and {last_name} placeholders.

// PizZip is required because docx/pptx/xlsx files are all zipped files, and
// the PizZip library allows us to load the file in memory
const PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");

const fs = require("fs");
const path = require("path");

// Load the docx file as binary content
const content = fs.readFileSync(
    path.resolve(__dirname, "input.docx"),
    "binary"
);

// Unzip the content of the file
const zip = new PizZip(content);

// This will parse the template, and will throw an error if the template is
// invalid, for example, if the template is "{user" (no closing tag)
const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
});

// Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
doc.render({
    first_name: "John",
    last_name: "Doe",
    phone: "0652455478",
    description: "New Website",
});

// Get the zip document and generate it as a nodebuffer
const buf = doc.getZip().generate({
    type: "nodebuffer",
    // compression: DEFLATE adds a compression step.
    // For a 50MB output document, expect 500ms additional CPU time
    compression: "DEFLATE",
});

// buf is a nodejs Buffer, you can either write it to a
// file or res.send it with express for example.
fs.writeFileSync(path.resolve(__dirname, "output.docx"), buf);

After running this code, you will get a file in the same folder called "output.docx" where the {first_name} was replaced by "John", the {last_name} tag replaced by "Doe", …

Talk with sales Contact us