### Start Carbone On-premise Web Server Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Command to start the Carbone On-premise web server, optionally enabling the studio interface. This command is executed after binary preparation and license configuration. ```bash ./carbone-ee webserver --studio ``` -------------------------------- ### Carbone API Webhook Integration Guide Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/http-api/introduction Detailed guide on configuring and utilizing Carbone.io webhooks for asynchronous document rendering, including endpoint setup, request and response formats for generation, custom headers, and final document download via render ID. ```APIDOC API Webhook Configuration: 1. Set Up Webhook Endpoint: - Your server should create a webhook endpoint that listens for POST requests. 2. Generate Report with Webhook: - Method: POST - Endpoint: /render/:templateId - Headers: - carbone-webhook-url: Your_Webhook_URL - Response Body: { "success": true, "message": "A render ID will be sent to your callback URL when the document is generated" } 3. Customize Webhook Headers (Optional): - Headers: - carbone-webhook-header-X: Your_Custom_Header_Value - Example: carbone-webhook-header-authorization: my-secret 4. Webhook Notification: - Method: POST (to your webhook URL) - HTTP Body: { "success": true, "data": { "renderId": "MTAuMjAuMTEuNDUgICAghMEQMbTlxkQYUWdRGoYotAcmVwb3J0.pdf" } } 5. Download Generated Document: - Method: GET - Endpoint: /render/:renderID ``` -------------------------------- ### Install Carbone.io CLI Globally Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Install the Carbone.io command-line interface globally using npm for convenient access to its utilities. ```Shell npm install carbone -g ``` -------------------------------- ### Install CarboneJS NPM Package Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Instructions to add the CarboneJS library to your NodeJS application using the npm package manager. ```bash npm install carbone ``` -------------------------------- ### Carbone.io DOCX to PDF Conversion Example Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Illustrates a practical example of converting a DOCX file to PDF using the `carbone.convert` function. The example demonstrates reading a DOCX file into a buffer, setting the `convertTo` option to 'pdf', and writing the resulting PDF buffer to a new file. ```javascript 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); }); ``` -------------------------------- ### Uncompress and Install LibreOffice Debian Packages Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Commands to extract the downloaded LibreOffice tarball, navigate into the DEBS directory, and install all Debian packages using dpkg. This completes the core LibreOffice installation. ```bash tar -zxvf LibreOffice_7.4.1.1_Linux_x86-64_deb.tar.gz cd LibreOffice_7.4.1.1_Linux_x86-64_deb/DEBS sudo dpkg -i *.deb ``` -------------------------------- ### Start Carbone EE Service on Linux Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/self-hosted-deployment/deploy-on-aws Provides the command to start the Carbone EE service on a Linux instance. This is the final step in the manual upgrade procedure, bringing the newly configured Carbone instance online. ```Bash sudo systemctl start carbone-ee ``` -------------------------------- ### Quickstart: Generate a Report with Carbone.io Python SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/python A quick example demonstrating how to initialize the CarboneSDK, provide a template path and JSON data, and render a report. This snippet shows the basic steps to generate a document using the SDK, requiring an API key for authentication. ```Python 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_path, json_data) ``` -------------------------------- ### Configure Carbone.io Global Options Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Set general Carbone.io parameters such as temporary paths, template directories, default language, in-memory translations, and LibreOffice worker settings. This function is synchronous and may create necessary directories. ```JavaScript carbone.set(options); ``` ```JavaScript { 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 } ``` ```JavaScript carbone.set({ lang : 'en-us' }); ``` -------------------------------- ### Start Carbone Docker Compose Stack Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/self-hosted-deployment/deploy-with-docker This command starts the services defined in the docker-compose.yml file. It will bring up the Carbone container and any other defined services, making them accessible according to their configurations. ```bash docker-compose up ``` -------------------------------- ### Dockerfile for Specific LibreOffice Version Installation Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/container-customization This Dockerfile illustrates how to create a Carbone.io Docker image that includes a specific version of LibreOffice. It starts from the 'slim' Carbone.io image, downloads the desired LibreOffice deb package, installs necessary system dependencies, and then installs LibreOffice from the downloaded package, enabling PDF generation with a chosen version. ```Dockerfile FROM debian:stable-slim AS downloader ADD https://downloadarchive.documentfoundation.org/libreoffice/old/7.6.7.2/deb/x86_64/LibreOffice_7.6.7.2_Linux_x86-64_deb.tar.gz /libreoffice.tar.gz FROM carbone/carbone-ee:slim USER root RUN apt update && \ apt install -y libnss3 libxinerama1 libdbus-glib-1-2 libcairo2 libcups2 openssl RUN --mount=type=bind,from=downloader,target=/tmp/libreoffice.tar.gz,source=libreoffice.tar.gz \ tar -zxf /tmp/libreoffice.tar.gz && \ dpkg -i LibreOffice*_Linux_*_deb/DEBS/*.deb && \ rm -r LibreOffice* USER carbone ENTRYPOINT ["./docker-entrypoint.sh"] CMD ["webserver"] ``` -------------------------------- ### Docker Compose Configuration for Single Carbone Instance Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/self-hosted-deployment/deploy-with-docker This docker-compose.yml example defines a single Carbone container service, mapping port 4000, injecting a license from a secret file, enabling Carbone Studio, and binding volumes for both templates and renders. This setup is recommended for production deployments requiring persistent storage. ```yaml version: "3.9" services: carbone: image: carbone-ee ports: - "4000:4000" secrets: - source: carbone-license target: /app/config/prod.carbone-license environment: - CARBONE_EE_STUDIO=true volumes: - ./template:/app/template - ./render:/app/render secrets: carbone-license: file: your_license.carbone-license ``` -------------------------------- ### Initialize Carbone.io Go SDK with Access Token Examples Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/go Provides Go examples demonstrating how to initialize the Carbone.io SDK by passing the access token directly as a parameter or by relying on the 'CARBONE_TOKEN' environment variable. ```Go // Carbone access token passed as parameter csdk, err := carbone.NewCarboneSDK("YOUR-ACCESS-TOKEN") ``` ```Go // Carbone access token passed as environment variable "Carbone TOKEN" csdk, err := carbone.NewCarboneSDK() ``` -------------------------------- ### Node.js Example: Specifying Carbone Cloud API Version Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/http-api/introduction Demonstrates how to include the 'carbone-version' HTTP header in a Node.js request using the 'request' library to target a specific Carbone Cloud API version, such as version 4, for operations like template deletion. ```javascript 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/' + templateId, headers : { 'Authorization': 'Bearer ' + bearerToken, 'carbone-version' : '4' } }, (err, response, body) => { // Handle error // Body contains a response }); ``` -------------------------------- ### Install Carbone.io Python SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/python Instructions to install the Carbone.io Python SDK using pip, the Python package installer. ```Shell $ pip install carbone-sdk ``` -------------------------------- ### Install LibreOffice Dependencies on Ubuntu Server Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Commands to update package lists and install essential dependencies required for LibreOffice 7.0+ on Ubuntu server environments, ensuring proper functionality of the office suite. ```bash sudo apt update sudo apt install libxinerama1 libfontconfig1 libdbus-glib-1-2 libcairo2 libcups2 libglu1-mesa libsm6 libnss3 ``` -------------------------------- ### Carbone.io `carbone.convert` API Reference Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Documents the `carbone.convert` function, which facilitates converting a file buffer from one format to another. It outlines the required `fileBuffer`, `options` (referencing `carbone.render` options), and a `callback` function for handling the conversion result. ```APIDOC carbone.convert(fileBuffer, options, callback); Arguments: - fileBuffer: Buffer returned by fs.readFile (no utf-8) - options: [carbone.render options](/documentation/developer/on-premise-installation/configuration.html) - callback: Callback function with 2 arguments: (err, result) result is the file converted as a buffer ``` -------------------------------- ### Carbone SDK Constructor Examples (Cloud and On-premise) Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/java Provides Java code examples for initializing the Carbone SDK. It shows how to create an instance for Carbone Cloud by providing an API Access Token and for Carbone On-premise/AWS by first setting the server URL and then creating an instance with an empty string. ```Java // For Carbone Cloud, provide your API Access Token as first argument: ICarboneServices carboneServices = CarboneServicesFactory.CARBONE_SERVICES_FACTORY_INSTANCE.create("API_TOKEN"); // Example of a new SDK instance for Carbone On-premise or Carbone On-AWS: // Define the URL of your Carbone On-premise Server or AWS EC2 URL: CarboneServicesFactory.CARBONE_SERVICES_FACTORY_INSTANCE.SetCarboneUrl("ON_PREMISE_URL"); // Then get a new instance by providing an empty string to the "create" function: ICarboneServices carboneServices = CarboneServicesFactory.CARBONE_SERVICES_FACTORY_INSTANCE.create(""); ``` -------------------------------- ### Install Carbone Go SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/go This command installs the Carbone Go SDK, allowing developers to integrate Carbone Cloud API functionalities into their Go applications. It fetches the necessary packages from the specified GitHub repository. ```Go go get github.com/carboneio/carbone-sdk-go ``` -------------------------------- ### Generate and Execute Carbone Systemd Installation Scripts Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Commands to generate systemd installation scripts for Carbone On-Premise and then execute them with superuser privileges. This daemonizes the Carbone service on Ubuntu or Debian systems. ```bash ./carbone install sudo ./install.sh ``` -------------------------------- ### Start Carbone Web Server with License and Studio Mode Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-macos This snippet first sets the Carbone Enterprise Edition license key as an environment variable. Then, it starts the Carbone web server using the `carbone-ee` binary. The `--studio` flag enables the Carbone Studio web component, providing a design interface for templates. ```Shell export CARBONE_EE_LICENSE="xxxxxxx" ./carbone-ee webserver --studio ``` -------------------------------- ### Install Carbone PHP SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/php Instructions to install the Carbone PHP SDK using Composer, the dependency manager for PHP. ```PHP composer require carboneio/carbone-sdk-php ``` -------------------------------- ### CarboneJS Document Rendering API Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node The `carbone.render` and `carbone.renderXML` methods are used to generate documents from templates and data. They return the generated report via a callback function. ```APIDOC carbone.render(templatePath, data, [options,] callback) templatePath: - Path to the template relative to `defaultTemplatePath` (process.cwd() by default). data: - Data to inject in the template. options: - Optional object to set parameters. callback: - Callback function with three parameters: `err`, `result` (Binary), `reportName` (String). carbone.renderXML('{d.param}', data, [options,] callback) data: - Data to inject in the template. options: - Optional object to set parameters. callback: - Callback function with three parameters: `err`, `result` (Binary), `reportName` (String). ``` -------------------------------- ### Translate Templates with Carbone.io CLI Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Use the `carbone translate` command to parse templates, identify translation tags, and update corresponding JSON translation files. This command automatically creates a `lang` directory if it doesn't exist, preserving existing translations. Carbone.io loads these files at startup if found in the default template path. ```Shell carbone translate --help # example: carbone translate -l fr-fr -p path/to/template_default_path ``` -------------------------------- ### Download Template with Carbone.io Go SDK Example Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/go This Go example demonstrates how to use the `GetTemplate` function to download a template by its ID and then save the retrieved template data to a local file. ```Go 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) } ``` -------------------------------- ### Install Carbone.io NodeJS SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/nodejs Instructions for installing the Carbone.io NodeJS SDK using either npm or yarn package managers. This is the first step to integrate the SDK into your project. ```Shell $ npm i --save carbone-sdk // OR $ yarn add carbone-sdk ``` -------------------------------- ### Install Carbone Cloud Javascript SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/javascript Instructions to install the Carbone Cloud Javascript SDK using npm or yarn package managers for client-side applications. ```Shell npm install --save carbone-sdk-js ``` ```Shell yarn add carbone-sdk-js ``` -------------------------------- ### Run Carbone Enterprise Edition Docker Container Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/self-hosted-deployment/deploy-with-docker This command starts a Carbone Enterprise Edition Docker container, exposing port 4000 and enabling the Carbone Studio. It requires the CARBONE_EE_LICENSE environment variable to be set with a valid license key. ```bash export CARBONE_EE_LICENSE=`MY_CARBONE_LICENSE` docker run -t -i --rm -p 4000:4000 -e CARBONE_EE_LICENSE -e CARBONE_EE_STUDIO=true carbone/carbone-ee ``` -------------------------------- ### Carbone.io Report Generation Options Reference Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/embedding/embedding-in-node Defines the comprehensive set of optional parameters that can be passed during report generation. These options control aspects such as output format, timezone, locale, additional data, report naming, enumerations, translations, and temporary file handling. ```JSON { 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)}`. 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/<22-random-chars>`. This filename can be decoded with the function `Carbone.decodeOuputFilename(pathOrFilename)`. It is the user responsability to delete the file or not. } ``` -------------------------------- ### Install Microsoft Core Fonts for LibreOffice Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Command to install the `ttf-mscorefonts-installer` package, which provides common Microsoft fonts like Arial, Times New Roman, and Verdana, for use in reports generated by LibreOffice. ```bash sudo apt install ttf-mscorefonts-installer ``` -------------------------------- ### Example JSON Data for Carbone.io Transform Source: https://carbone.io/documentation/design/overview/getting-started.html/design/advanced-features/transform This JSON object provides sample data that can be used with Carbone.io templates. The 'pos' field illustrates a simple integer value, which could be referenced by the `:transform` formatter to dynamically adjust the position of an element within a document, such as moving an item by a certain number of units. ```json { "pos" : 4 } ``` -------------------------------- ### Download Template with Curl Example Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/http-api/manage-templates Provides a Curl example for downloading a template from the Carbone.io API using its unique `templateId`. ```curl curl --location --request GET 'https://api.carbone.io/template/TEMPLATE_ID' \ --header 'carbone-version: 4' \ --header 'Authorization: Bearer API_TOKEN' \ -o 'FILENAME.docx' ``` -------------------------------- ### API Request Body for Volatile Template Rendering Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/under-the-hood/architecture-guideline This JSON object represents the request body for the POST /render/template API call when using a volatile template. It includes the data for the report, the base64-encoded template file, and the desired output format. ```JSON { data : {}, template : "base64-encoded-file", convertTo : "pdf" } ``` -------------------------------- ### Example: Implement beforeRender Hook Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/plugins An example implementation of the `beforeRender` hook. This function demonstrates how to add a prefix ('myPrefix') to the rendered filename by modifying `carboneOptions.renderPrefix` before the rendering process begins, affecting the output file name. ```JavaScript function beforeRender (req, res, carboneData, carboneOptions, next) { // add a prefix to rendered filename carboneOptions.renderPrefix = 'myPrefix'; next(null); } ``` -------------------------------- ### Example: Implement readTemplate Hook Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/plugins A basic example of the `readTemplate` hook. This function is a placeholder where custom logic to read a template from a custom storage system and return its local path for Carbone can be implemented. ```JavaScript function readTemplate (req, templateId, callback) { // Read your template and return a local path for carbone } module.exports = { readTemplate } ``` -------------------------------- ### Download Carbone-Tested LibreOffice Debian Package Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Command to download a specific, Carbone-tested version of LibreOffice (7.4.1.1) Debian package for 64-bit Linux systems using wget. Users can also find the latest stable version from the official LibreOffice download page. ```bash wget https://downloadarchive.documentfoundation.org/libreoffice/old/7.4.1.1/deb/x86_64/LibreOffice_7.4.1.1_Linux_x86-64_deb.tar.gz ``` -------------------------------- ### Check Carbone On-premise Service Status Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Command to check the current running status of the `carbone-ee` service using `sudo service`. This helps verify if the Carbone server is active and running correctly. ```bash sudo service carbone-ee status ``` -------------------------------- ### Run Carbone Docker with Persistent Template Volume Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/self-hosted-deployment/deploy-with-docker This Docker command starts a Carbone Enterprise Edition container, similar to the basic run command, but adds a volume bind for the /app/template directory. This ensures that templates are stored persistently on the host machine, recommended for single instance production use. ```bash docker run -t -i --rm -p 4000:4000 -e CARBONE_EE_LICENSE -e CARBONE_EE_STUDIO=true -volume ./template:/app/template carbone/carbone-ee ``` -------------------------------- ### Format Currency with Carbone.io Template Examples Source: https://carbone.io/documentation/design/overview/getting-started.html/design/formatters/currency Examples demonstrating the `formatC` function for currency formatting, including precision, target currency, and different language settings. Shows how API options like `lang`, `currency.source`, `currency.target`, and `currency.rates` influence the output. ```Carbone.io Template // With API options: { // "lang": "en-us", // "currency": { // "source": "EUR", // "target": "USD", // "rates": { // "EUR": 1, // "USD": 2 // } // } // } '1000.456':formatC() // "$2,000.91" '1000.456':formatC('M') // "dollars" '1':formatC('M') // "dollar" '1000':formatC('L') // "$2,000.00" '1000':formatC('LL') // "2,000.00 dollars" // With API options: { // "lang": "fr-fr", // "currency": { // "source": "EUR", // "target": "USD", // "rates": { // "EUR": 1, // "USD": 2 // } // } // } '1000.456':formatC() // "2 000,91 " // With API options: { // "lang": "fr-fr", // "currency": { // "source": "EUR", // "target": "EUR", // "rates": { // "EUR": 1, // "USD": 2 // } // } // } '1000.456':formatC() // "1 000,46 €" ``` -------------------------------- ### Example Dataset for Dynamic Parameters Source: https://carbone.io/documentation/design/overview/getting-started.html/design/formatters/overview This JSON object serves as the sample data used in the following examples to demonstrate dynamic parameter access and operations within Carbone.io templates. ```JSON { "id" : 10, "qtyA" : 20, "subObject" : { "qtyB" : 5, "qtyC" : 3 }, "subArray" : [{ "id" : 1000, "qtyE" : 3 }] } ``` -------------------------------- ### Generate Report with Carbone.io Go SDK Example Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/go This Go example demonstrates how to use the `Render` function to generate a report from a DOCX template with specified data and an optional payload, then saves the resulting report as a PDF file. ```Go 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) } ``` -------------------------------- ### Example: Implement readRender Hook (Basic) Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/plugins A basic example of the `readRender` hook. This function is a placeholder for custom logic to return the rendered report directly using the response object or provide a local path for Carbone to read and serve. ```JavaScript function readRender (req, res, renderName, next) { // Return the directly render or a local path } ``` -------------------------------- ### Convert Currency with Carbone.io Template Examples Source: https://carbone.io/documentation/design/overview/getting-started.html/design/formatters/currency Examples demonstrating the `convCurr` function for currency conversion between different currencies. Shows how API options like `currency.source`, `currency.target`, and `currency.rates` are used, and how parameters can override default settings. ```Carbone.io Template // With API options: { // "currency": { // "source": "EUR", // "target": "USD", // "rates": { // "EUR": 1, // "USD": 2 // } // } // } 10:convCurr() // 20 1000:convCurr() // 2000 1000:convCurr('EUR') // 1000 1000:convCurr('USD') // 2000 1000:convCurr('USD', 'USD') // 1000 ``` -------------------------------- ### Upload Template with Curl Examples Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/http-api/manage-templates Provides two Curl examples for uploading a template to the Carbone.io API: one using a file path with `multipart/form-data` and another using a base64 string with `application/json`. ```curl 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_TOKEN' \ --form 'template=@"ABSOLUTE_FILE_PATH"' ``` ```curl curl --location --request POST 'https://api.carbone.io/template' \ --header 'carbone-version: 4' \ --header 'Expect:' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer API_TOKEN' \ --data-raw '{ "template": "BASE64_STRING" }' ``` -------------------------------- ### List Carbone Webserver CLI Options Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/configuration Demonstrates how to use the `--help` command to display all available command-line options for the Carbone webserver. ```shell ./carbone webserver --help ``` -------------------------------- ### Carbone.io formatI Examples: Human Readable Output (English) Source: https://carbone.io/documentation/design/overview/getting-started.html/design/formatters/interval Examples showing the `formatI` function's use with 'human' and 'human+' patterns to generate English human-readable duration strings. These examples highlight the impact of the `lang` API option and demonstrate positive and negative durations. ```JavaScript // With API options: { // "lang": "en", // "timezone": "Europe/Paris" // } 2000:formatI('human') // "a few seconds" 2000:formatI('human+') // "in a few seconds" -2000:formatI('human+') // "a few seconds ago" ``` -------------------------------- ### Example Generated Carbone JWT Token Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/self-hosted-deployment/deploy-on-gcp An example of a successfully generated JWT token. This token is essential for making authenticated requests to the Carbone API by including it in the `Authorization` header. ```text JWT token successfully generated: eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjYXJib25lLXVzZXIiLCJhdWQiOiJjYXJib25lLWVlIiwiZXhwIjozMDA3MDMwMDI3LCJkYXRhIjp7fX0.APGGFckrEy2an51UkAsngpp98lno5c_hMD54ZtnxjXQaM6ScMSCuOZZUT7Z_iGaHh2pM-3ki86wkglWV6NxS1JDEAfVE8EYdMp5qEUt9GQP1RAoLfmYCBdqR7bLTZiqAKfyWZREB6NHWajltwtoqelH7kitPa7kq7jhNW3xqcr-siRjF ``` -------------------------------- ### Performing Spreadsheet Calculations with Carbone.io Source: https://carbone.io/documentation/design/overview/getting-started.html/design/overview/design-best-practices Demonstrates various methods to perform calculations involving Carbone.io tags within XLSX and ODS spreadsheet templates, addressing how Carbone processes data injection before formula execution. Solutions include Carbone's built-in multiplication, isolating tags for Excel calculations, and embedding tags directly within Excel formulas using IFERROR. ```Carbone Template {d.val:mul(100)} ``` ```Spreadsheet Formula Cell A1: {d.val:formatN} Cell A2: = A1 * 100 ``` ```Spreadsheet Formula = 100 * IFERROR("{d.val}", 0) ``` -------------------------------- ### Upload Template with Carbone.io Go SDK Example Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/go This Go example demonstrates how to use the `AddTemplate` function to upload a template file to the Carbone.io API, including error handling and verification of the returned `TemplateID`. ```Go 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) ``` -------------------------------- ### Carbone.io formatI Examples: Human Readable Output (French) Source: https://carbone.io/documentation/design/overview/getting-started.html/design/formatters/interval Examples showing the `formatI` function's use with 'human' and 'human+' patterns to generate French human-readable duration strings. These examples highlight the impact of the `lang` API option and demonstrate positive and negative durations. ```JavaScript // With API options: { // "lang": "fr", // "timezone": "Europe/Paris" // } 2000:formatI('human') // "quelques secondes" 2000:formatI('human+') // "dans quelques secondes" -2000:formatI('human+') // "il y a quelques secondes" ``` -------------------------------- ### Generate SHA256 Hash for Template ID in Node.js Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/http-api/introduction This Node.js example demonstrates how to compute a predictable and idempotent SHA256 hash from the content of a template. This hash serves as the unique Template ID within the Carbone.io system, ensuring consistent identification of templates based on their content. ```Node.js const crypto = require('crypto'); const hash = crypto.createHash('sha256') .update('FILE_CONTENT') .digest('hex'); ``` -------------------------------- ### Carbone.io formatI Examples: Numeric Input with Specified Input Unit Source: https://carbone.io/documentation/design/overview/getting-started.html/design/formatters/interval Examples demonstrating the `formatI` function's ability to convert numeric values from a specified input unit (e.g., minutes, weeks) to a desired output unit (e.g., milliseconds). This showcases the `patternIn` parameter. ```JavaScript // With API options: { // "lang": "en", // "timezone": "Europe/Paris" // } 60:formatI('ms', 'minute') // 3600000 4:formatI('ms', 'weeks') // 2419200000 ``` -------------------------------- ### Example: Return New Path in readRender Hook Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/plugins This example demonstrates how the `readRender` hook can be used to specify a new disk path for the rendered report, useful if the report has been moved or stored in a custom location after generation. ```JavaScript // OR // Return the new path on disk function (req, res, renderName, next) { return next(null, renderName, '/new/path/on/disk') } ``` -------------------------------- ### Access Last Elements of a List Using Negative Indexing in Carbone.io Source: https://carbone.io/documentation/design/overview/getting-started.html/design/substitutions/array-search This example shows how to retrieve elements from the end of a list in Carbone.io templates using negative indices. For instance, `[i=-1]` accesses the last element, and `[i=-2]` accesses the second to last. ```JSON [ { "name": "Inception", "year": 2010 }, { "name": "Matrix", "year": 1999 }, { "name": "BTTF", "year": 1985 } ] ``` ```Carbone.io Template The oldest movie was {d[i=-1].name}. ``` ```Plain Text The oldest movie was BTTF. ``` -------------------------------- ### Example: Implement afterRender Hook (Basic) Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/plugins A basic example of the `afterRender` hook. This function serves as a placeholder for custom logic to handle the rendered report, such as writing or renaming it, after Carbone has completed the generation. It simply calls `next(null)` to proceed. ```JavaScript function afterRender (req, res, err, reportPath, reportName, statistics, next) { // Write or rename your render // TemplateID available: req.params.templateId return next(null) } module.exports = { afterRender } ``` -------------------------------- ### Carbone.io DSL: ifGTE Operator Examples Source: https://carbone.io/documentation/design/overview/getting-started.html/design/conditions/overview Examples demonstrating the usage of the :ifGTE operator with various integer and string values, showing both true and false results based on the comparison. ```Carbone.io DSL 50:ifGTE(-29):show('Result true'):elseShow('Result false') // "Result true" 1:ifGTE(1):show('Result true'):elseShow('Result false') // "Result true" 1290:ifGTE(768):show('Result true'):elseShow('Result false') // "Result true" '1234':ifGTE('1'):show('Result true'):elseShow('Result false') // "Result true" -23:ifGTE(19):show('Result true'):elseShow('Result false') // "Result false" 1:ifGTE(768):show('Result true'):elseShow('Result false') // "Result false" '1':ifGTE('1234'):show('Result true'):elseShow('Result false') // "Result false" ``` -------------------------------- ### Quickstart: Generate Report with Carbone.io SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/javascript This snippet demonstrates how to quickly generate a report using the Carbone.io JavaScript SDK. It initializes the SDK with an API key, retrieves a template file and data from HTML inputs, and then renders the report, providing the content as a Blob and the report name. ```JavaScript import carboneSDK from "carbone-sdk-js"; // SDK constructor, the access token have to be passed as an argument to carboneRenderSDK const _carboneService = carboneSDK("eyJhbGc..."); // same as window.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 }); ``` -------------------------------- ### Filter Data Using Variables from JSON in Carbone.io Templates Source: https://carbone.io/documentation/design/overview/getting-started.html/design/substitutions/array-search This example illustrates how to use variables from the input JSON data as operands within Carbone.io filters. By prefixing the operand with a period, the template engine interprets it as a variable path within the JSON structure. ```JSON { "parent" : { "qty" : 2 }, "subArray" : [{ "text" : 1000, "other" : 1, "sub" : { "b" : { "c" : 1 } } },{ "text" : 2000, "other" : 1, "sub" : { "b" : { "c" : 2 } } }] } ``` ```Carbone.io Template {d.subArray[sub.b.c = .other].text}{d.subArray[sub.b.c = ..parent.qty].text} ``` ```Plain Text 10002000 ``` -------------------------------- ### Carbone On-Premise Configuration Options Reference Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/configuration Lists all configurable parameters for Carbone On-Premise, including settings for Studio, service ports, workspace and license directories, authentication, performance, and localization. ```APIDOC Configurable parameters: - Enable Studio - Service Port - Workspace directory - License directory - License - Authentication - Authentication public key - Studio basic authentication - Thread number - Conversion retry - Conversion timeout - Maximum data size - Maximum template size - Template retention time - Language - Timezone - Source currency - Target currency - Translation dictionary - Xlsm support - Maximum number of reports per batch ``` -------------------------------- ### Carbone Template: Performing Parallel Loops Source: https://carbone.io/documentation/design/overview/getting-started.html/design/repetitions/with-arrays This example demonstrates how to iterate through two separate arrays simultaneously using the same iterator variable. By combining the iterator `i` with relative path access (`..`), it's possible to print content from a different array, such as 'brands', while looping through 'cars'. ```JSON { "cars" : [ { "id" : 1 }, { "id" : 2 }, { "id" : 3 }, { "id" : 4 } ], "brands" : [ { "name" : "Toyota" }, { "name" : "Hyundai"}, { "name" : "BMW" } ] } ``` ```Carbone Template Carsid{d.cars[i].id}{d.cars[i].id:print(..brands[.i].name)}{d.cars[i+1].id} ``` ```Text Carsid1Toyota2Hyundai3BMW4 ``` -------------------------------- ### Removing Last Page Break or Comma in Carbone Loops Source: https://carbone.io/documentation/design/overview/getting-started.html/design/overview/design-best-practices Provides Carbone tag examples for conditionally dropping a page break or managing commas at the end of a loop, preventing unwanted blank pages or trailing separators. It shows two approaches for page break management. ```Carbone Template {d.list[i]..list:len():sub(1):ifEQ(.i):drop(p)} ``` ```Carbone Template {d.list[i, i=-1]:ifNEM:drop(p)} ``` -------------------------------- ### Quickstart: Render Report with Carbone.io Java SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/java This snippet demonstrates how to quickly render a report using the Carbone.io Java SDK. It covers initializing the service with an API key, preparing JSON data, calling the `render` method, handling potential `CarboneException` errors, and saving the generated document to a file, including `IOException` handling. ```Java ICarboneServices carboneServices = CarboneServicesFactory.CARBONE_SERVICES_FACTORY_INSTANCE.create(API_KEY); String json = "{ \"data\": { \"id\": \"AF128\",\"firstname\": \"John\", \"lastname\": \"wick\"}, \"reportName\": \"invoice-{d.id}\",\"convertTo\": \"pdf\"}"; /** Generate the document */ try{ CarboneDocument report = carboneServices.render(json ,"/path/to/template.docx"); } catch(CarboneException e) { // handle error System.out.println("Error message : " + e.getMessage() + "Status code : " + e.getHttpStatus()); } // Get the name of the document with the `getName()`. For instance the name of the document, based on the JSON, is: \"invoice-AF128.pdf\" try (FileOutputStream outputStream = new FileOutputStream(report.getName())) { /** Save the generated document */ outputStream.write(report.getFileContent()); } catch (IOException ioe) { // handle error } ``` -------------------------------- ### Generate Report with Carbone.io Go SDK Quickstart Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/go This Go code snippet demonstrates how to quickly generate a report using the Carbone.io SDK. It initializes the SDK with an access token, specifies a template path and JSON data, renders the report, and saves it as a PDF file. ```Go 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) } } ``` -------------------------------- ### Remove Old LibreOffice Versions on Debian/Ubuntu Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Commands to completely remove any existing LibreOffice installations and their associated configuration files from Debian or Ubuntu systems, ensuring a clean slate for new installations. ```bash sudo apt remove --purge libreoffice* sudo apt autoremove --purge ``` -------------------------------- ### Quickstart: Render Carbone.io Report with Rust SDK Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/rust This snippet demonstrates how to quickly generate and download a report using the Carbone.io Rust SDK. It covers initializing the SDK with an API token, preparing JSON data, specifying a template ID, and saving the generated report content to a file. ```Rust use std::env; use carbone_sdk_rust::config::Config; use carbone_sdk_rust::carbone::Carbone; use carbone_sdk_rust::types::{ApiJsonToken, JsonData}; use carbone_sdk_rust::template::TemplateId; use carbone_sdk_rust::errors::CarboneError; use std::fs::File; use std::io::Write; #[tokio::main] async fn main() -> Result<(), CarboneError> { let token = "Token"; let config: Config = Default::default(); let api_token = ApiJsonToken::new(token.to_string())?; let json_data_value = String::from(r#" { "data" : { "firstname" : "John", "lastname" : "Wick" }, "convertTo" : "odt" } "#); let json_data = JsonData::new(json_data_value)?; let template_id = TemplateId::new("YourTemplateId".to_string())?; let carbone = Carbone::new(&config, Some(&api_token))?; let report_content = match carbone.generate_report_with_template_id(template_id, json_data).await { Ok(v) => v, Err(e) => panic!("{}", e.to_string()) }; let mut output_file = File::create("report.pdf").expect("Failed to create file"); if let Err(e) = output_file.write_all(&report_content) { eprintln!("Failed to write to file: {:?}", e); } Ok(()) } ``` -------------------------------- ### Configure Carbone Webserver with CLI Options Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/configuration An example of passing multiple configuration options directly to the Carbone webserver via command-line arguments, setting port, factories, work directory, attempts, authentication, and studio mode. ```shell ./carbone webserver --port 4001 --factories 4 --workdir /var/www/carbone --attempts 2 --authentication --studio ``` -------------------------------- ### Initialize Carbone SDK with Access Token and API URL Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/api-sdks/python Demonstrates how to create a new instance of carbone_sdk.CarboneSDK, either by passing the access token directly or by using an environment variable. It also shows how to set a custom API URL for on-premise deployments and how to set the environment variable. ```Python 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() # Set API URL for Carbone On-Premise for example (default: "https://api.carbone.io") csdk.set_api_url("https://api.carbone.io") ``` ```Shell $ export CARBONE_TOKEN=your-secret-token ``` ```Shell $ printenv | grep "CARBONE_TOKEN" ``` -------------------------------- ### Install Fonts for Special Characters (e.g., Chinese Ideograms) Source: https://carbone.io/documentation/design/overview/getting-started.html/developer/on-premise-installation/install-on-linux Command to install a font package like `fonts-wqy-zenhei` that supports special characters, such as Chinese ideograms, ensuring they are rendered correctly in documents processed by LibreOffice. ```bash sudo apt install fonts-wqy-zenhei ``` -------------------------------- ### Carbone Template: Handling Nested Arrays Source: https://carbone.io/documentation/design/overview/getting-started.html/design/repetitions/with-arrays This example illustrates Carbone.io's capability to manage and repeat content from deeply nested arrays, allowing for the repetition of entire document sections. The template uses nested `[i]` and `[i+1]` tags to define the repetition pattern for both the main array and its nested 'models' array. ```JSON [ { "brand": "Toyota", "models": [{ "size": "Prius 4", "power": 125 }, { "size": "Prius 5", "power": 139 }] }, { "brand": "Kia", "models": [{ "size": "EV4", "power": 450 }, { "size": "EV6", "power": 500 }] } ] ``` ```Carbone Template {d[i].brand}Models{d[i].models[i].size} - {d[i].models[i].power}{d[i].models[i+1].size}{d[i+1].brand} ``` ```Text ToyotaModelsPrius 4 - 125Prius 5 - 139KiaModelsEV4 - 450EV6 - 500 ``` -------------------------------- ### Carbone Template: Implementing Bi-directional Loops Source: https://carbone.io/documentation/design/overview/getting-started.html/design/repetitions/with-arrays Introduced in v4.8.0+, the bidirectional loop feature allows iterations in two directions, creating additional columns and rows. This example demonstrates its usage with specific restrictions: the JSON parent array must be used for rows, and the nested array for columns. It is officially supported in DOCX, HTML, and MD templates. ```JSON { "titles" : [{ "name": "Kia" }, { "name": "Toyota" }, { "name": "Hopium" }], "cars" : [ { "models" : [ "EV3", "Prius 1", "Prototype" ] }, { "models" : [ "EV4", "Prius 2", "" ] }, { "models" : [ "EV6", "Prius 3", "" ] } ] } ``` ```Carbone Template {d.titles[i].name}{d.titles[i+1].name}{d.cars[i].models[i]}{d.cars[i].models[i+1]}{d.cars[i+1].models[i]} ``` ```Text KiaToyotaHopiumEV3Prius 1PrototypeEV4Prius 2EV6Prius 3 ```