Note: If you use the public Export Server at https://export.highcharts.com you should read our Terms of use and Fair Usage Policy. Note that a valid Highcharts License is required to do exports.
Convert Highcharts.JS charts into static image files.
In most cases, v4 should serve as a drop-in replacement for v2 and v3. However, due to changes in the browser backend, various tweaks related to process handling (e.g., worker counts, and so on) may now have different effects than before.
Significant changes have been made to the API for using the server as a Node.js module. While a compatibility layer has been created to address this, it is recommended to transition to the new API described below. It is worth noting that the compatibility layer may be deprecated at some point in the future.
An important note is that the Export Server now requires Node.js v18.12.0 or a higher version.
Additionally, with the v3 release, we transitioned from HTTP to HTTPS for export.highcharts.com, so all requests sent to our public server now must use the HTTPS protocol.
Version 4 introduces some breaking changes, mostly related to renamed options, environment variables, function names, and reordered function parameters. For further details, please refer to the changelog document provided below, under the Breaking Changes section.
The full change log for all versions can be viewed here.
This Node.js application/service converts Highcharts.JS charts into static image files, supporting PNG, JPEG, SVG, and PDF output. The input can be either SVG or JSON-formatted chart options.
The application is versatile and can be used as a CLI (Command Line Interface), an HTTP server, or as a Node.js module.
The primary use case for the Export Server is scenarios requiring headless conversion of charts. Common cases of using include automatic report generation, static caching, and incorporating charts into presentations or other documents.
In addition, the HTTP mode enables you to run your own Export Server for users, reducing reliance on the public https://export.highcharts.com/ server, which has rate limitations.
The HTTP server can be run either independently, integrating with your other applications and services, or in a way that directs the export buttons on your charts to your customized server.
To implement the latter, include the following configuration in your chart options:
{
exporting: {
url: "<IP to the self-hosted Export Server>"
}
}
For systems that generate automatic reports, using the Export Server as a Node.js module is a great fit - especially if your report generator is also written in Node.js. Check here for examples.
First, make sure you have Node.js installed. If not, visit nodejs.org, download and install Node.js for your platform. For compatibility reasons, version 18.12.0 or higher is required.
Once Node.js is installed, proceed to install the Export Server by opening a terminal and typing:
npm install highcharts-export-server -g
or:
git clone https://github.com/highcharts/node-export-server
npm install
npm link
Depending on your Node.js installation method, you might need to create a symlink from nodejs to node. For example, on Linux:
ln -s `which nodejs` /usr/bin/node
To use the Export Server, simply run the following command with the correct arguments:
highcharts-export-server <arguments>
There are four main ways of loading configurations:
- By loading default options from the
./lib/schemas/config.jsfile. - By providing configurations via environment variables from the
.envfile. - By loading options from a custom JSON file.
- By passing arguments through command line interface (CLI).
...or any combination of the four. In such cases, the options from the later step take precedence (config file -> envs -> custom JSON -> CLI arguments).
A description of how options are handled and processed when using a specific export method.
When starting a server or performing single or batch exports via the CLI, the server's global options are initialized from the defaultConfig object located in ./lib/schemas/config.js, along with values from the .env file. These options can be extended with additional values provided through CLI arguments, which are internally set using the setCliOptions() function.
For Node.js Module usage, the process differs slightly because API functions are called manually. By default, global options are initialized from the defaultConfig object and the .env file at startup, similar to the server and CLI scenarios. However, to include additional options, you need to explicitly call the updateOptions() function. If the updateOptions() function is not invoked, the system will rely on the default values previously set in the global options object.
All API functions accept specific sets of options that, if provided, extend the global options. When such options are not provided, the default global option values are used. Additionally, the updateOptions() function allows you to extend global options in advance, eliminating the need to provide options to each function individually. However, singleExport(), batchExport(), and startExport() must still be provided with export-related options.
This flexibility is particularly useful for deciding whether global options should remain static during subsequent exports or be updated dynamically. In either case, new options from various sources are merged into the configuration, and the resulting options are applied in API functions.
The singleExport(), batchExport(), and startExport() functions must be provided with at least partial options that include one of the following options from the export section: infile, instr, svg, or batch. Any missing values in the provided options object will automatically default to those specified in the global options object. Unlike other API functions, options provided to the export functions will not be merged into the global options object, as these options represent a specific export process. To make the export options global, you can use the updateOptions() function before initiating the export.
Essentially, all options can be configured through .env, the CLI, and prompts, with one exception: the HIGHCHARTS_ADMIN_TOKEN, which is only available as an environment variable.
By default, options validation is enabled, and it is recommended to keep it enabled to ensure that the provided options are correctly checked, validated, and parsed, allowing the exporting process to function without issues. However, it is possible to disable validation (by setting the validation option to false) if you are confident in the accuracy of the data you provide. Additionaly, when used as a Node.js module, each API function that updates global options with the provided data also offers the ability to validate the data.
The JSON below represents the default configuration stored in the ./lib/schemas/config.js file. If no .env file is found (more details on the file and environment variables below), these options will be used. The configuration is not recommended to be modified directly, as it can typically be managed through other sources.
The format, along with its default values, is as follows (using the recommended ordering of core and module scripts below).
Available default JSON config:
{
"puppeteer": {
"args": [/* See the `./lib/schemas/config.js` file */]
},
"highcharts": {
"version": "latest",
"cdnUrl": "https://code.highcharts.com",
"forceFetch": false,
"cachePath": ".cache"
"coreScripts": [
"highcharts",
"highcharts-more",
"highcharts-3d"
],
"moduleScripts": [
"stock",
"map",
"gantt",
"exporting",
"parallel-coordinates",
"accessibility",
"annotations-advanced",
"boost-canvas",
"boost",
"data",
"data-tools",
"draggable-points",
"static-scale",
"broken-axis",
"heatmap",
"tilemap",
"tiledwebmap",
"timeline",
"treemap",
"treegraph",
"item-series",
"drilldown",
"histogram-bellcurve",
"bullet",
"funnel",
"funnel3d",
"geoheatmap",
"pyramid3d",
"networkgraph",
"overlapping-datalabels",
"pareto",
"pattern-fill",
"pictorial",
"price-indicator",
"sankey",
"arc-diagram",
"dependency-wheel",
"series-label",
"series-on-point",
"solid-gauge",
"sonification",
"stock-tools",
"streamgraph",
"sunburst",
"variable-pie",
"variwide",
"vector",
"venn",
"windbarb",
"wordcloud",
"xrange",
"no-data-to-display",
"drag-panes",
"debugger",
"dumbbell",
"lollipop",
"cylinder",
"organization",
"dotplot",
"marker-clusters",
"hollowcandlestick",
"heikinashi",
"flowmap",
"export-data",
"navigator",
"textpath"
],
"indicatorScripts": [
"indicators-all"
],
"customScripts": [
"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.45/moment-timezone-with-data.min.js"
]
},
"export": {
"infile": null,
"instr": null,
"options": null,
"svg": null,
"batch": null,
"outfile": null,
"type": "png",
"constr": "chart",
"b64": false,
"noDownload": false,
"height": null,
"width": null,
"scale": null,
"globalOptions": null,
"themeOptions": null,
"rasterizationTimeout": 1500
},
"customLogic": {
"allowCodeExecution": false,
"allowFileResources": false,
"customCode": null,
"callback": null,
"resources": null,
"loadConfig": null,
"createConfig": null
},
"server": {
"enable": false,
"host": "0.0.0.0",
"port": 7801,
"uploadLimit": 3,
"benchmarking": false,
"proxy": {
"host": null,
"port": null,
"timeout": 5000
},
"rateLimiting": {
"enable": false,
"maxRequests": 10,
"window": 1,
"delay": 0,
"trustProxy": false,
"skipKey": null,
"skipToken": null
},
"ssl": {
"enable": false,
"force": false,
"port": 443,
"certPath": null
}
},
"pool": {
"minWorkers": 4,
"maxWorkers": 8,
"workLimit": 40,
"acquireTimeout": 5000,
"createTimeout": 5000,
"destroyTimeout": 5000,
"idleTimeout": 30000,
"createRetryInterval": 200,
"reaperInterval": 1000,
"benchmarking": false
},
"logging": {
"level": 4,
"file": "highcharts-export-server.log",
"dest": "log",
"toConsole": true,
"toFile": true
},
"ui": {
"enable": false,
"route": "/"
},
"other": {
"nodeEnv": "production",
"listenToProcessExits": true,
"noLogo": false,
"hardResetPage": false,
"browserShellMode": true,
"validation": true
},
"debug": {
"enable": false,
"headless": false,
"devtools": false,
"listenToConsole": false,
"dumpio": false,
"slowMo": 0,
"debuggingPort": 9222
}
}
These variables are set in your environment and take precedence over options from the ./lib/schemas/config.js file. They can be set in the .env file (refer to the .env.sample file). If you prefer setting these variables through the package.json, use export command on Linux/Mac OS X and set command on Windows.
Available environment variables:
PUPPETEER_ARGS: A stringified version of additional Puppeteer arguments sent during browser initialization. The string can be enclosed in [ and ], and the arguments must be separated by the ; character (defaults to ``).
HIGHCHARTS_VERSION: Highcharts version to use (defaults tolatest).HIGHCHARTS_CDN_URL: Highcharts CDN URL of scripts to be used (defaults tohttps://code.highcharts.com).HIGHCHARTS_FORCE_FETCH: The flag that determines whether to refetch all scripts after each server rerun (defaults tofalse).HIGHCHARTS_CACHE_PATH: A directory path where the fetched Highcharts scripts should be placed (defaults to.cache). Since v4.0.3 can be either absolute or relative path.HIGHCHARTS_ADMIN_TOKEN: An authentication token that is required to switch the Highcharts version on the server at runtime (defaults to ``).HIGHCHARTS_CORE_SCRIPTS: Highcharts core scripts to fetch (defaults to ``).HIGHCHARTS_MODULE_SCRIPTS: Highcharts module scripts to fetch (defaults to ``).HIGHCHARTS_INDICATOR_SCRIPTS: Highcharts indicator scripts to fetch (defaults to ``).HIGHCHARTS_CUSTOM_SCRIPTS: Additional custom scripts or dependencies to fetch (defaults to ``).
EXPORT_INFILE: The input file should include a name and a type (.json or .svg) and must contain a correctly formatted JSON or SVG (defaults to ``).EXPORT_INSTR: An input in a form of a stringified JSON.EXPORT_OPTIONS: An alias for theinstroption (defaults to ``).EXPORT_SVG: A string containing SVG representation to render as a chart (defaults to ``).EXPORT_BATCH: Initiates a batch job with a string containing input/output pairs: "in=out;in=out;.." (defaults to ``).EXPORT_OUTFILE: The output filename, accompanied by a type (jpeg, png, pdf, or svg). Ignores thetypeoption (defaults to ``).EXPORT_TYPE: The format of the file to export to. Can be jpeg, png, pdf, or svg (defaults topng).EXPORT_CONSTR: The constructor to use. Can be chart, stockChart, mapChart, or ganttChart (defaults tochart).EXPORT_B64: Boolean flag, set to true to receive the chart in the base64 format instead of the binary (defaults tofalse).EXPORT_NO_DOWNLOAD: Boolean flag, set to true to exclude attachment headers from the response (defaults tofalse).EXPORT_HEIGHT: The height of the exported chart. Overrides the option in the chart settings (defaults to ``).EXPORT_WIDTH: The width of the exported chart. Overrides the option in the chart settings (defaults to ``).EXPORT_SCALE: The scale of the exported chart. Ranges between 0.1 and 5.0 (defaults to ``).EXPORT_DEFAULT_HEIGHT: The default fallback height for exported charts if not set explicitly (defaults to400).EXPORT_DEFAULT_WIDTH: The default fallback width for exported charts if not set explicitly (defaults to600).EXPORT_DEFAULT_SCALE: The default fallback scale for exported charts if not set explicitly. Ranges between 0.1 and 5.0 (defaults to1).EXPORT_GLOBAL_OPTIONS: Either a stringified JSON or a filename containing global options to be passed into theHighcharts.setOptions()(defaults to ``).EXPORT_THEME_OPTIONS: Either a stringified JSON or a filename containing theme options to be passed into theHighcharts.setOptions()(defaults to ``).EXPORT_RASTERIZATION_TIMEOUT: The specified duration, in milliseconds, to wait for rendering a webpage (defaults to1500).
CUSTOM_LOGIC_ALLOW_CODE_EXECUTION: Controls whether the execution of arbitrary code is allowed during the exporting process (defaults tofalse).CUSTOM_LOGIC_ALLOW_FILE_RESOURCES: Controls the ability to inject resources from the filesystem. This setting has no effect when running as a server (defaults tofalse).CUSTOM_LOGIC_CUSTOM_CODE: Custom code to execute before chart initialization. It can be a function, code wrapped within a function, or a filename with the .js extension (defaults to ``).CUSTOM_LOGIC_CALLBACK: JavaScript code to run during construction. It can be a stringified function or a filename with the .js extension that contains a correct Highcharts callback (defaults to ``).CUSTOM_LOGIC_RESOURCES: Additional resources in the form of a stringified JSON. It may containfiles(array of JS filenames),js(stringified JS), andcss(stringified CSS) sections (defaults to ``).CUSTOM_LOGIC_LOAD_CONFIG: A file containing a pre-defined configuration to use (defaults to ``).CUSTOM_LOGIC_CREATE_CONFIG: Enables setting options through a prompt and saving them in a provided config file (defaults to ``).
SERVER_ENABLE: If set to true, the server starts on 0.0.0.0 (defaults tofalse).SERVER_HOST: The hostname of the server. Additionally, it starts a server listening on the provided hostname (defaults to0.0.0.0).SERVER_PORT: The port to be used for the server when enabled (defaults to7801).SERVER_UPLOAD_LIMIT: The maximum request body size in MB (defaults to3).SERVER_BENCHMARKING: Indicates whether to display a message with the duration, in milliseconds, of specific actions that occur on the server while serving a request (defaults tofalse).
SERVER_PROXY_HOST: The host of the proxy server to use, if it exists (defaults to ``).SERVER_PROXY_PORT: The port of the proxy server to use, if it exists (defaults to ``).SERVER_PROXY_TIMEOUT: The timeout, in milliseconds, for the proxy server to use, if it exists (defaults to5000).
SERVER_RATE_LIMITING_ENABLE: Enables rate limiting for the server (defaults tofalse).SERVER_RATE_LIMITING_MAX_REQUESTS: The maximum number of requests allowed in one minute (defaults to10).SERVER_RATE_LIMITING_WINDOW: The time window, in minutes, for the rate limiting (defaults to1).SERVER_RATE_LIMITING_DELAY: The delay duration for each successive request before reaching the maximum limit (defaults to0).SERVER_RATE_LIMITING_TRUST_PROXY: Set this to true if the server is behind a load balancer (defaults tofalse).SERVER_RATE_LIMITING_SKIP_KEY: Allows bypassing the rate limiter and should be provided with theskipTokenargument (defaults to ``).SERVER_RATE_LIMITING_SKIP_TOKEN: Allows bypassing the rate limiter and should be provided with theskipKeyargument (defaults to ``).
SERVER_SSL_ENABLE: Enables or disables the SSL protocol (defaults tofalse).SERVER_SSL_FORCE: If set to true, the server is forced to serve only over HTTPS (defaults tofalse).SERVER_SSL_PORT: The port on which to run the SSL server (defaults to443).SERVER_SSL_CERT_PATH: The path to the SSL certificate/key file (defaults to ``).
POOL_MIN_WORKERS: The number of minimum and initial pool workers to spawn (defaults to4).POOL_MAX_WORKERS: The number of maximum pool workers to spawn (defaults to8).POOL_WORK_LIMIT: The number of work pieces that can be performed before restarting the worker process (defaults to40).POOL_ACQUIRE_TIMEOUT: The duration, in milliseconds, to wait for acquiring a resource (defaults to5000).POOL_CREATE_TIMEOUT: The duration, in milliseconds, to wait for creating a resource (defaults to5000).POOL_DESTROY_TIMEOUT: The duration, in milliseconds, to wait for destroying a resource (defaults to5000).POOL_IDLE_TIMEOUT: The duration, in milliseconds, after which an idle resource is destroyed (defaults to30000).POOL_CREATE_RETRY_INTERVAL: The duration, in milliseconds, to wait before retrying the create process in case of a failure (defaults to200).POOL_REAPER_INTERVAL: The duration, in milliseconds, after which the check for idle resources to destroy is triggered (defaults to1000).POOL_BENCHMARKING: Indicates whether to show statistics for the pool of resources or not (defaults tofalse).
LOGGING_LEVEL: The logging level to be used. Can be 0 - silent, 1 - error, 2 - warning, 3 - notice, 4 - verbose or 5 - benchmark (defaults to4).LOGGING_FILE: The name of a log file. ThelogToFileandlogDestoptions also need to be set to enable file logging (defaults tohighcharts-export-server.log).LOGGING_DEST: The path to store log files. ThelogToFileoption also needs to be set to enable file logging (defaults tolog).LOGGING_TO_CONSOLE: Enables or disables showing logs in the console (defaults totrue).LOGGING_TO_FILE: Enables or disables creation of the log directory and saving the log into a .log file (defaults totrue).
UI_ENABLE: Enables or disables the user interface (UI) for the Export Server (defaults tofalse).UI_ROUTE: The endpoint route to which the user interface (UI) should be attached (defaults to/).
OTHER_NODE_ENV: The type of Node.js environment. The value controls whether to include the error's stack in a response or not. Can be development or production (defaults toproduction).OTHER_LISTEN_TO_PROCESS_EXITS: Decides whether or not to attach process.exit handlers (defaults totrue).OTHER_NO_LOGO: Skip printing the logo on a startup. Will be replaced by a simple text (defaults tofalse).OTHER_HARD_RESET_PAGE: Determines whether the page's content should be reset from scratch, including Highcharts scripts (defaults tofalse).OTHER_BROWSER_SHELL_MODE: Decides whether to enable older but much more performant shell mode for the browser (defaults totrue).OTHER_VALIDATION: Decides whether or not to enable validation of options types (defaults totrue).
DEBUG_ENABLE: Enables or disables debug mode for the underlying browser (defaults tofalse).DEBUG_HEADLESS: Controls the mode in which the browser is launched when in the debug mode (defaults tofalse).DEBUG_DEVTOOLS: Decides whether to enable DevTools when the browser is in a headful state (defaults tofalse).DEBUG_LISTEN_TO_CONSOLE: Decides whether to enable a listener for console messages sent from the browser (defaults tofalse).DEBUG_DUMPIO: Redirects browser process stdout and stderr to process.stdout and process.stderr (defaults tofalse).DEBUG_SLOW_MO: Slows down Puppeteer operations by the specified number of milliseconds (defaults to0).DEBUG_DEBUGGING_PORT: Specifies the debugging port (defaults to9222).
To load an additional JSON configuration file, use the --loadConfig <filepath> option. This JSON file can either be manually created or generated through a prompt triggered by the --createConfig <filepath> option. The <filepath> value does not need a .json extension, but the file's content must be valid JSON when using the --loadConfig option.
To supply command line arguments, add them as flags when running the application:
highcharts-export-server --flag1 value --flag2 value ...
For readability reasons, many options passed as CLI arguments have slightly different names, which combine the option and the section it comes from. For example, to set server.enable, use --enableServer. This way, it is clear which option is being set. The full listing of CLI options can be seen by typing the highcharts-export-server --help command in the console.
Available CLI arguments:
--puppeteerArgs: A stringified version of additional Puppeteer arguments sent during browser initialization. The string can be enclosed in [ and ], and the arguments must be separated by the ; character (defaults to Default JSON Config).
--version: Highcharts version to use (defaults tolatest).--cdnUrl: Highcharts CDN URL of scripts to be used (defaults tohttps://code.highcharts.com).--forceFetch: The flag that determines whether to refetch all scripts after each server rerun (defaults tofalse).--cachePath: A directory path where the fetched Highcharts scripts should be placed (defaults to.cache). Since v4.0.3 can be either absolute or relative path.--coreScripts: Highcharts core scripts to fetch (defaults to Default JSON Config).--moduleScripts: Highcharts module scripts to fetch (defaults to Default JSON Config).--indicatorScripts: Highcharts indicator scripts to fetch (defaults to Default JSON Config).--customScripts: Additional custom scripts or dependencies to fetch (defaults to Default JSON Config).
--infile: The input file should include a name and a type (.json or .svg) and must contain a correctly formatted JSON or SVG (defaults tonull).--instr: An input in a form of a stringified JSON.--options: An alias for theinstroption (defaults tonull).--svg: A string containing SVG representation to render as a chart (defaults tonull).--batch: Initiates a batch job with a string containing input/output pairs: "in=out;in=out;.." (defaults tonull).--outfile: The output filename, accompanied by a type (jpeg, png, pdf, or svg). Ignores thetypeoption (defaults tonull).--type: The format of the file to export to. Can be jpeg, png, pdf, or svg (defaults topng).--constr: The constructor to use. Can be chart, stockChart, mapChart, or ganttChart (defaults tochart).--b64: Boolean flag, set to true to receive the chart in the base64 format instead of the binary (defaults tofalse).--noDownload: Boolean flag, set to true to exclude attachment headers from the response (defaults tofalse).--height: The height of the exported chart. Overrides the option in the chart settings (defaults tonull).--width: The width of the exported chart. Overrides the option in the chart settings (defaults tonull).--scale: The scale of the exported chart. Ranges between 0.1 and 5.0 (defaults tonull).--defaultHeight: The default fallback height for exported charts if not set explicitly (defaults to400).--defaultWidth: The default fallback width for exported charts if not set explicitly (defaults to600).--defaultScale: The default fallback scale for exported charts if not set explicitly. Ranges between 0.1 and 5.0 (defaults to1).--globalOptions: Either a stringified JSON or a filename containing global options to be passed into theHighcharts.setOptions()(defaults tonull).--themeOptions: Either a stringified JSON or a filename containing theme options to be passed into theHighcharts.setOptions()(defaults tonull).--rasterizationTimeout: The specified duration, in milliseconds, to wait for rendering a webpage (defaults to1500).
--allowCodeExecution: Controls whether the execution of arbitrary code is allowed during the exporting process (defaults tofalse).--allowFileResources: Controls the ability to inject resources from the filesystem. This setting has no effect when running as a server (defaults tofalse).--customCode: Custom code to execute before chart initialization. It can be a function, code wrapped within a function, or a filename with the .js extension (defaults tonull).--callback: JavaScript code to run during construction. It can be a stringified function or a filename with the .js extension that contains a correct Highcharts callback (defaults tonull).--resources: Additional resources in the form of a stringified JSON. It may containfiles(array of JS filenames),js(stringified JS), andcss(stringified CSS) sections (defaults tonull).--loadConfig: A file containing a pre-defined configuration to use (defaults tonull).--createConfig: Enables setting options through a prompt and saving them in a provided config file (defaults tonull).
--enableServer: If set to true, the server starts on 0.0.0.0 (defaults tofalse).--host: The hostname of the server. Additionally, it starts a server listening on the provided hostname (defaults to0.0.0.0).--port: The port to be used for the server when enabled (defaults to7801).--uploadLimit: The maximum request body size in MB (defaults to3).--serverBenchmarking: Indicates whether to display a message with the duration, in milliseconds, of specific actions that occur on the server while serving a request (defaults tofalse).
--proxyHost: The host of the proxy server to use, if it exists (defaults tonull).--proxyPort: The port of the proxy server to use, if it exists (defaults tonull).--proxyTimeout: The timeout, in milliseconds, for the proxy server to use, if it exists (defaults to5000).
--enableRateLimiting: Enables rate limiting for the server (defaults tofalse).--maxRequests: The maximum number of requests allowed in one minute (defaults to10).--window: The time window, in minutes, for the rate limiting (defaults to1).--delay: The delay duration for each successive request before reaching the maximum limit (defaults to0).--trustProxy: Set this to true if the server is behind a load balancer (defaults tofalse).--skipKey: Allows bypassing the rate limiter and should be provided with theskipTokenargument (defaults tonull).--skipToken: Allows bypassing the rate limiter and should be provided with theskipKeyargument (defaults tonull).
--enableSsl: Enables or disables the SSL protocol (defaults tofalse).--sslForce: If set to true, the server is forced to serve only over HTTPS (defaults tofalse).--sslPort: The port on which to run the SSL server (defaults to443).--sslCertPath: The path to the SSL certificate/key file (defaults tonull).
--minWorkers: The number of minimum and initial pool workers to spawn (defaults to4).--maxWorkers: The number of maximum pool workers to spawn (defaults to8).--workLimit: The number of work pieces that can be performed before restarting the worker process (defaults to40).--acquireTimeout: The duration, in milliseconds, to wait for acquiring a resource (defaults to5000).--createTimeout: The duration, in milliseconds, to wait for creating a resource (defaults to5000).--destroyTimeout: The duration, in milliseconds, to wait for destroying a resource (defaults to5000).--idleTimeout: The duration, in milliseconds, after which an idle resource is destroyed (defaults to30000).--createRetryInterval: The duration, in milliseconds, to wait before retrying the create process in case of a failure (defaults to200).--reaperInterval: The duration, in milliseconds, after which the check for idle resources to destroy is triggered (defaults to1000).--poolBenchmarking: Indicates whether to show statistics for the pool of resources or not (defaults tofalse).
--logLevel: The logging level to be used. Can be 0 - silent, 1 - error, 2 - warning, 3 - notice, 4 - verbose or 5 - benchmark (defaults to4).--logFile: The name of a log file. ThelogToFileandlogDestoptions also need to be set to enable file logging (defaults tohighcharts-export-server.log).--logDest: The path to store log files. ThelogToFileoption also needs to be set to enable file logging (defaults tolog).--logToConsole: Enables or disables showing logs in the console (defaults totrue).--logToFile: Enables or disables creation of the log directory and saving the log into a .log file (defaults totrue).
--enableUi: Enables or disables the user interface (UI) for the Export Server (defaults tofalse).--uiRoute: The endpoint route to which the user interface (UI) should be attached (defaults to/).
--nodeEnv: The type of Node.js environment. The value controls whether to include the error's stack in a response or not. Can be development or production (defaults toproduction).--listenToProcessExits: Decides whether or not to attach process.exit handlers (defaults totrue).--noLogo: Skip printing the logo on a startup. Will be replaced by a simple text (defaults tofalse).--hardResetPage: Determines whether the page's content should be reset from scratch, including Highcharts scripts (defaults tofalse).--browserShellMode: Decides whether to enable older but much more performant shell mode for the browser (defaults totrue).--validation: Decides whether or not to enable validation of options types (defaults totrue).
--enableDebug: Enables or disables debug mode for the underlying browser (defaults tofalse).--headless: Controls the mode in which the browser is launched when in the debug mode (defaults tofalse).--devtools: Decides whether to enable DevTools when the browser is in a headful state (defaults tofalse).--listenToConsole: Decides whether to enable a listener for console messages sent from the browser (defaults tofalse).--dumpio: Redirects browser process stdout and stderr to process.stdout and process.stderr (defaults tofalse).--slowMo: Slows down Puppeteer operations by the specified number of milliseconds (defaults to0).--debuggingPort: Specifies the debugging port (defaults to9222).
Apart from using as a CLI tool, which allows you to run one command at a time, it is also possible to configure the server to accept POST requests. The simplest way to enable the server is to run the command below:
highcharts-export-server --enableServer true
To test if the server is running correctly, you can send a simple POST request, e.g. by using Curl:
curl -H "Content-Type: application/json" -X POST -d '{"options":{"title": {"text": "Chart"}, "xAxis": {"categories": ["Jan", "Feb", "Mar"]}, "series": [{"data": [29.9, 71.5, 106.4]}]}}' 127.0.0.1:7801 -o chart.png
The above should result in a chart being generated and saved in a file named chart.png.
To enable SSL support, add --certPath <path to key/crt> when running the server. Note that the certificate files needs to be named as such:
server.crtserver.key
The server accepts the following arguments in a POST request body.
Available request arguments:
instr: Chart options in the form of JSON or stringified JSON.options: An alias for theinstroption.svg: A string containing SVG representation to render as a chart.outfile: The output filename, accompanied by a type (jpeg, png, pdf, or svg). Ignores thetypeoption.type: The format of an exported chart (can be png, jpeg, pdf or svg). Mimetypes can also be used.constr: The constructor to use (can be chart, stockChart, mapChart or ganttChart).height: The height of the exported chart.width: The width of the exported chart.scale: The scale factor of the exported chart. Use it to improve resolution in PNG and JPEG, for example setting scale to 2 on a 600px chart will result in a 1200px output.globalOptions: Either a JSON or a stringified JSON with global options to be passed intoHighcharts.setOptions().themeOptions: Either a JSON or a stringified JSON with theme options to be passed intoHighcharts.setOptions().resources: Additional resources in the form of a JSON or a stringified JSON. It may containfiles(array of JS filenames),js(stringified JS), andcss(stringified CSS) sections.callback: Stringified JavaScript function to execute in the Highcharts constructor.customCode: Custom code to be executed before the chart initialization. This can be a function, code wrapped within a function, or a filename with the .js extension. BothallowFileResourcesandallowCodeExecutionmust be set to true for the option to be considered.b64: Boolean flag, set to true to receive the chart in the base64 format instead of the binary.noDownload: Boolean flag, set to true to exclude attachment headers from the response.
The server responds to application/json, multipart/form-data, and URL encoded requests.
CORS is enabled for the server.
It is recommended to run the server using pm2 unless running in a managed environment/container. Please refer to the pm2 documentation for details on how to set this up.
-
POST
/: An endpoint for exporting charts./:filename- An endpoint for exporting charts with a specified filename parameter to save the chart to. The file will be downloaded with the {filename}.{type} name (thenoDownloadmust be set to false)./version_change/:newVersion: An authenticated endpoint allowing the modification of the Highcharts version on the server through the use of a token.
-
GET
/: An endpoint to perform exports through the user interface the server allows it./health: An endpoint for outputting basic statistics for the server.
If the HIGHCHARTS_ADMIN_TOKEN is set, you can use the POST /version_change/:newVersion route to switch the Highcharts version on the server at runtime, ie. without restarting or redeploying the application.
A sample request to change the version to 10.3.3 is as follows:
curl -H 'hc-auth: <YOUR AUTH TOKEN>' -X POST <SERVER URL>/change_hc_version/10.3.3
e.g.
curl -H 'hc-auth: 12345' -X POST 127.0.0.1:7801/change_hc_version/10.3.3
This is useful to e.g. upgrade to the latest HC version without downtime.
Finally, the Export Server can also be used as a Node.js module to simplify integrations:
// Import the Highcharts Export Server module
const exporter = require('highcharts-export-server');
// Options correspond to the available CLI/HTTP arguments described above
const customOptions = {
export: {
type: 'png',
options: {
title: {
text: 'My Chart'
},
xAxis: {
categories: ["Jan", "Feb", "Mar", "Apr"]
},
series: [
{
type: 'line',
data: [1, 3, 2, 4]
},
{
type: 'line',
data: [5, 3, 4, 2]
}
]
}
}
};
// Logic must be triggered in an asynchronous function
(async () => {
// Must initialize exporting before being able to export charts
await exporter.initExport();
// Perform an export
await exporter.startExport(options, async (error, data) => {
// The export result is now in the `data` (it will be Base64 encoded)
console.log(data.result);
// Kill the pool when we are done with it
await exporter.killPool();
});
})();
In order for exporting to work as intended, the initExport() function must be called before running any export-related functions (singleExport(), batchExport(), or startExport()). This initializes all required mechanisms, such as script fetching, cache setting, resource pooling, and browser startup.
This package supports both CommonJS and ES modules.
highcharts-export-server module
-
async function startServer(serverOptions = {}): Starts an HTTP and/or HTTPS server based on the provided configuration. TheserverOptionsobject contains server-related properties (refer to theserversection in the./lib/schemas/config.jsfile for details).-
@param {Object} [serverOptions={}]- The configuration object containingserveroptions. This object may include a partial or complete set of theserveroptions. If the options are partial, missing values will default to the current global configuration. The default value is an empty object. -
@returns {Promise<void>}A Promise that resolves when the server is either not enabled or no valid Express app is found, signaling the end of the function's execution. -
@throws {ExportError}Throws anExportErrorif the server cannot be configured and started.
-
-
function closeServers(): Closes all servers associated with Express app instance. -
function getServers(): Get all servers associated with Express app instance.@returns {Array<Object>}Servers associated with Express app instance.
-
function getExpress(): Get the Express instance.@returns {Express}The Express instance.
-
function getApp(): Get the Express app instance.@returns {Express}The Express app instance.
-
function enableRateLimiting(rateLimitingOptions): Enable rate limiting for the server.@param {Object} rateLimitingOptions- The configuration object containingrateLimitingoptions. This object may include a partial or complete set of therateLimitingoptions. If the options are partial, missing values will default to the current global configuration.
-
function use(path, ...middlewares): Apply middleware(s) to a specific path.@param {string} path- The path to which the middleware(s) should be applied.@param {...Function} middlewares- The middleware function(s) to be applied.
-
function get(path, ...middlewares): Set up a route with GET method and apply middleware(s).@param {string} path- The path to which the middleware(s) should be applied.@param {...Function} middlewares- The middleware function(s) to be applied.
-
function post(path, ...middlewares): Set up a route with POST method and apply middleware(s).@param {string} path- The path to which the middleware(s) should be applied.@param {...Function} middlewares- The middleware function(s) to be applied.
-
function getOptions(getCopy = true): Retrieves a copy of the global options object or an original global options object, based on thegetCopyflag.-
@param {boolean} [getCopy=true]- Specifies whether to return a copied object of the global options (true) or a reference to the global options object (false). The default value istrue. -
@returns {Object}A copy of the global options object, or a reference to the global options object.
-
-
function updateOptions(newOptions, getCopy = false, strictCheck = true): Updates and returns the global options object or a copy of the global options object, based on thegetCopyflag. ThenewOptionsobject can be strictly validated depending on thestrictCheckflag.-
@param {Object} newOptions- An object containing the new options to be merged into the global options. -
@param {boolean} [getCopy=false]- Determines whether to merge the new options into a copy of the global options object (true) or directly into the global options object (false). The default value isfalse. -
@param {boolean} [strictCheck=true]- Determines if stricter validation should be applied. The default value istrue. -
@returns {Object}The updated options object, either the modified global options or a modified copy, based on the value ofgetCopy.
-
-
function mapToNewOptions(oldOptions): Maps old-structured configuration options (PhantomJS-based) to a new format (Puppeteer-based). This function converts flat, old-structured options into a new, nested configuration format based on a predefined mapping provided in thenestedPropsobject. The new format is used for Puppeteer, while the old format was used for PhantomJS.-
@param {Object} oldOptions- The old, flat configuration options to be converted. -
@returns {Object}A new object containing options structured according to the mapping defined in thenestedPropsobject or an empty object if the providedoldOptionsis not a correct object.
-
-
function validateOption(name, configOption, strictCheck = true): Validates a specified option using the corresponding validator from the configuration object. Returns the original option if the validation is disabled globally.-
@param {string} name- The name of the option to validate. -
@param {any} configOption- The value of the option to validate. -
@param {boolean} [strictCheck=true]- Determines if stricter validation should be applied. The default value istrue. -
@returns {any}The parsed and validated value of the option.
-
-
function validateOptions(configOptions, strictCheck = true): Validates the provided configuration options for the exporting process. Returns the original option if the validation is disabled globally.-
@param {Object} configOptions- The configuration options to be validated. -
@param {boolean} [strictCheck=true]- Determines if stricter validation should be applied. The default value istrue. -
@returns {Object}The parsed and validated configuration options object.
-
-
async function initExport(initOptions = {}): Initializes the export process. Tasks such as configuring logging, checking the cache and sources, and initializing the resource pool occur during this stage.This function must be called before attempting to export charts or set up a server.
@param {Object} [initOptions={}]- TheinitOptionsobject, which may be a partial or complete set of options. If the options are partial, missing values will default to the current global configuration. The default value is an empty object.
-
async function singleExport(options): Starts a single export process based on the specified options and saves the resulting image to the provided output file.-
@param {Object} options- Theoptionsobject, which should include settings from theexportandcustomLogicsections. It can be a partial or complete set of options from these sections. The object must contain at least one of the followingexportproperties:infile,instr,options, orsvgto generate a valid image. -
@returns {Promise<void>}A Promise that resolves once the single export process is completed. -
@throws {ExportError}Throws anExportErrorif an error occurs during the single export process.
-
-
async function batchExport(options): Starts a batch export process for multiple charts based on information provided in thebatchoption. Thebatchis a string in the following format: "infile1.json=outfile1.png;infile2.json=outfile2.png;...". Results are saved to the specified output files.-
@param {Object} options- Theoptionsobject, which should include settings from theexportandcustomLogicsections. It can be a partial or complete set of options from these sections. It must contain thebatchoption from theexportsection to generate valid images. -
@returns {Promise<void>}A Promise that resolves once the batch export processes are completed. -
@throws {ExportError}Throws anExportErrorif an error occurs during any of the batch export process.
-
-
async function startExport(exportingOptions, endCallback): Starts an export process. TheexportingOptionsparameter is an object that should include settings from theexportandcustomLogicsections. It can be a partial or complete set of options from these sections. If partial options are provided, missing values will be merged with the current global options.The
endCallbackfunction is invoked upon the completion of the export, either successfully or with an error. Theerrorobject is provided as the first argument, and thedataobject is the second, containing the Base64 representation of the chart in theresultproperty and the complete set of options in theoptionsproperty.-
@param {Object} exportingOptions- TheexportingOptionsobject, which should include settings from theexportandcustomLogicsections. It can be a partial or complete set of options from these sections. If the provided options are partial, missing values will be merged with the current global options. -
@param {Function} endCallback- The callback function to be invoked upon finalizing the export process or upon encountering an error. The first argument is theerrorobject, and the second argument is thedataobject, which includes the Base64 representation of the chart in theresultproperty and the full set of options in theoptionsproperty. -
@returns {Promise<void>}This function does not return a value directly. Instead, it communicates results via theendCallback. -
@throws {ExportError}Throws anExportErrorif there is a problem with processing input of any type. The error is passed into theendCallbackfunction and processed there.
-
-
async function killPool(): Terminates all workers in the pool, destroys the pool, and closes the browser instance.@returns {Promise<void>}A Promise that resolves once all workers are terminated, the pool is destroyed, and the browser is successfully closed.
-
async function shutdownCleanUp(exitCode = 0): Performs cleanup operations to ensure a graceful shutdown of the process. This includes clearing all registered timeouts/intervals, closing active servers, terminating resources (pages) of the pool, pool itself, and closing the browser.@param {number} [exitCode=0]- The exit code to use withprocess.exit(). The default value is0.
-
function log(...args): Logs a message with a specified log level. Accepts a variable number of arguments. The arguments after thelevelare passed toconsole.logand/or used to construct and append messages to a log file.-
@param {...unknown} args- An array of arguments where the first is the log level and the remaining are strings used to build the log message. -
@returns {void}Exits the function execution if attempting to log at a level higher than allowed.
-
-
function logWithStack(newLevel, error, customMessage): Logs an error message along with its stack trace. Optionally, a custom message can be provided.-
@param {number} newLevel- The log level. -
@param {Error} error- The error object containing the stack trace. -
@param {string} customMessage- An optional custom message to be included in the log alongside the error. -
@returns {void}Exits the function execution if attempting to log at a level higher than allowed.
-
-
function logZodIssues(newLevel, issues, customMessage): Logs an error message related to Zod validation issues. Optionally, a custom message can be provided.@param {number} newLevel- The log level.@param {Error[]} issues- An array of Zod validation issues.@param {string} customMessage- An optional custom message to be included in the log alongside the error.
-
function setLogLevel(level): Sets the log level to the specified value. Log levels are (0= no logging,1= error,2= warning,3= notice,4= verbose, or5= benchmark).@param {number} level- The log level to be set.
-
function enableConsoleLogging(toConsole): Enables console logging.@param {boolean} toConsole- The flag for setting the logging to the console.
-
function enableFileLogging(dest, file, toFile): Enables file logging with the specified destination and log file name.@param {string} dest- The destination path where the log file should be saved.@param {string} file- The name of the log file.@param {boolean} toFile- A flag indicating whether logging should be directed to a file.
Samples and tests for every mentioned export method can be found in the ./samples and ./tests folders. Detailed descriptions are available in their corresponding sections on the Wiki.
Typing highcharts-export-server --v will display information about the current version of the Export Server, and highcharts-export-server --h will display information about available CLI options.
All path-related options (such as those for loading additional resources and logic) can be either relative or absolute. If they are relative, they will be resolved based on the current working directory (the directory from which the Node.js process was started). This is especially important to remember when running a custom script in your application that imports the highcharts-export-server npm package and uses provided exporting API functions.
At some point during the transition process from the PhantomJS solution, certain options were deprecated. Here is a list of options that no longer work with the server based on Puppeteer:
asyncasyncRenderingtmpdirdataOptionsqueueSize
Additionally, some options are now named differently due to the new structure and categorization. Here is a list of old names and their corresponding new names (old name -> new name):
fromFile->loadConfigsslOnly->forceorsslForcesslPath->sslCertPathrateLimit->maxRequestsworkers->maxWorkers
If you depend on any of the above options, the optimal approach is to directly change the old names to the new ones in the options. However, you don't have to do it manually, as there is a utility function called mapToNewOptions that can easily transfer the old-structured options to the new format. For an example, refer to the ./samples/module/optionsPhantom.js file.
If you need to set the height or width of the chart, it can be done in two ways:
Set it in the chart config under:
Set it in the exporting config under:
The latter is preferred, as it allows you to set separate sizing when exporting and when displaying the chart on your web page.
Like previously mentioned, there are multiple ways to set and prioritize options, and the height, width and scale are no exceptions here. The priority goes like this:
- The
height,width, andscaleoptions from theexportsection of the provided options (CLI, JSON, envs). - The
sourceHeight,sourceWidthandscalefrom thechart.exportingsection of chart's Highcharts options. - The
heightandwidthfrom thechartsection of chart's Highcharts options. - The
sourceHeight,sourceWidthandscalefrom thechart.exportingsection of chart's Highcharts global options, if provided. - The
heightandwidthfrom thechartsection of chart's Highcharts global options, if provided. - The
sourceHeight,sourceWidthandscalefrom thechart.exportingsection of chart's Highcharts theme options, if provided. - The
heightandwidthfrom thechartsection of chart's Highcharts theme options, if provided. - If no options are found to this point, the default values will be used (
height = 400,width = 600andscale = 1).
The Export Server attaches event listeners to process.exit, uncaughtException and signals such as SIGINT, SIGTERM and SIGHUP. This is to make sure that there are no memory leaks or zombie processes if the application is unexpectedly terminated.
Listeners are also attached to handle uncaught exceptions. If an exception occurs, the entire pool and browser instance are terminated, and the application is shut down.
If you do not want this behavior, start the server with --listenToProcessExits false.
Be aware though, that if you disable this and you do not take great care to manually kill the pool of resources along with a browser instance, your server will bleed memory when the app is terminated.
If --resources argument is not set and a file named resources.json exists in the folder from which the CLI tool was ran, it will use the resources.json file.
The Export Server utilizes a pool of workers, where each worker is a Puppeteer process (browser instance's page) responsible for the actual chart rasterization. The pool size can be set with the --minWorkers and --maxWorkers options, and should be tweaked to fit the hardware on which you are running the server.
It is recommended that you start with the default 4, and work your way up (or down if 8 is too many for your setup, and things are unstable) gradually. The tests/other/stress-test.js script can be used to test the server and expects the server to be running on port 7801.
Each of the workers has a maximum number of requests it can handle before it restarts itself to keep everything responsive. This number is 40 by default, and can be tweaked with --workLimit. As with --minWorkers and --maxWorkers, this number should also be tweaked to fit your use case. Also, the --acquireTimeout option is worth to mention as well, in case there would be problems with acquiring resources. It is set in miliseconds with 5000 as a default value. Lastly, the --createTimeout and --destroyTimeout options are similar to the --acquireTimeout but for resource's create and destroy actions.
In order to use the Export Server, Highcharts needs to be injected into the export template (see the ./templates folder for reference).
Since version 3.0.0, Highcharts is fetched in a Just-In-Time manner, making it easy to switch configurations. It is no longer required to explicitly accept the license, as in older versions. However, the Export Server still requires a valid Highcharts license to be used.
Since version 3.0.0, when using in automated deployments, the configuration can be loaded either using environment variables or a JSON configuration file.
For a reference on available variables, refer to the configuration section above.
If you are using the Export Server as a dependency in your application, depending on your setup, it may be possible to set the environment variables in the package.json file as follows:
On Linux/Mac OS X:
{
"scripts": {
"preinstall": "export <variable1>=<value1>&&<variable2>=<value2>&&..."
}
}
On Windows:
{
"scripts": {
"preinstall": "set <variable1>=<value1>&&<variable2>=<value2>&&..."
}
}
When fetching the built Highcharts library, the default behaviour is to fetch them from https://code.highcharts.com.
Does your Linux server not have Arial or Calibri? Puppeteer uses the system installed fonts to render pages. Therefore the Highcharts Export Server requires fonts to be properly installed on the system in order to use them to render charts.
Note that the default font-family config in Highcharts is "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif".
Fonts are installed differently depending on your system. Please follow the below guides for font installation on most common systems.
Install your desired fonts with the Font Book app, or place it in /Library/Fonts/ (system) or ~/Library/Fonts/ (user).
Copy or move the TTF file to the /usr/share/fonts/truetype (may require sudo privileges):
mkdir -p /usr/share/fonts/truetype
cp yourFont.ttf /usr/share/fonts/truetype/
fc-cache -fv
Copy or move the TTF file to C:\Windows\Fonts\:
copy yourFont.ttf C:\Windows\Fonts\yourFont.ttf
If you need Google Fonts in your custom installation, they can be had here: https://github.com/google/fonts.
Download them, and follow the above instructions for your OS.
Version 4.0.0 introduced a new mode that allows debugging the Puppeteer browser instance. This is particularly useful when setting up a custom server. It helps to delve into the implementation, observe how things work, and analyze and resolve potential problems.
Setting the --enableDebug to true passes all debug options to the puppeteer.launch() function on startup. Together with the --headless option set to false, it launches the browser in a headful state providing a full version of the browser with a graphical user interface (GUI). While this serves as the minimal configuration to simply display the browser, Puppeteer offers additional options. Here is the full list:
--enableDebug: Enables passing debug options to thepuppeteer.launch().--headless: Sets the browser's state.--devtools: Allows turning on the DevTools automatically upon launching the browser.--listenToConsole: Allows listening to messages from the browser's console.--dumpio: Redirects the browser's processstdoutandstderrtoprocess.stdoutandprocess.stderrrespectively.--slowMo: Delays Puppeteer operations by a specified amount of milliseconds.--debuggingPort: Specifies a debugging port for a browser.
There are two main ways to debug code:
-
By adding a
debuggerstatement within any client-side code (e.g., inside apage.evaluatecallback). With the--devtoolsoption set to true, the code execution will stop automatically. -
By running the Export Server with the
--inspect-brk=<PORT>flag, and adding adebuggerstatement within any server-side code. Subsequently, navigate tochrome://inspect/, input the server's IP address and port (e.g.,localhost:9229) in the Configure section. Clicking 'inspect' initiates debugging of the server-side code.
The npm run start:debug script from the package.json allows debugging code using both methods simultaneously. In this setup, client-side code is accessible from the devTools of a specific Puppeteer browser's page, while server-side code can be debugged from the devTools of chrome://inspect/.
For more details, refer to the Puppeteer debugging guide.
-
Ensure to set the
--headlessto false when the--devtoolsis set to true. Otherwise, there's a possibility that while DevTools may be recognized as enabled, the browser won't be displayed. Moreover, if adebuggeris caught within the browser, it might lead to the entire debugging process getting stuck. In such scenarios, you can set the IP address and port (using the value of the--debuggingPortoption) the same way as described in the section for debugging server-side code. This allows you to access DevTools and resume code execution. -
When using the
--listenToConsoleand--dumpiooptions, be aware that the server's console may become 'polluted' with messages from the browser. If you prefer to avoid this, simply set both options to false.
In cases of batch exports, using the HTTP server is faster than the CLI. This is due to the overhead of starting Puppeteer for each job when using the CLI.
So it is better to write a bash script that starts the server and then performs a set of POSTS to it through e.g. Curl if not wanting to host the Export Server as a service.
Alternatively, you can use the --batch switch if the output format is the same for each of the input files to process:
highcharts-export-server --batch "infile1.json=outfile1.png;infile2.json=outfile2.png;..."
Other switches can be combined with this switch.
The system requirements largely depend on your use case.
The application is largely CPU and memory bound, so for heavy-traffic situations, it needs a fairly beefy server. It is recommended that the server has at least 1GB of memory regardless of traffic, and more than one core.
MIT. Note that a valid Highcharts License is also required to do exports.