Carbone JS API

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 generations, data formatting, and more! It does not contain Enterprise features*.
  • All export formats: DOCX, PDF, XLSX, ODS, ODG, XML, HTML, and more!
  • Apache License: The source code is open source on Github.
  • Support: Create an issue on Github
  • Tutorial: Access the CarboneJS quickstart.

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

Minimum Requirements

  • NodeJS 8.x+
  • Runs on OSX, Linux, and Docker Containers
  • 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).
Consider using Carbone Cloud API if you want a Ready-to-use, Secured and High Available solution.

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',           // 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
    }
  }
}

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.convert

Convert a file to another format.

carbone.convert(fileBuffer, options, callback);

Arguments

  • fileBuffer: Buffer returned by fs.readFile (no utf-8)
  • options: carbone.render options
  • callback: Callback function with 2 arguments: (err, result) result is the file converted as a buffer

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

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 tags or variables to formatters as parameter.

carbone.decodeOuputFilename()

When options.renderPrefix is used, the returned filename can be parsed with this function. It decodes the filename an returns an object with two parameters

{
  extension  : 'pdf',                // output file extension
  reportName : 'decoded report name' // reportName
}

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

Carbone Cloud API

Introduction

Carbone Cloud API is a secure, fast, high-availability REST API serving Carbone anywhere in the world.
Generate documents through HTTP requests from any applications, services, or languages.
The Cloud API provides community and enterprise features.

Requirements

  • Create a Carbone Cloud account or sign-in: https://account.carbone.io/
  • For testing purposes, use a test API key: Generate unlimited watermarked PDFs for free (Only PDF file format).
  • For production purposes, use a production API key: Generate any document formats without a watermark. The free Sandbox Plan plan is available, giving you 100 credits per month. If you need more credits, you can upgrade your subscription.

Quickstart & API Flow

To generate a document, you have to:

  1. Upload a template to get a template ID. The template is stored in your personal template storage.
  2. Generate a report from the template ID and a JSON dataset, then the request returns a unique usable render ID.
  3. Download the report thanks to the render ID.
  4. To get a new document, repeat the process from point 2.

Test the API with Carbone Cloud API quickstart

API Integration

Nocode & Automation

Software Development Kits

SDKs are available to integrate the Carbone Cloud API into your service/application in a few lines of code:

API Clients for Windows / MacOS / Linux

To test the Cloud API in a few minutes, load a pre-made API specification into:

Terminal

Template storage

Templates are your documents' base design. It will include static and dynamic content thanks to Carbone tags {d.value}. Each subscription gives access to a storage space to store all your templates and identify them with a template ID.

Based on the API key, the template storage retention behave differently:

  • When a template is uploaded with a production token, it is stored for an unlimited time on your template storage. It is possible to upload a non-persistent template that will be deleted automatically by adding the header carbone-template-delete-after with days in seconds (86400s = 1 day, max 30 days).
  • When a template is uploaded with a test token, it is deleted automatically within 30 days.

Learn more about your template storage on the help center.

Template ID generation

The Template ID is predictable and idempotent SHA256 hash, computed from the template content in hexadecimal. NodeJS example:

const crypto = require('crypto');

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

Report storage

When a document is generated thanks to a template ID and a JSON dataset, a render ID is provided to download a file. The document and URL are available for one hour, and can be downloaded one time.

They are deleted automatically when:

  • The document is downloaded.
  • After one hour.

To get the same document, you must generate a new document and get a new render ID.

API Base URL

The Carbone API base URL is https://api.carbone.io since summer 2022.
Before this date, the URL was https://render.carbone.io and it will continue to be operational today and in the future.

API timeout

The rendering timeout default value is 60 seconds, and it may throw if the report contains:

  • More than a hundred PDF pages are rendered
  • High-quality images.
  • Many pages and many images.

If a timeout is thrown, consider using asynchronous rendering with webhooks, asynchronous rendering is 5 minutes.
If a generation is longer than 5 minutes, contact the support.

API Webhook

An asynchronous rendering is available, Carbone will notify your application/service at a custom URL as soon as the document is generated. For webhooks, the rendering timeout default value is 5 minutes. To enable it:

  • On your server, add webhook endpoint listening to a POST request.
  • When generating a report with the request POST /render/:templateId, add the header carbone-webhook-url with your webhook URL as a value.

If errors is returned from your server, the webhook is requested again. The retry is executed only for the following errors:

  • Status Code Errors: 408, 429, 502, 503, 504, 521, 522, 524
  • Socket Errors: 'ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN'

API Rate Limits

When you generate documents through POST https://api.carbone.io/render/:templateID: the maximum number of parallel request is 20 per IP. Above that number, a HTTP status code 429 indicates that too many requests have been sent in parallel.

The rate limit will involved in the coming months, and it will depends on:

  • The duration to generate a document
  • The number of parallel requests
  • Your Carbone Cloud subscription pricing

This status code prevents abuse by limiting the number of requests users can make in a given timeframe. Developers and users can ensure a smoother experience by implementing strategies like exponential backoff to handle these limits gracefully.

API version

By default, HTTP requests target the latest version of the Cloud API. It is recommended to specify an API version by providing the HTTP header carbone-version, such as: { "carbone-version": 4 }. Supported values:

Only a major version can be specified, and it will include all upcoming minor versions or patches.

Examples

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

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

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

Add templates

POST api.carbone.io/template

Endpoint to upload a template.

When a template is uploaded, a template ID is created, representing the unique identifier of the file. If you download the same model twice, you will have the same template ID.

The returned template ID can be used for:

Request body

The body request should be either:

  • Solution 1 : A FormData object that contains the template as a Buffer or as a Blob for vanilla javascript. On the FormData object, assign the file to the attribute template. The request header must include {"content-type": "multipart/form-data" }.
  • Solution 2 : A JSON object that contains the template as a base64 String { "template" : "pure base64 or a base64 data-URI"}. The request header must include {"content-type": "application/json" }.
{
  template : ''  // File content
}

Responses

A JSON is returned as body response.
On success, the templateId is returned.

Status Code Body
🟒 200 { "success" : true, "data" : { "templateId" : "" } }
πŸ”΄ 400 { "success" : false, "error" : "Cannot store template" }
πŸ”΄ 400 { "success" : false, "error" : "Content-Type header should be multipart/form-data or application/json" }
πŸ”΄ 401 { "success" : false, "error" : "Unauthorized, please provide a correct API key on the "Authorization" header"}
πŸ”΄ 415 { "success" : false, "error" : "Template format not supported" }
πŸ”΄ 422 { "success" : false, "error" : ""template" field is empty" }

NodeJS Example

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

const bearerToken = 'YOUR_TOKEN';

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

Render reports

POST api.carbone.io/render/:templateId

Endpoint to generate a report from a template ID, a unique template identifier, and a JSON data-set.

Request header

{
  "Content-type": "application/json",
  "carbone-webhook-url": "OPTIONAL - asynchronous rendering with **webhooks**, pass the URL a server listening to a POST request"
}

Request body

{
  "data"         : {},              // Required - ️JSON data-set merged into the template to generate a document
  "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",            // 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 - Predefine alias, related documenation: https://carbone.io/documentation.html#alias
  "reportName"   : "{d.date}.odt",  // Optional - Static or dynamic file name returned on the `content-disposition` header when the generated report is fetched with `GET /report/:renderId`. Multiple Carbone tags are accepted, such as `{d.type}-{d.date}.pdf`
  "enum"         : {                // Optional - List of enumerations, use it in reports with `convEnum` formatters, documentation: https://carbone.io/documentation.html#convenum-type-
    "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" : {"one":"un" },
    "es" : {"one":"uno"}
  },
  "currencySource" : "EUR",         // Optional - Currency source coming from your JSON data. The option is used by `formatC` to convert the currency based on the `currencyTarget` and `currencyRates`. Learn more: https://carbone.io/documentation.html#formatc-precisionorformat-
  "currencyTarget" : "USD",         // Optional - Target currency when the document is generated. The option is used by `formatC` to convert the currency based on the `currencySource` and `currencyRates`. Learn more: https://carbone.io/documentation.html#formatc-precisionorformat-
  "currencyRates"  : {              // Optional - Currency exchange rates for conversions from `currencySource` to `currencyTarget`. Learn more: https://carbone.io/documentation.html#formatc-precisionorformat-
    "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.
}

Response

A JSON is returned as body response.
On success, the renderId is returned.

Status Code Body
🟒 200 { "success" : true, "data": { "renderId": "" } }
πŸ”΄ 400 { "success" : false, "error" : ""Content-Type" header is not "application/json""}
πŸ”΄ 400 { "success" : false, "error" : "Invalid templateId"}
πŸ”΄ 401 { "success" : false, "error" : "Unauthorized, please provide a correct API key on the "Authorization" header"}
πŸ”΄ 404 { "success" : false, "error" : "Template not found"}
πŸ”΄ 413 { "success" : false, "error" : "Content too large, the JSON size limit is X MB"}
πŸ”΄ 422 { "success" : false, "error" : "Missing "data" property in body"}
πŸ”΄ 429 { "success" : false, "error" : "Maximum 100 parallel requests per IP is allowed."}
πŸ”΄ 500 { "success" : false, "error" : "Error while rendering template"}
πŸ”΄ 500 { "success" : false, "error" : "Error while setting up the webhook"}

Nodejs Example

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

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

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

Download rendered reports

GET api.carbone.io/render/:renderId

Endpoint to retreive a generated document from a render ID, a unique identifier for rendered files.

Response

On success, the file is returned.
On error, a JSON is returned with details of the problem.

Status Code Body
🟒 200 File stream
πŸ”΄ 400 { "success" : false, "error" : "Invalid renderId"}
πŸ”΄ 404 { "success" : false, "error" : "File not found"}

Examples

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

let bufferArray = [];

request.get({
  url : 'https://api.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 api.carbone.io/template/:templateId

Endpoint to download a template from a template ID, a unique identifier for templates.

Response

On success, the file is returned.
On error, a JSON is returned with details of the problem.

Status Code Body
🟒 200 File stream
πŸ”΄ 400 { "success" : false, "error" : "Invalid templateId"}
πŸ”΄ 400 { "success" : false, "error" : "Cannot retrieve template"}
πŸ”΄ 401 { "success" : false, "error" : "Unauthorized, please provide a correct API key on the "Authorization" header"}
πŸ”΄ 404 { "success" : false, "error" : "Template not found"}

Examples

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

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

let bufferList = [];

request.get({
  url : 'https://api.carbone.io/template/' + templateId,
  headers : {
    'Authorization': 'Bearer ' + bearerToken,
    'carbone-version': '4'
  }
}).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 api.carbone.io/template/:templateId

Endpoint to delete a template from a template ID, a unique identifier for templates.

Response

A JSON is returned as body response.
On success, a status code 200 is returned.

Status Code Body
🟒 200 { "success" : true }
πŸ”΄ 400 { "success" : false, "error" : "Invalid templateId"}
πŸ”΄ 400 { "success" : false, "error" : "Cannot delete template"}
πŸ”΄ 401 { "success" : false, "error" : "Unauthorized, please provide a correct API key on the "Authorization" header"}
πŸ”΄ 404 { "success" : false, "error" : "Template not found"}

Examples

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

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

request.delete({
  url : 'https://api.carbone.io/template/' + templatedId,
  headers : {
    'Authorization': 'Bearer ' + bearerToken,
    'carbone-version': '4'
  }
}, (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.

{
  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
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). 15 : PDF 1.5 Standard. 16 : PDF 1.6 Standard.
PDFUACompliance boolean false Specifies the PDF/UA Universal Accessibility standard (ISO 14289)
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. To enable this option, you must also define "RestrictPermissions": true and define a password with "PermissionPassword": "RandomPassword1234"
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.
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 true 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. To enable this option, you must also define "RestrictPermissions": true and define a password with "PermissionPassword": "RandomPassword1234"
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.
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.
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 true 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 option is set to 4.

Image export filter options

It is possible to export jpg or png images with options (list bellow).

Export Types Option name Type Default Description
jpg / png PixelWidth Number Document width Image width as pixels
jpg / png PixelHeight Number Document height Image height as pixels
jpg / png ColorMode Number 0 0 Colors, 1 Greyscale
jpg Quality Number 100 From 1 (low quality, high compression, low size) to 100 (high quality, low compression, high size)
png Compression Number 0 From 0 (compression disabled) to 9 (high compression, low size)
png Interlaced Number 0 0 not interlaced, 1 enterlaced (higher size)

Here is an example of exporting a JPG image with options:

{
  convertTo: {
    formatName : 'jpg',
    formatOptions: {
      Quality   : 50,
      ColorMode : 1
    }
  }
}

Carbone Cloud CURL

CURL can be use to generate reports. The following commands can be executed on any terminal to request the Carbone Cloud API. It is containing uppercase tags that have to be replaced, such as:

  • API_KEY: Your test or production API key, login on https://account.carbone.io to get it.
  • TEMPLATE_ID: The template ID returned by the add template request.
  • RENDER_ID: The render ID returned after rendering a report.
  • FILENAME: The filename used to create the report or template just downloaded.
  • ABSOLUTE_FILE_PATH: The absolute path of a template.
  • BASE64_STRING: Template as a pure base64 string or a base64 data-URI.

Add a templates with Curl

A template must be uploaded to get a template ID, it can be done by providing:

  • the file absolute path, in this case, the request body is a Form-Data object (e.g. Example 1).
  • the template as a base64 string, in this case, the request body is a JSON object (e.g. Example 2).

Example 1 - Add a template with the absolute file path

curl --location --request POST 'https://api.carbone.io/template' \
--header 'carbone-version: 4' \
--header 'Expect:' \
--header 'Content-Type: multipart/form-data' \
--header 'Authorization: Bearer API_KEY' \
--form 'template=@"ABSOLUTE_FILE_PATH"'

Example 2 - Add a template with the file as a base64 String

curl --location --request POST 'https://api.carbone.io/template' \
--header 'carbone-version: 4' \
--header 'Expect:' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer API_KEY' \
--data-raw '{ "template": "BASE64_STRING" }'

Get a template with Curl

curl --location --request GET 'https://api.carbone.io/template/TEMPLATE_ID' \
--header 'carbone-version: 4' \
--header 'Authorization: Bearer API_KEY' \
-o 'FILENAME.docx'

Delete a template with Curl

curl --location --request DELETE 'https://api.carbone.io/template/TEMPLATE_ID' \
--header 'carbone-version: 4' \
--header 'Authorization: Bearer API_KEY'

Render a report with Curl

Learn more about rendering options and PDF export options.

curl --location --request POST 'https://api.carbone.io/render/TEMPLATE_ID' \
--header 'carbone-version: 4' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer API_KEY' \
--data-raw '{ "data": { "firstname": "John", "lastname": "Wick" }, "convertTo": "pdf" }'

Download a report with Curl

The command downloads the generated report into the file "FILENAME.pdf". If an error occurs (status 4XX or 5XX), the error is also saved into the file. Each render ID can be downloaded only one time.

curl --location --request GET 'https://api.carbone.io/render/RENDER_ID' \
--header 'carbone-version: 4' \
-o 'FILENAME.pdf'

Carbone Cloud Node SDK

Node SDK to generates reports through the Carbone Cloud API in few lines of codes.

The source code is available on Github: https://github.com/carboneio/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 generate a report in few seconds. Insert an API key, provide the template, and the data as a stringified JSON, that's it.

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)

Carbone version

You can set the version of Carbone you want to use. With this, you can upgrade your carbone version when you are ready.

To set the version, call this function:

carbone.setApiVersion(2) // Set the version of carbone to 2

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

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 Cloud Go SDK

Golang SDK to generate reports through the Carbone Cloud API in few lines of codes.

The source code is available on Github: https://github.com/carboneio/carbone-sdk-go

Install

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

Quickstart

Try the following code to generate a report in few seconds. Insert an API key, provide the template, and the data as a stringified JSON, that's it.

package main

import (
    "io/ioutil"
    "log"

    "github.com/carboneio/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 Cloud Python SDK

Python SDK to generate reports through the Carbone Cloud API in few lines of codes.

The source code is available on Github: https://github.com/carboneio/carbone-sdk-python

Install

$ pip install carbone-sdk

Quickstart

Try the following code to generate a report in few seconds. Insert an API key, provide the template, and the data as a stringified JSON, that's it.

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 (for example "01EEYYHV0ENQE07JCKW8BD2QRP.odt")
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')
  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.

Carbone Cloud Javascript SDK

The Carbone Cloud Javascript SDK is used to generate reports easily from a client side service (Angular, Vuejs, Svelte, React, Ember.js).

The source code is available on Github: https://github.com/carboneio/carbone-sdk-js

Install

npm install --save carbone-sdk-js

or

yarn add carbone-sdk-js

Quickstart

Try the following code to generate a report in few seconds. Insert an API key, provide the template, and the data as a stringified JSON, that's it.

import carboneSDK from "carbone-sdk-js";
// SDK constructor, the access token have to be passed as an argument to carboneRenderSDK
const _carboneService = carboneSDK("eyJhbGc...");
// Template from a file input OR template ID
const _template = document.getElementById("inputFile").files[0];
// Data from an input, for example: {"data" :{"firstname":"John","lastname":"Wick"},"convertTo":"pdf"}
let _data = JSON.parse(document.getElementById("inputData").value);
// Render the report from an DOCX template and a JSON Data
_carboneService.render(_template, _data).then(({ content, name }) => {
  // name == report name as a String
  // content == report content as a Blob, it can be used to download the file
});

API

CarboneSDK Constructor

Instanciate the SDK with:

import carboneSDK from "carbone-sdk-js";
// SDK constructor, the access token have to be passed as an argument to carboneRenderSDK
const _carboneService = carboneSDK("eyJhbGc...");

Or, the SDK is available through the global window variable.

// Carbone access token passed as parameter
const _carboneService = window.carboneSDK("eyJhbGc...");

Render

async function render(templateIdOrFile, data, payload = "", responseType = "blob");

The render function takes templateIdOrFile a File/Blob from an input OR a template ID, data JSON (not stringified), an optional payload, and an optional responseType which correspond to the type of the response.

It returns the report as a Blob by default 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 render function upload automatically the template again and return the result.

When a File or Blob 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. Then it calls renderReport and getReport to generate the report.

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

addTemplate

async function addTemplate (file, payload = '');

The function adds the template to the API and returns the response (that contains a templateId). The file argument is a type File or Blob. You can add multiple times the same template and get different template ID thanks to the optional payload.

Example

const carboneService = window.carboneRenderSDK("eyJhbGc...");

carboneService.addTemplate(file).then(data => {
  if (data.success === true) {
    // templateId: data.data.templateId
  } else {
    // error: data.error
  }
});

getTemplate

async function getTemplate(templateId, responseType = "blob");

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

const carboneService = window.carboneRenderSDK("eyJhbGc...");

carboneService.getTemplate("templateId").then(file => {
  // `file` is Blob type
});

deleteTemplate

async function deleteTemplate(templateId);

Delete a template from a templateId.

Example

const carboneService = window.carboneRenderSDK("eyJhbGc...");

carboneService.deleteTemplate("templateId").then(resp => {
  if (resp.success === false) {
    throw new Error(resp.error);
  }
});

generateTemplateId

async function generateTemplateId(fileContent, payload = "");

The Template ID is predictable and idempotent, pass the template path and it will return the templateId. Different template ID can be returned thanks to the optional payload.

setAccessToken

function setAccessToken(newToken)

It sets the Carbone access token.

setApiVersion

function setApiVersion(version)

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.

Carbone Cloud PHP SDK

PHP SDK to generate documents (PDF DOCX ODT XLSX ODS XML ...) through the Carbone Cloud API

The source code is available on Github: https://github.com/carboneio/carbone-sdk-php

Install

composer require carboneio/carbone-sdk-php

API

Carbone instance

Start creating a new instance of the Carbone class and provide your private API key. Get your API key on your Carbone account: https://account.carbone.io/.

use Carboneio\SDK\Carbone;

$carbone = new Carbone('YOUR_API_KEY');

Upload a template

You can upload a template to Carbone using the upload method. This method takes the content of the template as base64. The method returns a template ID used to render a template.

$response = $carbone->templates()->upload($contentBase64);

$templateId = $response->getTemplateId();

Example to upload a template

Render a template

You can generate a document using the render method. This method takes the template Id and the data as parameters. A render ID is returned and must be used to download the generated document.

$response = $carbone->renders()->render($templateId, $data);

$renderId = $response->getRenderId();

Example to render a template

Download a rendered template

You can download a rendered template using the download method. This method takes the render ID as a parameter.

$response = $carbone->renders()->download($renderId);

// Save the contents of the file yourself on your filesystem
$content = $response->getContent();

Example to download a rendered document

Delete a template

You can delete a template using the delete method. This method takes the template Id as a parameter.

$response = $carbone->templates()->delete($templateId);

Example to delete a template

Download a template

You can download a template using the download method. This method takes the template Id as a parameter.

$response = $carbone->templates()->download($templateId);

Example to download a template

Add custom headers

Set custom headers, such as "carbone-version" to select a specific Carbone version. By default, the SDK request the version 4 of Carbone.

$carbone->setHeaders([
  "carbone-version" => 4,
  /** Uncomment to delete automatically templates after a specific time */
  // "carbone-template-delete-after" => 86400 // 86400s = 1 day
]);

Get API Status

$response = $carbone->getStatus();
$json = $response->json();

echo "Status : " . $response->status() . "\n";
echo "Success: " . $json['success'] . "\n";
echo "Version: " . $json['version'] . "\n";
echo "Message: " . $json['message'] . "\n";