HTTP API

Generate reports

HTTP API to merge the data in your template

Generate a report

/render/{templateId}

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

Request header

{
  // Required Pass your API token here (string)
  "authorization"       : "Bearer API_TOKEN",
  // Required Content-type (string)
  "content-type"        : "application/json",
  // Webhook for asynchronous rendering (string)
  // Called by Carbone when the report is generated
  "carbone-webhook-url" : "http://your-url",
  // Webhook custom headers (string)
  "carbone-webhook-header-X" : "headers value"
}

Request body

{
  // Required Data that is merged into the template with tags {d.} (array|object)
  "data"         : {},
  // Output file format. More info (string|object)
  "convertTo"    : "pdf",
  // Convert document dates to a timezone. More info (string)
  "timezone"     : "Europe/Paris",
  // Locale of the generated document. More info (string)
  "lang"         : "en-us",
  // Extra data object that can be merged into the template with tags {c.} (object)
  "complement"   : {},
  // Predefined alias TODO put the link to the alais doc in designer (string)
  "variableStr"  : "{#def = d.id}",
  // Static or dynamic file name returned on the `content-disposition` header. More info (string)
  "reportName"   : "{d.date}.odt",
  // List of enumerations with to use with convEnum formatter (object)
  "enum"         : {
    "ORDER_STATUS" : ["open", "close"],
    "SPEED" : {
      "10" : "slow",
      "20" : "fast"
    }
  },
  // Localization dictionary to use with Carbone tags `{t( )}`. More info (object)
  "translations" : {
    "fr-ca" : {"one":"un" },
    "es"    : {"one":"uno"}
  },
  // Currency source coming from your JSON data. More info (string)
  "currencySource" : "EUR",
  "currencyTarget" : "USD",
  // More info (object)
  "currencyRates"  : {
    "EUR" : 1,
    "USD" : 1.1403
  },
  // Force the report to recomppute pagination & table of content. TODO add info (boolean)
  "hardRefresh": false,
  // Generate multiple reports with one template and multiple JSON objects #
  "batchSplitBy" : "d.items"
}

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"}
500 { "success" : false, "error" : "Error while rendering template"}
500 { "success" : false, "error" : "Error while setting up the webhook"}

Curl Example

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

Output filename

With Carbone, even the generated report filename is a template!

This filename is returned content-disposition header when the generated report is fetched with GET /report/:renderId.

Output file type

By default, if convertTo is undefined, the output file type is the same as the input template file type.

The table below list all accepted convertTo values according to the input template file type.

And some output file types can have additional options. See the dedicated documentation

Template Type convertTo
document pdf, docx, odt, bib, doc, doc6, doc95, docbook, docx7, fodt, html, latex, mediawiki, odt, ooxml, ott, pdb, psw, rtf, sdw, sdw4, sdw3, stw, sxw, text, txt, uot, vor, vor4, vor3, xhtml, jpg, jpeg, png, epub
spreadsheet pdf, xlsx, ods, csv, dbf, dif, fods, html, ooxml, ots, pxl, sdc, sdc4, sdc3, slk, stc, sxc, uos, vor3, vor4, vor, xhtml, xls, xls5, xls95, xlt, xlt5, xlt95
presentation pdf, pptx, odp, bmp, emf, eps, fodp, gif, html, jpg, met, odg, pbm, pct, pgm, png, ppm, pwp, ras, sda, sdd, sdd3, sdd4, sxd, sti, svg, svm, swf, sxi, tiff, uop, vor, vor3, vor4, vor5, wmf, xhtml, xpm, , otp, potm, pot, pps, ppt
web pdf, etext, html10, html, mediawiki, sdw3, sdw4, sdw, txt, text10, text, vor4, vor
graphics bmp, emf, eps, fodg, gif, html, jpg, met, odd, otg, pbm, pct, pdf, pgm, png, ppm, ras, std, svg, svm, swf, sxd, sxd3, sxd5, sxw, tiff, vor, vor3, wmf, xhtml, xpm

Notes:

Multi-timezone

Some dates formatter like formatD or formatI adapt the inserted date in the template according to the timezone.

List of accepted timezone (Column TZ identifier) : https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Multi-language

Many text, dates, numbers formatters like formatN,formatD,formatI` adapt the inserted date in the template according to the locale.

Also, the lang parameter is used to select the correponding translations when the Carbone tag {t()} is used for multi-lingual reports.

List of supported locales: https://github.com/carboneio/carbone/blob/master/formatters/_locale.js

You can support multiple languages in your report by using translations formatters.

Multi-currency

You can also create templates that support multiple devices depending on the locale.

The option is used by formatC to convert the currency based on the currencyTarget and currencyRates. Target currency when the document is generated. The option is used by formatC to convert the currency based on the currencySource and currencyRates. Currency exchange rates for conversions from currencySource to currencyTarget. Learn more

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

JPG/PNG 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)
png Translucent Number 0 0 no transparent background, 1 transparent brackground

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

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

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

Asynchronous jobs

When the report is huge, we highly recommend employing the asynchronous rendering system. This method offers a longer rendering timeout of 5 minutes, surpassing the 60-second limit of the synchronous API.

Carbone will notify your application/service at a custom URL as soon as the document is generated.

How to use this system?

  1. Prepare your server to accept POST requests at a webhook endpoint. For experimentation, https://webhook.site/ is a convenient option.
  2. Send a request to POST /render/:templateId with the HTTP header carbone-webhook-url: https://my-custom-webhook/my-custom-url
  3. (From version 4.23.0) If your webhook url needs authentication or a specific header, you can configure it by adding the header carbone-webhook-header-X. Ex : carbone-webhook-header-authorization: my-secret
  4. Upon report completion, Carbone will invoke your webhook endpoint, sending a JSON object that includes the renderId. The response object is the same as the response from the synchronous method.

Carbone automatically retries (one retry) to call your webhook 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
  • Request Timeout (16 seconds max)

Batch processing

Starting from version 4.20.0, Carbone introduces the capability to generate multiple reports in one go using a single HTTP request, with the same template. This feature streamlines the creation of reports, especially when dealing with bulk data, by returning a compressed ZIP file that contains all generated reports.

Batch processing is particularly useful for generating personalized documents, such as letters or invoices, for multiple recipients simultaneously.

Batch processing is enabled if all of the following conditions are met

  • Include the batchSplitBy attribute in the POST /render/:templateId request (see below).
  • Utilize asynchronous job processing by setting the carbone-webhook-url HTTP header in your request (see above).
  • Only for Cloud: Ensure the data payload contains a non-empty array with up to 100 objects (= 100 reports)
  • Only for On-Premise: The global configuration parameter nbReportMaxPerBatch is greater than 0.

API Request Example

To initiate batch processing, send a JSON object structured as follows:

{
  "data"         : {
    "letters" : [
      { "id" : 1, "name" : "John"   },
      { "id" : 2, "name" : "David"  },
      { "id" : 2, "name" : "Steeve" }
    ]
  },
  // The result will be a ZIP file of multiple PDFs
  "convertTo"    : "pdf",
  // Batch processing option.
  "batchSplitBy" : "d.letters"
}

batchSplitBy determines how the batch is split. Accepted values:

  • "d" if data is an array of objects, resulting in one report per object.
  • "d.myCustomField" to select a direct child array of "data", resulting in one report per object in that array.

Template Writing Methods

When writing templates for batch processing, you can employ two approaches. Carbone automatically detects the method used.

  1. Direct child access: Write the template directly at the d.letters[] level, using placeholders for each data field.

     {d.id} {d.name}
  2. Array access: Write the template at the root level d. For each report, Carbone generates an array containing a single object, thereby producing one report for every object within d.letters.

     {d.letters[i].id}    {d.letters[i].name}
     {d.letters[i+1].id}

Download report with single API call

Add a new option to the API endpoint POST /render/:idTemplate. The query parameter ?download=true can be used to download the rendered report directly.

When this option is used, the file is not stored on our servers. A single API call is enough to download the file. There is no need to call GET /render.

Important: The Content-Disposition header changes based on the HTTP status: If the status is 200 (OK):

  Content-Disposition: 'attachment; filename="report.pdf"'
  Content-Type: 'application/pdf'

For all other statuses: The response remains in application/json format as before.