Carbone Render API

You should read the getting started section before going further.

Add a template

POST render.carbone.io/template

When a template is uploaded, a Template ID is created which is the unique identifier for the template. If you upload the same template twice, you will have the same Template ID. You can have a different Template ID for a same file by providing a payload in the body: payload will be used to create the hash of the template.

The Template ID is useful to identify the template you want to remove it or to render your report.

Request body

{
  payload  : '', // [Optional] Filename salt for hashing
  template : ''  // File content
}

Success

{
  "success" : true,   // Request result
  "data"    : {
    "templateId" : "" // Template ID
  }
}

Error

{
  "success" : false, // Request result
  "error"   : ""     // Error message
}

Examples

const request = require('request');
const fs      = require('fs');

const bearerToken = 'YOUR_TOKEN';

request.post({
  url      : 'https://render.carbone.io/template',
  formData : {
    payload  : 'FILENAME_SALT', // OPTIONAL
    template : fs.createReadStream('/path/to/your/document')
  },
  headers : {
    'Authorization': 'Bearer ' + bearerToken
  }
}, (err, response, body) => {
  // Handle error
  // body contains a response
});

Template ID generation

The Template ID is predictable and indempotent, this is why we made it like that. Here is how we compute it (NodeJS):

const crypto = require('crypto');

const hash = crypto.createHash('sha256')
                 .update(new Buffer('YOUR_OPTIONAL_PAYLOAD'))
                 .update('FILE_CONTENT')
                 .digest('hex');

It is a sha256 hash from payload concatenated with the template content, in hexadecimal.

Get a template

GET render.carbone.io/template/:templateId

templateId Unique identifier of the template

Success

This request does not return a JSON object. In case of success, the request stream the file content with a 200 code status.

Error

In case of error, no file is stream and a 404 or 500 code is returned.

Examples

const request = require('request');
const fs      = require('fs');

const bearerToken = 'YOUR_TOKEN';
const templateId  = 'YOUR_TEMPLATE_ID';

request.get({
  url : 'https://render.carbone.io/template/' + templateId,
  headers : {
    'Authorization': 'Bearer ' + bearerToken
  }
}).on('response', (response) => {
  if (response.statusCode !== 200) {
    // Template not found
    return;
  }

  const writeStream = fs.createWriteStream('./my-file.odt');

  writeStream.on('error', (err) => {
    // Handle file system error
  });

  writeStream.on('finish', () => {
    // Your file is ready!
  });

  response.pipe(writeStream);
}).on('error', (err) => {
  // Handle network error
});

Delete a template

DELETE render.carbone.io/template/:templateId

templateId Unique identifier of the template

Success

{
  "success" : true,   // Request result
  "error"   : null
}

Error

{
  "success" : false,   // Request result
  "error"   : ""       // Error message
}

Examples

const request = require('request');
const fs      = require('fs');

const bearerToken = 'YOUR_TOKEN'
const templateId  = 'YOUR_TEMPLATE_ID';

request.delete({
  url : 'https://render.carbone.io/template/' + templatedId,
  headers : {
    'Authorization': 'Bearer ' + bearerToken
  }
}, (err, response, body) => {
  // Handle error
  // Body contains a response
});

Rendering a report

POST render.carbone.io/render/:templateId

templateId Unique identifier of the template to use for rendering

Request body

{
  data         : {},              // JSON data
  convertTo    : 'pdf',           // String|Object, to convert the document (pdf, xlsx, docx, ods, csv, txt, ...)
  lang         : 'en',            // String, output lang of the report
  complement   : {},              // Object|Array, extra data accessible in the template with {c.} instead of {d.}
  variableStr  : '{#def = d.id}', // String, predefined alias string, see designer's documentation
  reportName   : '{d.date}.odt',  // String, dynamic file name, output in third argument of the callback
  enums        : {                // Object, list of enumerations, use it in reports with `convEnum` formatters
    'ORDER_STATUS' : ['open', 'close']
    'SPEED' : {
      10 : 'slow'
      20 : 'fast'
    }
  },
  translations : {                // Object, dynamically overwrite all loaded translations for this rendering
    fr : {'one':'un' },
    es : {'one':'uno'}
  },
  currencySource : 'EUR',         // String, currency of your JSON data, used by the formatter formatC
  currencyTarget : 'USD',         // String, target currency for conversions direclty in your report
  currencyRates  : {              // Object, currency exchange rates for conversions from currencySource to currencyTarget
    EUR : 1,
    USD : 1.1403
  }
}
See the Carbone JS API to know what field you can provide in the body.

Success

{
  "success" : true,   // Request result
  "error"   : null,
  "data": {
    "renderId": ""    // Render Id
  }
}

Error

{
  "success" : false,   // Request result
  "error"   : ""       // Error message
}

Examples

const request = require('request');
const fs      = require('fs');

const bearerToken = 'YOUR_TOKEN';
const templateId  = 'YOUR_TEMPLATE_ID';

request.post({
  url : 'https://render.carbone.io/render/' + templateId,
  json : true,
  body : {
    data : {}
  },
  headers : {
    'Authorization': 'Bearer ' + bearerToken
  }
}, (err, response, body) => {
  // Handle error
  // Body contains an error or the render ID
});

Get a rendered report

GET render.carbone.io/render/:renderId

renderId Unique identifier of the rendered report

You don't need the authentication token to get a render.

Success

This request does not return a JSON object. In case of success, the request stream the file content with a 200 code status.

Error

In case of error, no file is stream and a 404 code is returned.

Examples

const regexp = /filename="(.*)"/gi;

request.get({
  url : 'https://render.carbone.io/render/YOUR_RENDER_ID'
}).on('response', (response) => {
  if (response.statusCode !== 200) {
    // File is not found
    return;
  }

  const filename    = regexp.exec(response.headers['content-disposition'])[1];
  const writeStream = fs.createWriteStream(filename);

  writeStream.on('error', (error) => {
    // Handle file system error
  });

  writeStream.on('finish', () => {
    // Your file is ready
  });

  response.pipe(writeStream);
}).on('error', (error) => {
  // Handle network error
});

Carbone JS API

This API is intended for

  • NodeJS developer who wants to integrate the Open Source version of Carbone in his application
  • Carbone Render user who wants to learn more on the data he can send in APIs

Consider using Carbone Render API if you want a ready-to-use solution with High Availability and more features.

Native API

render(templatePath, 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> : options, details below
  • callback <Function> : three parameters, err, result (Binary), reportName (String)
As a Carbone Render user, you can send data and options fields.

options can one of these parameters:

{
  convertTo    : 'pdf', // String|Object, to convert the document (pdf, xlsx, docx, ods, csv, txt, ...)
  lang         : 'en-us', // String, output lang of the report
  complement   : {},  // Object|Array, extra data accessible in the template with {c.} instead of {d.}
  variableStr  : '{#def = d.id}', // String, predefined alias string, see designer's documentation
  reportName   : '{d.date}.odt', // String, dynamic file name, output in third argument of the callback
  enums        : { // Object, list of enumerations, use it in reports with `convEnum` formatters
    'ORDER_STATUS' : ['open', 'close']
    'SPEED' : {
      10 : 'slow'
      20 : 'fast'
    }
  },
  translations : {  // Object, dynamically overwrite all loaded translations for this rendering
    'fr-fr' : {'one':'un' },
    'es-es' : {'one':'uno'}
  }
}

convertTo can be an object for CSV export

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

characterSet can be one these options : https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options

renderXML(xml, data, options, callback)

Same as render function, except that it accepts pure XML string instead of a template path

Example:

  var data = {
    param : 'field_1'
  };
  carbone.renderXML('<xml>{d.param}</xml>', data, function (err, result) {
    console.log(result); //output <xml>field_1</xml>
  });

set(options)

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

Set general carbone parameters.

  • options can contains
  {
    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
  }

Example:

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

addFormatters(customFormatters)

Carbone comes with embedded formatters

You can add your own formatters, and overwrite default ones.

  • 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
}

CLI

For convenience, install carbone globally

  npm install carbone -g

translate

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