---
source: https://carbone.io/documentation/developer/embedding/embedding-in-node.html
title: "Embedding in Node.js"
description: "Embed Carbone in your NodeJS application"
generated_at: "2026-07-24"
---

# Embedding in Node.js

Embed Carbone in your NodeJS application

## Introduction

> ℹ️ **Note:** Only the Community Edition can be embedded in a NodeJS application.  
> Please, contact us if you need the Enterprise Edition with all features in a NodeJS application

> ⚠️ **Warning:** Chat support is not available to Community users.

CarboneJS is an open source document generator, it provides:

-   The **NodeJS engine** generates any documents from a template and a JSON data-set.
-   **Community features**: Text replacement, loops, PDF generation, data formatting, and more! It does not contain **_Enterprise features\*_**.
-   **All export formats**: DOCX, PDF, XLSX, ODS, ODG, XML, HTML, and more!
-   **CCL License**: [Permissive license](https://github.com/carboneio/carbone/blob/master/LICENSE.md).
-   **Support**: Create an [issue on Github](https://github.com/carboneio/carbone/issues)
-   **Tutorial**: Access the [CarboneJS quickstart](#generate-a-report).

**_\* Enterprise Features_** (dynamic images, charts, colors, et cetera...): are available through the [Carbone Cloud API](/documentation/quickstart/getting-started/generate-a-document.md) or Carbone On-premise.

### Minimum Requirements

-   NodeJS 10.x+
-   Libre Office is required to generate PDFs. Without LibreOffice, Carbone can still generate other formats, with the constraint that the export file type must be the template type (e.g., Docx to Docx, Xlsx to Xlsx, Pptx to Pptx, Odt to Odt, etc).

## Installation

Add Carbone in your application

```js
  npm install carbone
```

## Generate a report

Renders a template with given data and returns the result to the callback function.

```js
  // template file path input
  carbone.render(templatePath, data, [options,] callback);
  // alternative with XML input
  carbone.renderXML('<xml>{d.param}</xml>', data, [options,] callback);
```

-   templatePath `<string>`: path to the template relative to `defaultTemplatePath`, which is `process.cwd()` by default
-   data `<object|array>` : data to inject in the template
-   options `<object>` : optional object to set parameters, [details below](/documentation/developer/on-premise-installation/configuration.md)
-   callback `<Function>` : three parameters, `err`, `result` (Binary), `reportName` (String)

### Options

Complete options documentation is [here](/documentation/developer/http-api/generate-reports.md#generate-a-report-request-body). `options` can be one of these parameters:

```javascript
{
  convertTo    : 'pdf',           // Optional - Convert the document into another format. Accepted values: ods xlsx xls csv pdf txt odp ppt pptx jpg png odt doc docx txt jpg png epub html xml idml. List of supported formats: https://carbone.io/documentation.html#supported-files-and-features-list
  timezone     : 'Europe/Paris',  // Optional - Convert document dates to a timezone. The default timezone is `Europe/Paris`. The date must be chained with the `:formatD` formatter, for instance `{d.date:formatD(YYYY-MM-DD HH:MM)}`. List of accepted timezones (Column TZ identifier): https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
  lang         : 'en-us',         // Optional - Locale of the generated document, it will be used for translation `{t()}`, formatting numbers with `:formatN`, and currencies `:formatC`. List of supported locales: https://github.com/carboneio/carbone/blob/master/formatters/_locale.js
  complement   : {},              // Optional - Object|Array, extra data accessible in the template with {c.} instead of {d.}
  variableStr  : '{#def = d.id}', // Optional - Predefined alias, related documentation: https://carbone.io/documentation.html#alias
  reportName   : '{d.date}.odt',  // Optional - Static or dynamic file name. Multiple Carbone tags are accepted, such as `{d.type}-{d.date}.pdf`
  enum         : {                // Optional - Object, list of enumerations, use it in reports with `convEnum` formatters
    'ORDER_STATUS' : ['open', 'close']
    'SPEED' : {
      10 : 'slow'
      20 : 'fast'
    }
  },
  translations : {                // Optional - When the report is generated, all text between `{t( )}` is replaced with the corresponding translation. The `lang` option is required to select the correct translation. Learn more: https://carbone.io/documentation.html#translations
    'fr-fr' : {'one':'un' },
    'es-es' : {'one':'uno'}
  },
  hardRefresh: false,             // Optional - If true, the report content is refreshed at the end of the rendering process. To use this option, `convertTo` has to be defined.
  renderPath: 'carbone_render',   // Optional - can change the default path where rendered files are temporarily saved. By default, it creates the directory `carbone_render` in Operating System temp directory. It creates the path automatically
  renderPrefix: undefined         // Optional -  If defined, `Carbone.render` returns a file path instead of a buffer, and it adds this prefix in the rendered filename. The generated filename contains three parts: the prefix + a secure Pseudo-Random part of 22 characters + the report name, encoded in specific base64 to generate safe POSIX compatible filename on disk: `/renderpath/<prefix><22-random-chars><encodedReportName.extension>`. This filename can be decoded with the function `Carbone.decodeOuputFilename(pathOrFilename)`. It is the user responsibility to delete the file or not.
}
```

### CSV export options

During CSV conversion, the following elements can be changed: separator, delimiters and the character set. `convertTo` has to be an object with `formatName` set to `csv` and `formatOptions` with options. `characterSet` can be one of these options : [https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter\_Options](https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options)

```javascript
{
  convertTo : {
    formatName    : 'csv',
    formatOptions : {
      fieldSeparator : '+',
      textDelimiter  : '"',
      characterSet   : '76' // utf-8
    }
  }
}
```

## Convert a document

Convert a file to another format.

```javascript
  carbone.convert(fileBuffer, options, callback);
```

**Arguments**

-   `fileBuffer`: Buffer returned by fs.readFile (no utf-8)
-   `options`: [carbone.render options](/documentation/developer/on-premise-installation/configuration.md)
-   `callback`: Callback function with 2 arguments: (err, result) result is the file converted as a buffer

**Example**

Example of a simple DOCX to PDF conversion.

```javascript
  const carbone = require('carbone');
  const fs      = require('fs');

  var fileBuffer = fs.readFileSync('./invoice.docx');

  var options = {
    convertTo: 'pdf'
  };

  carbone.convert(fileBuffer, options, function (err, result) {
    fs.writeFileSync('./invoice.pdf', result);
  });
```

## Set global options

Set general carbone parameters.

```js
  carbone.set(options);
```

`options` can contain:

```javascript
  {
    tempPath     : os.tmpdir(),  // String, system temp directory by default
    templatePath : process.cwd(), // String, default template path, and lang path
    lang         : 'fr-fr', // String, set default lang of carbone, can be overwritten by carbone.render options
    translations : {    // Object, in-memory loaded translations at startup. Can be overwritten here
      'fr-fr' : {'one':'un' },
      'es-es' : {'one':'uno'}
    },
    factories    : 1, // Number of LibreOffice workers
    startFactory : false // If true, start LibreOffice worker immediately
  }
```

> ℹ️ **Note:** This function is not asynchronous (It may create the template or temp directory synchronously).

**Example**

```javascript
  carbone.set({
    lang : 'en-us'
  });
```

## Add custom formatters

Carbone comes with [embedded formatters](/documentation/design/formatters/overview.md).  
You can add your own formatters, and overwrite default ones.

```js
  carbone.addFormatters(customFormatters);
```

`customFormatters` must be an object containing one or many functions.

**Example**

```javascript
  carbone.addFormatters({
    // this formatter can be used in a template with {d.myBoolean:yesOrNo()}
    yesOrNo : function (data) { // data = d.myBoolean
      if (this.lang === 'fr-fr') {
        return data === true ? 'oui' : 'non';
      }
      return data === true ? 'yes' : 'no';
    }
  });
```

The function signature must be like this:

```javascript
function(data, firstParam, secondParam, ...) {
  return '' // value printed in a rendered report
}
```

> ℹ️ **Note:** It is not possible to pass tags or variables to formatters as parameters.

## CLI

For convenience, install carbone globally

```bash
  npm install carbone -g
```

### Translate

With this command, Carbone parses all your templates, finds [translation tags](/documentation/design/advanced-features/translations-i18n.md) like `{t(movie)}`, and updates JSON translation files accordingly.

It creates automatically a `lang` directory with all translation files, one per lang. It never loses already translated sentences.

Carbone loads translation files at startup if it finds a `lang` directory in the default template path.

```bash
carbone translate --help

# example:
carbone translate -l fr-fr -p path/to/template_default_path
```

### Find

If you want to find where a deprecated formatter is used among all your templates, carbone provides a search tool

```bash
carbone find needle
```

It searches among all reports in the current working directory and its subdirectories

## Related topics

- [Studio Web Component](/documentation/developer/embedding/studio-web-component.md)
- [Multi-Tenancy](/documentation/developer/embedding/multi-tenancy.md)
