Socket
Socket
Sign inDemoInstall

amcharts

Package Overview
Dependencies
0
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    amcharts

http://amcharts.com


Version published
Weekly downloads
1.2K
increased by32.79%
Maintainers
1
Install size
9.81 MB
Created
Weekly downloads
 

Readme

Source

amCharts Export

Version: 1.1.8

Description

This plugin adds export capabilities to all amCharts products - charts and maps.

It allows annotating and exporting chart or related data to various bitmap, vector, document or data formats, such as PNG, JPG, PDF, SVG, JSON, XLSX and many more.

Important notice

Please note that due to security measures implemented in modern browsers, some or all export options might not work if the web page is loaded locally (via file:///) or contain images loaded from different host than the web page itself.

Usage

1) Include the minified version of file of this plugin as well as the

bundled CSS file. I.e.:

<script src="amcharts/plugins/export/export.min.js"></script>
<link  type="text/css" href="amcharts/plugins/export/export.css" rel="stylesheet">

Or if you'd rather use amCharts CDN:

<script src="//cdn.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link  type="text/css" href="//cdn.amcharts.com/lib/3/plugins/export/export.css" rel="stylesheet">

(this needs to go after all the other amCharts includes)

2) Enable export with default options:

AmCharts.makeChart( "chartdiv", {
  ...,
  "export": {
    "enabled": true
  }
} );

... OR set your own custom options:

AmCharts.makeChart( "chartdiv", {
  ...,
  "export": {
    "enabled": true,
    "menu": [ {
      "class": "export-main",
      "menu": [ {
        "label": "Download",
        "menu": [ "PNG", "JPG", "CSV" ]
      }, {
        "label": "Annotate",
        "action": "draw",
        "menu": [ {
          "class": "export-drawing",
          "menu": [ "PNG", "JPG" ]
        } ]
      } ]
    } ]
  }
} );

Loading external libraries needed for operation of this plugin

The plugin relies on a number of different libraries, to export images, draw annotations or generate download files.

Those libraries need to be loaded for the plugin to work properly.

There are two ways to load them. Choose the one that is right:

1) Automatic (preferred)

All libraries required for plugin operation are included withing plugins /libs subdirectory.

If you want the plugin to load them on-demand (when it's needed for a certain operation), make sure you've set the path property in your chart setup.

If you are using relative url, note that it is relative to the web page you are displaying your chart on, not the export.js library.

In case you've moved the libs folder you need to tell the plugin where it is "libs": { "path": "../libs/" }

2) Manual

You can also load all those JavaScript libraries by <script> tags. Since loading of libraries is on by default you will need to turn it off by setting "libs": { "autoLoad": false }

Here is a full list of the files that need to be loaded for each operation:

FileLocated inRequired for
fabric.min.jslibs/fabric.js/Any export operation
FileSaver.jslibs/FileSaver.js/Used to offer download files
pdfmake.min.jslibs/pdfmake/Export to PDF format
vfs_fonts.jslibs/pdfmake/Export to PDF format
jszip.jslibs/jszip/Export to XLSX format
xlsx.jslibs/xlsx/Export to XLSX format

Complete list of available export settings

PropertyDefaultDescription
backgroundColor#FFFFFFRGB code of the color for the background of the exported image
enabledtrueEnables or disables export functionality
divIdID or a reference to div object in case you want the menu in a separate container.
fabric{}Overwrites the default drawing settings (fabricJS library)
fallback{}Holds the messages to guide the user to copy the generated output; false will disable the fallback feature
fileNameamChartsA file name to use for generated export files (an extension will be appended to it based on the export format)
legend{}Places the legend in case it is within an external container (skip to chapter)
libs3rd party required library settings (see the above section)
menu[]A list of menu or submenu items (see the next chapter for details)
pdfMake{}Overwrites the default settings for PDF export (pdfMake library)
positiontop-rightA position of export icon. Possible values: "top-left", "top-right" (default), "bottom-left", "bottom-right"
removeImagestrueIf true export checks for and removes "tainted" images that area lodead from different domains
delayGeneral setting to delay the capturing of the chart (skip to chapter)

Configuring export menu

Plugin includes a way to completely control what is displayed on export menu. You can set up menus, sub-menus, down to any level. You can even add custom items there that execute your arbitrary code on click. It's so configurable it makes us sick with power ;)

The top-level menu is configured via menu property under export. It should always be an array, even if you have a single item in it.

The array items could be either objects or format codes. Objects will allow you to specify labels, action, icon, child items and even custom code to be executed on click.

Simple format codes will assume you need an export to that format.

Simple menu setup

Here's a sample of the simple menu setup that allows export to PNG, JPG and CSV:

"export": {
  "enabled": true,
  "menu": [ {
    "class": "export-main",
    "menu": [ "PNG", "JPG", "CSV" ]
  } ]
}

The above will display a menu out of three options when you hover on export icon:

  • PNG
  • JPG
  • CSV

When clicked the plugin will trigger export to a respective format.

If that is all you need, you're all set.

Please note that we have wrapped out menu into another menu item, so that only the icon is displayed until we roll over the icon. This means that technically we have a two-level hierarchical menu.

If we opmitted that first step, the chart would simply display a format list right there on the chart.

Advanced menu setup

However, you can do so much more with the menu.

Let's add more formats and organize image and data formats into separate submenus.

To add a submenu to a menu item, simply add a menu array as its own property:

"export": {
  "enabled": true,
  "menu": [ {
    "class": "export-main",
    "menu": [ {
      "label": "Download as image",
      "menu": [ "PNG", "JPG", "SVG" ]
    }, {
      "label": "Download data",
      "menu": [ "CSV", "XLSX" ]
    } ]
  } ]
}

Now we have a hierarchical menu with the following topology:

  • Download as image
    • PNG
    • JPG
    • SVG
  • Download data
    • CSV
    • XLSX

We can mix "string" and "object" formats the way we see fit, i.e.:

"export": {
  "menu": [
    "PNG", 
    { "label": "JPEG",
      "format": "JPG" },
    "SVG"
  ]
}

The magic does not end here, though.

Adding custom click events to menu items

Just like we set label and format properties for menu item, we can set click as well.

This needs to be a function reference. I.e.:

"export": {
  "menu": [
    "PNG", 
    { "label": "JPEG",
      "click": function () {
        alert( "Clicked JPEG. Wow cool!" );
      } },
    "SVG"
  ]
}

Adding external legend

In case you have an external legend you need to define the position where it should get placed in your export. By default it obtains the dimensions from the container but you can optionally overwrite those settings as shown below.

"export": {
  "legend": {
    "position": "top",  // or "right", "bottom" and "left" are possible
    "width": 200,       // optional
    "height": 200       // optional
  }
}

Menu item reviver

By passing the menuReviver callback you are to adapt or completely replace the generated menu item before it gets appended to the list (ul). It retrieves two arguments and it needs to return a valid DOM element.

"export": {
  "menuReviver": function(item,li) {
    li.setAttribute("class","something special");
    return li;
  }
}

Menu walker

In case you don't like our structure, go ahead and write your own recursive function to create the menu by the given list configured through menu.

"export": {
  "menuWalker": function(list,container) {
    // some magic to generate the nested lists using the given list
  }
}

Printing the chart

Adding menu item to print the chart or map is as easy as adding export ones. You just use "PRINT" as format. I.e.:

"export": {
  "menu": [
    "PNG", 
    "SVG",
    "PRINT"
  ]
}

Or if you want to change the label:

"export": {
  "menu": [
    "PNG", 
    "SVG",
    {
      "format": "PRINT",
      "label": "Print Chart"
    }
  ]
}

Annotating the chart before export

OK, this one is so cool, you'll need a class 700 insulation jacket.

By default each menu item triggers some kind of export. You can trigger an "annotation" mode instead by including "action": "draw" instead.

"export": {
  "menu": [ {
    "class": "export-main",
    "menu": [ {
      "label": "Download",
      "menu": [ "PNG", "JPG", "CSV", "XLSX" ]
    }, {
      "label": "Annotate",
      "action": "draw"
    } ]
  } ]
}

Now, when you click on the "Annotate" item in the menu, the chart will turn into an image editor which you can actual draw on.

As cool as it may sound, there's little we can do if the annotated chart if we can't save the result image.

That's where sub-menus come for the rescue again:

"export": {
  "menu": [ {
    "class": "export-main",
    "menu": [ {
      "label": "Download",
      "menu": [ "PNG", "JPG", "CSV", "XLSX" ]
    }, {
      "label": "Annotate",
      "action": "draw",
      "menu": [ {
        "class": "export-drawing",
        "menu": [ "JPG", "PNG", "SVG", PDF" ]
      } ]
    } ]
  } ]
}

Now, when you turn on the annotation mode, a submenu will display, allowing to export the image into either PNG,JPG,SVG or PDF.

And that's not even the end of it. You can add menu items to cancel, undo, redo.

"export": {
  "menu": [ {
    "class": "export-main",
    "menu": [ {
      "label": "Download",
      "menu": [ "PNG", "JPG", "CSV", "XLSX" ]
    }, {
      "label": "Annotate",
      "action": "draw",
      "menu": [ {
        "class": "export-drawing",
        "menu": [ {
          "label": "Edit",
          "menu": [ "UNDO", "REDO", "CANCEL" ]
        }, {
          "label": "Save",
          "format": "PNG"
        } ]
      } ]
    } ]
  } ]
}

If you need to filter the drawn elements you can pass the reviver method in your global configuration or pass it to the capture method if you export manually. To hide e.G. all free labels you can simply do so like following:

"export": {
  "menu": ["PNG"],
  "reviver": function(obj) {
    if ( obj.className == "amcharts-label" ) {
      obj.opacity = 0;
    }
  }
}

Delay the capturing before export

In some cases you may want to delay the capturing to highlight the current value, therefore you simply need to define the 'delay' property in your menu item.

"export": {
  "delay": 3,

  // or specifically on individual menu items

  "menu": [{
    "label": "PNG",
    "format": "PNG",
    "delay": 3
  }]
}

Events

Since version 1.1.7 the plugin has some events to celebrate with. For example the afterCapture event allows you to add some texts or images which can't be seen on the regular chart but on the generated export - Magic! This allows you to point to your website from where the chart has been downloaded or simply add some fancy watermark.

"export": {
  "afterCapture": function(menuConfig) {
      var text = new fabric.Text("This is shown on exported image only", {
        top: 50,
        left: 100,
        family: this.setup.chart.fontFamily,
        size: this.setup.chart.fontSize * 2
      });
      this.setup.fabric.add(text);
  },

  // or specifically on individual menu items

  "menu": [{
    "label": "PNG",
    "format": "PNG",  
    "afterCapture": function(menuConfig) {
        var text = new fabric.Text("This is shown on exported image only", {
          top: 50,
          left: 100,
          family: this.setup.chart.fontFamily,
          size: this.setup.chart.fontSize * 2
        });
        this.setup.fabric.add(text);
    }
  }]
}

A list of the events

NameArgumentsDescription
beforeCapturemenu item setupCalled before the SVG element gets converted
afterCapturemenu item setupCalled right before the passed callback of the capture method

A list of menu item properties

PropertyDescription
actionSet to "draw" if you want the item to trigger annotation mode
classClass name applied to the tag
clickFunction handler invoked upon click on menu item
formatA format to export chart/map to upon click (see below for a list of available formats)
iconIcon file (will use chart's path if the URL is not full)
labelText label to be displayed
menuAn array of submenu items
titleA title attribute of the link
backgroundColorThe background color of the canvas
fileNameA file name to use for generated export files (an extension will be appended to it based on the export format)
extensionFile extension for the generated export file (uses format default if not defined)
mimeTypeInternet media type to generate the export file (usses format default if not defined)
pageSizeA string or { width: number, height: number } (details)
pageOrientationBy default we use portrait, you can change it to landscape if you wish (details)
pageMargins[left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins (details)
contentArray of elements which represents the content (details)
freeDrawingBrushObject which hold the settings of the brush e.G.: { color: "#FF00FF" }
multiplierScale factor for the generated image
losslessFlag to print the actual vector graphic instead of buffered bitmap (print option only, experimental)
delayA numeric value to delay the capturing in seconds (details)

Available format values:

  • JPG
  • PNG
  • SVG
  • CSV
  • JSON
  • PDF
  • XLSX
  • PRINT

Exporting to PDF

When exporting to PDF, you can set and modify the content of the resulting document. I.e. add additional text and/or modify image size, etc.

To do that, you can use menu item's content property.

Each item in content represents either a text line (string) or an exported image.

To add a text line, simply use a string. It can even be a JavaScript variable or a function that returns a string.

To include exported image, use image: "reference".

Additionally, you can add fit property which is an array of pixel dimensions, you want the image to be scaled to fit into.

Here's an example of such export menu item:

{
  "format": "PDF",
  "content": [ "Saved from:", window.location.href, {
    "image": "reference",
    "fit": [ 523.28, 769.89 ] // fit image to A4
  } ]
}
PropertyDescription
pageSizea string or { width: number, height: number }
pageOrientationby default we use portrait, you can change it to landscape if you wish
pageMargins[left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
contentarray of elements which represents the content (full description)
PagesizeDimensions in pixel
4A0[4767.87, 6740.79]
2A0[3370.39, 4767.87]
A0[2383.94, 3370.39]
A1[1683.78, 2383.94]
A2[1190.55, 1683.78]
A3[841.89, 1190.55]
A4[595.28, 841.89]
A5[419.53, 595.28]
A6[297.64, 419.53]
A7[209.76, 297.64]
A8[147.40, 209.76]
A9[104.88, 147.40]
A10[73.70, 104.88]
B0[2834.65, 4008.19]
B1[2004.09, 2834.65]
B2[1417.32, 2004.09]
B3[1000.63, 1417.32]
B4[708.66, 1000.63]
B5[498.90, 708.66]
B6[354.33, 498.90]
B7[249.45, 354.33]
B8[175.75, 249.45]
B9[124.72, 175.75]
B10[87.87, 124.72]
C0[2599.37, 3676.54]
C1[1836.85, 2599.37]
C2[1298.27, 1836.85]
C3[918.43, 1298.27]
C4[649.13, 918.43]
C5[459.21, 649.13]
C6[323.15, 459.21]
C7[229.61, 323.15]
C8[161.57, 229.61]
C9[113.39, 161.57]
C10[79.37, 113.39]
RA0[2437.80, 3458.27]
RA1[1729.13, 2437.80]
RA2[1218.90, 1729.13]
RA3[864.57, 1218.90]
RA4[609.45, 864.57]
SRA0[2551.18, 3628.35]
SRA1[1814.17, 2551.18]
SRA2[1275.59, 1814.17]
SRA3[907.09, 1275.59]
SRA4[637.80, 907.09]
EXECUTIVE[521.86, 756.00]
FOLIO[612.00, 936.00]
LEGAL[612.00, 1008.00]
LETTER[612.00, 792.00]
TABLOID[792.00, 1224.00]

Styling the export menu

The plugin comes with a default CSS file export.css. You just need to include it on your page.

Feel free to override any styles defined in it, create your own version and modify as you see fit.

If you choose to modify it, we suggest creating a copy so it does not get overwritten when you update amCharts or plugin.

Plugin API

We explained how you can define custom functions to be executed on click on export menu items.

Those functions can tap into plugin's methods to augment it with some custom functionality.

Here's an example:

"export": {
  menu: [ {
    label: "JPG",
    click: function() {
      this.capture({},function() {
        this.toJPG( {}, function( data ) {
          this.download( data, "image/jpg", "amCharts.jpg" );
        });
      });
    }
  } ]
}

The above will use plugin's internal capture method to capture it's current state and toJPG() method to export the chart to JPEG format.

Yes, you're right, it's the exact equivalent of just including "JPG" string. The code is here for the explanatory purposes.

Here's a full list of API functions available for your consumption:

FunctionParametersDescription
toJPG(object) options, (function) callbackPrepares a JPEG representation of the chart and passes the binary data to the callback function
toPNG(object) options, (function) callbackPrepares a PNG representation of the chart and passes the binary data to the callback function
toSVG(object) options, (function) callbackPrepares a SVG representation of the chart and passes the binary data to the callback function
toPDF(object) options, (function) callbackPrepares a PDF representation of the chart and passes the binary data to the callback function
toJSON(object) options, (function) callbackPrepares a JSON and passes the plain data to the callback function
toCSV(object) options, (function) callbackPrepares a CSV and passes the plain data to the callback function
toXLSX(object) options, (function) callbackPrepares a XLSX representation of the chart and passes the binary data to the callback function
toBlob(object) options, (function) callbackPrepares a BLOB and passes the instance to the callback function
toCanvas(object) options, (function) callbackPrepares a Canvas and passes the element to the callback function
toArray(object) options, (function) callbackPrepares an Array and passes the data to the callback function
toImage(object) options, (function) callbackGenerates an image element which holds the output in an embedded base64 data url

Fallback for IE9

Unfortunately our lovely Internet Explorer 9 does not allow us to offer downloads which has been locally generated. For those cases the plugin will place an overlay on top of the chart to place an img or textarea to let the user manually save the generated output with some instructions above. To avoid having a bigger payload by including senseless polyfills to your site, you may need to add following metatag in your <head> of your HTML document.

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

This feature will kick in by default if you want to disable it simply pass false to the fallback parameter.

"export": {
  fallback: false
}

In case you want to change our default messages you can modify it like following.

"export": {
  fallback: {
    text: "CTRL + C to copy the data into the clipboard.",
    image: "Rightclick -> Save picture as... to save the image."
  }
}

Requirements

This plugin requires at least 3.13 version of JavaScript Charts, JavaScript Stock Chart or JavaScript Maps.

The export will also need relatively recent browsers.

IE10 and up are supported.

Partial support for IE9; Fallback mechanism.

IE8 and older are not supported I'm afraid. Hey, it's time to upgrade!

Demos

They're all in subdirectory /examples.

Extending this plugin

You're encouraged to modify, extend and make derivative plugins out of this plugin.

You can modify files, included in this archive or, better yet, fork this project on GitHub:

https://github.com/amcharts/export

We're curious types. Please let us know (contact@amcharts.com) if you do create something new out of this plugin.

License

This plugin is licensed under Apache License 2.0.

This basically means you're free to use or modify this plugin, even make your own versions or completely different products out of it.

Please see attached file "license.txt" for the complete license or online here:

http://www.apache.org/licenses/LICENSE-2.0

Contact us

Changelog

1.1.8

  • Fix: Issue with safari browser which prevented to open the generated export in a tab

1.1.7

  • Added: beforeCapture to be able to indicate the export process in some way
  • Added: afterCapture to be able to modify the fabric instance if needed
  • Added: SVG element as second argument within the "reviver" callback
  • Added: Multiple arguments supported in "handleCallback" method

1.1.6

  • Fix: Pattern render issue in IE;
  • Added: Multiline support (workaround until fabricJS supports tspan)
  • Added: General delay property to delay the capturing of the chart (details)

1.1.5

  • Fix: Tainted check issue which failed if location.origin wasn't available
  • Fix: Capture image check, triggers callback only if all images have been loaded
  • Added: Multi language support; embedded english by default; overtakes chart language
  • Added: Delay feature, which allows to delay the capturing (details)

1.1.4

  • Fix: Did not collect clip-path and pattern from legend
  • Fix: External legend did not respect given width when positioned on left side
  • Fix: Improved tainted image detection

1.1.3

  • Added: Added reviver in capturing method to filter the drawn chart elements

1.1.2

  • Added: Generalized fallback; does a lookup on the Blob constructor
  • Fix: Wait for lazy images, triggers capture callback only when all images have been fully loaded
  • Discovered: Safari 5 issue please adapt fabric.js manually to solve it

1.1.1

  • Fix: CSV export issue on date based charts
  • Fix: Enhanced migration script to obtain more settings

1.1.0

  • Fix: Print issue on safari which captured the actual page instead of the export
  • Added: IE9 download fallback for text/plain and image/* mime types (CSS has been modified)
  • Added: toImage method; returns img element with embedded base64 imagery
  • Added: getBase64 option in toSVG
  • Added: toImage usage in toPRINT to be able to choose the image type + settings.
  • Added: lossless option in toPRINT (experimental)

1.0.9

  • Added: IE9 base64 export
  • Added: Third party updates + minified versions

1.0.8

  • Fix: IE8 issue which prevents the chart from initiating

1.0.7

  • Fix: issue on toCSV handling the header (first row)

1.0.6

  • Fix: issue on revalidation the chart/map
  • Added: path to load the libaries by default

1.0.5

  • Added: divId to be able to place the menu within an external container
  • Added: menuWalker to replace the whole menu generation
  • Added: menuReviver to adapt menu items before being appended to the list
  • Added: libs.async to load dependencies asynchronous (default true)

1.0.4

  • Considering classNamePrefix (dont't forget to adapt export.css)
  • Added: safety delay on print restore to ensure capturing the canvas

1.0.3

  • Fix: flagged relative image paths as tainted

1.0.2

  • Fix: compabitily on array method extension such as PrototypeJS

1.0.1

  • Added: libs.reload: false, script tag crawling to avoid multiple insertions
  • Fix: IE10 bug on print
  • Fix: migration bug, replaces menu instead of appending

1.0

  • Initial release

FAQs

Last updated on 08 Jul 2015

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc