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.

You should read the CarboneJS getting started section before going further.

carbone.render

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

carbone.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> : optional object to set parameters, details below
  • callback <Function> : three parameters, err, result (Binary), reportName (String)

options

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
  enum         : {                // 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'}
  },
  hardRefresh: false              // If true, the report content is refreshed at the end of the rendering process. To use this option, `convertTo` has to be defined.
}

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

carbone.renderXML

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

carbone.renderXML(xml, data, options, callback);

Example

  const carbone = require('carbone');

  var data = {
    param : 'field_1'
  };

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

carbone.set(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'
  });

carbone.addFormatters

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 markers 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 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

Carbone Render API

You should read the getting started section before going further.

To try the api in few minutes, an Open API specification (previously known as Swagger) is available. Drag and drop the following file to Postman: carbone_render_api.yml.

Introduction

Test API

When you create an account on Carbone Account, you can generate an unlimited number or test reports. At your account creation, a test token is created and is available in your API access. You should use this token to test your Carbone integration in your products.

When you use the test token, all your templates are converted to PDF and contains a watermark.

To get a production token, you must take at least the free subscription. When it's done, you will see two tokens in your API access.

With a production token, you can convert your templates in any formats without watermark.

Choose carbone version

To avoid breaking your templates in production when a new version of carbone is deployed, you can choose the version of carbone with which your template will be rendered.

To do it, you have to add the carbone-version key in your header when request Carbone Render.

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,
    'carbone-version' : '2'
  }
}, (err, response, body) => {
  // Handle error
  // Body contains a response
});

You can only choose which major version you will use (1, 2...).

When a new minor version or a patch id deployed you will automatically use it but when a new major version is deployed, you will stay on the one you choose in your header.

Add templates

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,
    'carbone-version': '2'
  }
}, (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.

Render reports

POST render.carbone.io/render/:templateId

templateId Unique identifier of the template to use for rendering

Request header

{
  "Content-type": "application/json"
}

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
  enum         : {                // 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
  },
  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.
}

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
}

Nodejs Example

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,
    'carbone-version': '2'
  }
}, (err, response, body) => {
  // Handle error
  // Body contains an error or the render ID
});

Download rendered reports

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 request = require('request');
const fs      = require('fs');

let bufferArray = [];

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

}).on('data', (data) => {
  bufferArray.push(data);
}).on('end', () => {
  fs.writeFileSync('result.pdf', Buffer.concat(bufferArray));
}).on('error', () => {
  // Handle network error
});

Get templates

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';

let bufferList = [];

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

}).on('data', (data) => {
  bufferList.push(data);
}).on('end', () => {
  fs.writeFileSync('./my-file.odt', Buffer.concat(bufferList));
}).on('error', () => {
  // Handle network error
});

Delete templates

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,
    'carbone-version': '2'
  }
}, (err, response, body) => {
  // Handle error
  // Body contains a response
});

PDF export filter options

Options can be passed for PDF conversion. In this case, convertTo have to be an object with formatName set to pdf and formatOptions with options. It is available only on Carbone Render.

{
  convertTo : {
    formatName    : 'pdf',
    formatOptions: {
      EncryptFile          : true,
      DocumentOpenPassword : 'QWERTY1234',
      Watermark            : 'Watermark Carbone.io'
    }
  }
}

The following options can be passed to formatOptions:

Option name Type Default Description
AllowDuplicateFieldNames boolean false Specifies whether multiple form fields exported are allowed to have the same field name. Since: OOo 3.3
CenterWindow boolean false Specifies that the PDF viewer window is centered to the screen when the PDF document is opened.
Changes integer 4 0:Not permitted 1:Inserting, deleting and rotating pages 2:Filling in form fields 3:Commenting, filling in form fields 4:Any except extracting pages
ConvertOOoTargetToPDFTarget boolean false Specifies that the target documents with .od[tpgs] extension, will have that extension changed to .pdf when the link is exported to PDF. The source document remains untouched.
DisplayPDFDocumentTitle boolean true Specifies that the title of the document, if present in the document properties, is displayed in the PDF viewer window title bar.
DocumentOpenPassword string This is the password that allows the user to open the PDF file is "EncryptFile" is set to true.
EnableCopyingOfContent boolean true Specifies that the pages and the document content can be extracted to be used in other documents (copy and paste).
EnableTextAccessForAccessibilityTools boolean true Specifies that the document content can be extracted to be used in accessibility applications.
EncryptFile boolean false If true, selects to encrypt the PDF document with a password. The PDF file can be opened only when the user enters the correct password.
ExportBookmarks boolean true Specifies if bookmarks are exported to PDF.
ExportBookmarksToPDFDestination boolean false Specifies that the bookmarks contained in the source OpenOffice.org file should be exported to the PDF file as Named Destination (see PDF 1.4 section 8.2.1).
ExportFormFields boolean true Specifies whether form fields are exported as widgets or only their fixed print representation is exported.
ExportLinksRelativeFsys boolean false Specifies that the file system related hyperlinks (file:// method) present in the document will be exported as relative to the source document location.
ExportNotes boolean false Specifies if notes are exported to PDF.
ExportNotesPages boolean false Specifies if notes pages are exported to PDF. (Notes pages are available in Impress documents only).
FirstPageOnLeft boolean false Used with the value 3 of the PageLayout property when the first page (odd) should be on the left side of the screen.
FormsType integer 0 Specifies the submitted format of a PDF form. 0:FDF format 1:PDF format 2:HTML format 3:XML format
HideViewerMenubar boolean false Specifies whether to hide the PDF viewer menubar when the document is active.
HideViewerToolbar boolean false Specifies whether to hide the PDF viewer toolbar when the document is active.
HideViewerWindowControls boolean false Specifies whether to hide the PDF viewer controls when the document is active.
InitialPage integer 1 Specifies the page on which a PDF document should be opened in the viewer application.
InitialView integer 0 Specifies how the PDF document should be displayed when opened. 0:meaning neither outlines or thumbnails, 1:meaning the document is opened with outline pane opened, 2:meaning the document is opened with thumbnail pane opened
IsAddStream boolean false Specifies that a stream is inserted to the PDF file which contains the original document for archiving purposes. This option is active only if the PDF Import extension is installed.
IsSkipEmptyPages boolean false Specifies that automatically inserted empty pages are suppressed. This option is active only if storing Writer documents.
Magnification integer 0 Specifies the action to be performed when the PDF document is opened. 0:meaning opens with default zoom magnification. 1:meaning opens magnified to fit the entire page within the window. 2:meaning opens magnified to fit the entire page width within the window. 3:meaning opens magnified to fit the entire width of its boundig box within the window (cuts out margins) 4:means with a zoom level given in the “Zoom” property.
MaxImageResolution integer 300 If the property If the property ReduceImageResolution is set to true all images will be reduced to the given value in DPI. Possible values: 75, 150, 300, 600, 1200
OpenBookmarkLevels integer -1 Specifies how many bookmark levels should be opened in the reader application when the PDF gets opened. -1 means all levels, non-negative numbers mean the respective number of levels.
OpenInFullScreenMode boolean false Specifies that the PDF viewer window is opened full screen, on top of all windows.
PageLayout integer 0 Specifies the page layout to be used when the document is opened. 0:meaning display the pages according to the reader configuration. 1:meaning display one page at a time. 2:meaning display the pages in one column. 3:meaning display the pages in two columns odd pages on the right, to have the odd pages on the left the FirstPageOnLeft properties should be used as well.
PageRange string If this property is set, it indicates the range of pages to be printed. If you want to print all the pages, leave this property unset. If you want to export a selection, leave this property unset, setting only the property Selection.
PDFViewSelection integer 0 Specifies the way the exported PDF will be viewed (experienced) by the user. 0:specifies that the PDF will be exported with all the links external to the document treated as URI. 1:specifies that the PDF will be exported in order to be viewed through a PDF reader application only. Valid only if not exporting to PDF/A-1 (e.g. SelectPdfVersion not set to 1). 2:specifies that the PDF will be exported in order to be viewed through an Internet browser, using the PDF plug-in provided with it. The bookmark of the URI will be rendered compatible with the target bookmark generated with OOo PDF Export feature (see ExportBookmarksToPDFDestination property).
PermissionPassword string This is the password that allows the user to access some permissions restricted if "RestrictPermissions" is set to true.
Printing integer 2 0 :Not permitted. 1 :Low resolution only(150 DPI). 2 :Maximum Resolution allowed.
Quality integer 90 Specifies quality of the JPG export. A higher value results in higher quality and file size. Specifies quality of the JPG export. A higher value results in higher quality and file. 1 :represents lowest value that can be used. The lower the value, the less good is the compression quality and the bigger is be the file size. 100 :represents highest value that can be used. The higher the value, the better is the compression quality and the smaller is the file size. (1 - 100)
ReduceImageResolution boolean false Specifies if the resolution of each image is reduced to the resolution specified by the property MaxImageResolution.
ResizeWindowToInitialPage boolean false Specifies that the PDF viewer window is opened full screen when the document is opened.
RestrictPermissionPassword boolean false If true, selects to restrict some permissions. The permissions can be changed only when the user enters the correct password.
SelectPdfVersion integer 0 Specifies the PDF version to emit. 0 : PDF 1.6 Standard. 1 : PDF/A-1 (ISO 19005-1:2005). 2 : PDF/A-2 (ISO 19005-2:2011). 3 : PDF/A-3 (ISO 19005-3:2012).
UseLosslessCompression boolean false Specifies if graphics are exported to PDF using a lossless compression eg. PNG or if they are compressed using the JPEG format.
UseTaggedPDF boolean false Determines if PDF are created by using special tags also known as Tagged PDF.
UseTransitionEffects boolean false Specifies slide transitions are exported to PDF. This option is active only if storing Impress documents.
Watermark string Specifies the text for a watermark to be drawn on every page of the exported PDF file.
Zoom integer 100 Specifies the zoom level a PDF document is opened with. Only valid if "Magnification" is set to "4".

Carbone Render Node SDK

The SDK to use Carbone render API easily.

It is available on Github: https://github.com/Ideolys/carbone-sdk-node

Install

$ npm i --save carbone-sdk
// OR
$ yarn add carbone-sdk

To use it, you will need your API key you can find on Carbone Account in the API access menu.

Once you have your API key, you can require the module.

const carboneSDK = require('carbone-sdk')('YOUR-API-KEY')

INFO: Each request executed in the SDK is retry once if the first reponse request is a ECONNRESET error

Quickstart

Try the following code to render a report in 10 seconds. Just replace your API key, the template you want to render, add data.

const carboneSDK = require('carbone-sdk')('YOUR-API-KEY');

const data = {
  data: {
    // Add your data here
  },
  convertTo: 'pdf'
}

// Create a write stream with the report name as parameter.
const writeStream = fs.createWriteStream(path.join(__dirname, 'report.odt'))
// Pass the template path as first parameter, in this example 'test.odt' is the template.
// Pass the data object as second parameter.
const carboneStream = carboneSDK.render(path.join(__dirname, 'test', 'datasets', 'test.odt'), data)

carboneStream.on('error', (err) => {
  console.error(err)
})

writeStream.on('close', () => {
  console.log('File rendered')
})

carboneStream.pipe(writeStream)

API

All path you can give to carbone must be absolute path. Use the path module to get it.

const absolutePath = path.join(__dirname, 'path', 'to', 'file.odt')

Add a template

carbone.addTemplate('/absolute/path/to/your/file', (err, templateId) => {

})

WARNING: The file path must be absolute.

You can add multiple times the same template and get different templateId thanks to the payload.

carbone.addTemplate('/absolute/path/to/your/file', 'YOUR-PAYLOAD', (err, templateId) => {

})

Get a template

carbone.getTemplate('templateId', (err, content) => {

})

WARNING: The content returned is a buffer and not a string

You can also get a template with stream.

const writeStream = fs.createWriteStream('tmp.odt')
const carboneStream = carbone.getTemplate('templateId')

carboneStream.on('error', (err) => {

})

writeStream.on('close', () => {
  // Get the real filename here
  let filename = carbone.getFilename(carboneStream)
})

carboneStream.pipe(writeStream)

The only way to get the filename when using stream is to wait the end of the request execution.

Delete a template

carbone.delTemplate('templateId', (err) => {

})

Render a template

There are multiple ways to render a template.

The first way is to use the templateId.

const dataToRender = {}

carbone.render('templateId', dataToRender, (err, buffer, filename) => {

})

Or if you don't want the buffer but juste the link to download it later, you can set the conf like this.

carbone.setOptions({
  isReturningBuffer: false
})

carbone.render('templateId', dataToRender, (err, downloadLink, filename) => {

})

The second way is to use the path of your local file. Using this method is the most safety way to avoid errors. Carbone engine deleted files which has not been used since a while. By using this method, if your file has been deleted, the SDK will automatically upload it again and return you the result.

const dataToRender = {}

carbone.render('/absolute/path/to/your/file', dataToRender, (err, buffer, filename) => {

})

WARNING: If you want to set a payload, it must be located in the data object

const dataToRender = {
  payload: 'MY-PAYLOAD'
}

carbone.render('/absolute/path/to/your/file', dataToRender, (err, buffer, filename) => {

})

You can also render you template and get result with a stream.

const dataToRender = {}

const writeStream = fs.createWriteStream('result.pdf')
const sdkStream = carbone.render('/absolute/path/to/your/file', dataToRender)

sdkStream.on('error', (err) => {

})

writeStream.on('close', () => {
  // Here you can get the real filename
  let filename = carbone.getFilename(sdkStream)
})

sdkStream.pipe(writeStream)

API Promise

All function of the SDK are also available with promise.

Add a template

carbone.addTemplatePromise('/absolute/path/to/your/file', 'OPTIONAL-PAYLOAD')
.then(templateId => {

})
.catch(err => {

})

Get a template

carbone.getTemplatePromise('templateId')
.then(content => {

})
.catch(err => {

})

Delete a template

carbone.delTemplatePromise('templateId', 'OPTIONAL-PAYLOAD')
.then(templateId => {

})
.catch(err => {

})

Render a template

const dataToRender = {}

carbone.renderPromise('/absolute/path/to/your/file', dataToRender)
.then(result => {
  // result.content contains the rendered file
  // result.filename containes the rendered filename
})
.catch(err => {

})

Carbone Render Go SDK

The Carbone Go SDK provides a simple interface to communicate with Carbone Render easily.

It is available on Github: https://github.com/Ideolys/carbone-sdk-go

Install

go get github.com/Ideolys/carbone-sdk-go

Quickstart

Try the following code to render a report in 10 seconds. Just replace your API key, the template you want to render, and the data as a stringified JSON.

package main

import (
    "io/ioutil"
    "log"

    "github.com/Ideolys/carbone-sdk-go/carbone"
)

func main() {
    csdk, err := carbone.NewCarboneSDK("YOUR-ACCESS-TOKEN")
    if err != nil {
        log.Fatal(err)
  }
  // Path to your template
  templateID := "./folder/template.odt"
  // Add your data here
    jsonData := `{"data":{},"convertTo":"pdf"}`
    reportBuffer, err := csdk.Render(templateID, jsonData)
    if err != nil {
        log.Fatal(err)
    }
    err = ioutil.WriteFile("Report.pdf", reportBuffer, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

API

NewCarboneSDK

func NewCarboneSDK(SecretAccessToken ...string) (*CSDK, error)

Function to create a new instance of CSDK (CarboneSDK). The access token can be pass as an argument to NewCarboneSDK (args[0]) or by the environment variable "CARBONE_TOKEN". To set a new environment variable, use the command:

$ export CARBONE_TOKEN=your-secret-token

Check if it is set by running:

$ printenv | grep "CARBONE_TOKEN"

Example

// Carbone access token passed as parameter
csdk, err := carbone.NewCarboneSDK("YOUR-ACCESS-TOKEN")
// Carbone access token passed as environment variable "Carbone TOKEN"
csdk, err := carbone.NewCarboneSDK()

Render

func (csdk *CSDK) Render(pathOrTemplateID string, jsonData string, payload ...string) ([]byte, error)

The render function takes pathOrTemplateID the path of your local file OR a templateID, jsonData a stringified JSON, and an optional payload.

It returns the report as a []byte. Carbone engine deleted files that have not been used for a while. By using this method, if your file has been deleted, the SDK will automatically upload it again and return you the result.

When a template file path is passed as an argument, the function verifies if the template has been uploaded to render the report. If not, it calls AddTemplate to upload the template to the server and generate a new template ID. Then it calls RenderReport and GetReport to generate the report. If the path does not exist, an error is returned.

When a templateID is passed as an argument, the function renders with RenderReport then call GetReport to return the report. If the templateID does not exist, an error is returned.

Example

reportBuffer, err := csdk.Render("./templates/invoice.docx", `{"data":{"nane":"eric"},"convertTo":"pdf"}`, "OptionalPayload1234")
if err != nil {
    log.Fatal(err)
}
// create the file
err = ioutil.WriteFile("Report.pdf", reportBuffer, 0644)
if err != nil {
    log.Fatal(err)
}

AddTemplate

func (csdk *CSDK) AddTemplate(templateFileName string, payload ...string) (APIResponse, error)

Add the template to the API and returns an APIResponse struct (that contains a TemplateID). You can add multiple times the same template and get different templateId thanks to the optional payload.

Example

resp, err := csdk.AddTemplate("./tests/template.test.odt")
if err != nil {
    t.Error(err)
}
if resp.Success == false {
    t.Error(resp.Error)
}
if len(resp.Data.TemplateID) <= 0 {
    t.Error(errors.New("templateId not returned from the api"))
}
fmt.Println("templateID:", resp.Data.TemplateID)

GetTemplate

func (csdk *CSDK) GetTemplate(templateID string) ([]byte, error)

Pass a templateID to the function and it returns the template as []byte. The templateID must exist otherwise an error is returned by the server.

    templateData, err := csdk.GetTemplate("TemplateId")
    if err != nil || len(templateData) <= 0 {
        t.Error(err)
    }
    err = ioutil.WriteFile(filename, templateData, 0644)
    if err != nil {
        t.Error(err)
    }

DeleteTemplate

func (csdk *CSDK) DeleteTemplate(templateID string) (APIResponse, error)

Example

resp, err := csdk.DeleteTemplate(templateID)
if err != nil {
    t.Error(err)
}
if resp.Success == false {
    t.Error(resp.Error)
}

GenerateTemplateID

func (csdk *CSDK) GenerateTemplateID(filepath string, payload ...string) (string, error)

The Template ID is predictable and idempotent, pass the template path and it will return the templateID. You can get a different templateId thanks to the optional payload.

SetAccessToken

func (csdk *CSDK) SetAccessToken(newToken string)

It sets the Carbone access token.

SetAPIVersion

func (csdk *CSDK) SetAPIVersion(version int)

It sets the the Carbone version requested. By default, it is calling the version 2 of Carbone.

Note: You can only set a major version of carbone.

GetAPIVersion

func (csdk *CSDK) GetAPIVersion() (int, error)

It returns the Carbone version.

Carbone Render Python SDK

The Carbone Python SDK provides a simple interface to communicate with Carbone Render easily.

It is available on Github: https://github.com/Ideolys/carbone-sdk-python

Install

$ pip install carbone-sdk

Quickstart

Try the following code to render a report in 10 seconds. Just replace your API key, the template you want to render, and the data object.

import carbone_sdk

csdk = carbone_sdk.CarboneSDK("ACCESS-TOKEN")

template_path = "./path/to/template.odt"
json_data = {
  # Add the data here
  "data": {}
}

# Render and return the report as bytes and a unique report name
report_bytes, unique_report_name = csdk.render(template_id, json_data)

# Create the file
fd = open(unique_report_name, "wb")
fd.write(report_bytes)
fd.close()

API

CarboneSDK Constructor

import carbone_sdk

# Carbone access token passed as parameter
csdk = carbone_sdk.CarboneSDK("ACCESS-TOKEN")
# Carbone access token passed as environment variable "CARBONE_TOKEN"
csdk = carbone_sdk.CarboneSDK()

Constructor to create a new instance of CarboneSDK. The access token can be pass as an argument or by the environment variable "CARBONE_TOKEN". To set a new environment variable, use the command:

$ export CARBONE_TOKEN=your-secret-token

Check if it is set by running:

$ printenv | grep "CARBONE_TOKEN"

Render

def render(self, file_or_template_id = None, json_data = None, payload = "")

The render function takes file_or_template_id the path of your local file OR a template ID, json_data a stringified JSON, and an optional payload.

It returns the report as a bytes and a unique report name as a string. Carbone engine deletes files that have not been used for a while. By using this method, if your file has been deleted, the SDK will automatically upload it again and return you the result.

When a template file path is passed as an argument, the function verifies if the template has been uploaded to render the report. If not, it calls add_template to upload the template to the server and generate a new template ID. Then it calls render_report and get_report to generate the report. If the path does not exist, an error is returned.

When a template ID is passed as an argument, the function renders with render_report then call get_report to return the report. If the template ID does not exist, an error is returned.

Example

import carbone_sdk

csdk = carbone_sdk.CarboneSDK("your_access_token")

template_path = "./templates/invoice.docx"
json_data = {
  # Add the data here
  "data": {
    "firstname": "John",
    "lastname": "Wick",
    "price": 1000
  },
  "convertTo": "pdf"
}

# Render and return the report as bytes and a unique report name
try:
  report_bytes, unique_report_name = csdk.render(template_path, json_data)
except Exception as err:
  print("Something went wrong: {0}".format(err))

# Create the invoice report
fd = open(unique_report_name, "wb")
fd.write(report_bytes)
fd.close()

add_template

def add_template(self, template_file_name = None, payload = "")

Add the template to the API and returns the response (that contains a template_id). You can add multiple times the same template and get different template ID thanks to the optional payload.

Example

import carbone_sdk

csdk = carbone_sdk.CarboneSDK("your_access_token")

try:
  resp = csdk.add_template('./tests/template.test.odt', 'salt1234')
  print("Template ID: " + resp['data']['templateId'])
except Exception as err:
  print("Something went wrong: {0}".format(err))

get_template

def get_template(self, template_id = None)

Pass a template ID to the function and it returns the template as bytes. The template ID must exist otherwise an error is returned by the server.

import carbone_sdk

csdk = carbone_sdk.CarboneSDK("your_access_token")

try:
  f = csdk.get_template("cb03f7676ef0fbe5d7824a64676166ac2c7c789d9e6da5b7c0c46794911ee7a7")
  fd = open("template.odt", "wb")
  fd.write(f)
  fd.close()
except Exception as err:
  print("Something went wrong: {0}".format(err))

delete_template

def delete_template(self, template_id = None)

Example

import carbone_sdk

csdk = carbone_sdk.CarboneSDK("your_access_token")

try:
  resp = csdk.delete_template("template_id")
  print(resp)
except Exception as err:
  print("Something went wrong: {0}".format(err))

generate_template_id

def generate_template_id(self, template_file_name = None, payload = "")

The Template ID is predictable and idempotent, pass the template path and it will return the template_id. You can get a different template ID thanks to the optional payload.

set_access_token

def set_access_token(self, api_token = None)

It sets the Carbone access token.

set_api_version

def set_api_version(self, api_version = None)

It sets the the Carbone version requested. By default, it is calling the version 2 of Carbone.

Note: You can only set a major version of carbone.