[Chartjs]-Using react-chartjs-2 , How can I save my chart as png using a download button

4๐Ÿ‘

โœ…

So I installed a plugin called FileSave.js //

  1. npm install
    npm i file-saver
  2. import the plugin
    import { saveAs } from 'file-saver';
  3. than just write this blob function
   class StackedBar extends Component {
   saveCanvas() {
       //save to png
       const canvasSave = document.getElementById('stackD');
       canvasSave.toBlob(function (blob) {
           saveAs(blob, "testing.png")
       })
   }

   render() {

       return (
           <div>
               <a onClick={this.saveCanvas}>Download as PNG</a>
      
               <Bar id="stackD" data={data} options={options} />
           </div>
       );
   }
}
export default StackedBar; 



1๐Ÿ‘

another option is to use the chart ref, and then use the chart.js toBase64Image function. save this out as base64, convert to blob and save as a file using the file-saver package.

import { saveAs } from 'file-saver';

/**
 * @param b64Data
 * @param contentType
 * @param sliceSize
 * @returns {Blob}
 * @link https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
 */
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < slice.length; i += 1) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  return new Blob(byteArrays, { type: contentType });
};

... in component
  const chartRef = useRef(null);
... in jsx...


<Button
   onClick={() => {
   const b64 = chartRef.current.toBase64Image().replace('data:image/png;base64,', '');
   const content = b64toBlob(b64);
   const file = new File([content], 'Revenue_chart.png', { type: 'image/png' });
   saveAs(file);
  }}
  >
    img
</Button>
<Line data={data} options={options} ref={chartRef} />

Leave a comment