Embedding

Embedding in Node.js

Embed Carbone in your NodeJS application

Introduction

Only the Community Edition can be embedded in a NodeJS application.
Please, contact us if you need the Enterprise Edition will all features in a NodeJS application

Chat support is not available to Community users.

CarboneJS is an open source document generator, it provides:

* Enterprise Features (dynamic images, charts, colors, et cetera...): are available through the Carbone Cloud API or Carbone On-premise.

Minimum Requirements

Installation

Add Carbone in your application

  npm install carbone

Generate a report

Renders a template with given datas and return result to the callback function.

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

Options

Complete options documentation is here. options can one of these parameters:

{
  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 doocument, it will 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 changes the default path where rendered files are temporary 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 responsability 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 have to be an object with formatName set to csv and formatOptions with options. characterSet can be one these options : https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options

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

Convert a document

Convert a file to another format.

  carbone.convert(fileBuffer, options, callback);

Arguments

Example

Example of a simple DOCX to PDF convertion.

  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.

  carbone.set(options);

options can contain:

  {
    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 overwrite 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 worker
    startFactory : false // If true, start LibreOffice worker immediately
  }

This function is not asynchronous (It may create the template or temp directory synchronously).

Example

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

Add custom formatters

Carbone comes with embedded formatters.
You can add your own formatters, and overwrite default ones.

  carbone.addFormatters(customFormatters);

customFormatters must be an object containing one or many functions.

Example

  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:

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

It is not possible to pass tags or variables to formatters as parameter.

CLI

For convenience, install carbone globally

  npm install carbone -g

Translate

With this command, Carbone parses all your templates, find translation tags 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.

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

carbone find needle

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