Chartsjs export PNG automatically

Asked

Viewed 299 times

0

I need to export a chart co Chartjs (version 2.7) to PNG that I got on:

https://jsfiddle.net/uabczmxa/

The only problem I need to push the button.

Would anyone know what to modify in javascript?

At the end I will generate a report with FPDF in PHP, so I need PNG.

  • What exactly do you want? Download when entering the page? What is the difficulty you have?

  • I know almost nothing about javascript. I wanted to automatically save the image when displaying the page without needing a button. With the saved image I will generate a PDF report with the FPDF in PHP that knows well.

1 answer

1


Just call the function: downloadImage();, so when the page loads it performs the function without the need of click.

I put the function in your Jsfiddle, and I had the code run again and downloaded the image without the need to click.

var chart_variable = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'My First Dataset',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      title: {
         display: true,
         text: 'Chart Title'
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      }
   }
});

function downloadImage() {
   /* set new title */
   chart_variable.options.title.text = 'New Chart Title';
   chart_variable.update({
      duration: 0
   });
   // or, use
   // chart_variable.update(0);

   /* save as image */
   var link = document.createElement('a');
   link.href = chart_variable.toBase64Image();
   link.download = 'myImage.png';
   link.click();

   /* rollback to old title */
   chart_variable.options.title.text = 'Chart Title';
   chart_variable.update({
      duration: 0
   });
   // or, use
   // chart_variable.update(0);
}

//executa a função ao abrir a página.
downloadImage();
  • You can also put the function in the body tag with Event Listener onload, ie <body onload="downloadImage()">. The difference in this case is that the function is only executed when the page has fully loaded.

  • It worked, but still not good, as it appears downloading the file, in the background I want to export the image to a folder and then use in my report.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.