Ad

Trying To Export Chart With Chartjs And React But Getting Erorr

- 1 answer

I'm trying to export chart with Chart JS and React to PDF, but i'm receiving error that element is not attached to the document and i don't see where i didn't attach element.

Here is code :

import React, { Component } from "react";
import { Bar, Line, Pie } from "react-chartjs-2";
import html2canvas from "html2canvas";
const pdfConverter = require("jspdf");

class Chart extends Component {
state = {
chartData: {
  labels: [
    "Podgorica",
    "Belgrade",
    "New York",
    "London",
    "Paris",
    "Stockholm",
    "Berlin"
  ],
  datasets: [
    {
      label: "Population",
      data: [250000, 1300000, 8600000, 8136000, 2140000, 965000, 3575000],
      backgroundColor: [
        "rgba(255, 99, 132, 0.6)",
        "rgba(54, 162, 235, 0.6)",
        "rgba(255, 206, 86, 0.6)",
        "rgba(75, 192, 192, 0.6)",
        "rgba(153, 102, 255, 0.6)",
        "rgba(255, 159, 64, 0.6)",
        "rgba(255, 99, 132, 0.6)"
      ]
    }
  ]
}
};

demoFromHTML() {
let input = window.document.getElementsByClassName("divToPDF");
html2canvas(input).then(canvas => {
  const imgData = canvas.toDataURL("image/png");
  const pdf = new pdfConverter("l", "pt");
  pdf.addImage(imgData, "JPEG", 15, 110, 800, 250);
  pdf.save("test.pdf");
});
}

render() {
return (
  <div className="divToPDF">
    <Bar
      data={this.state.chartData}
      options={{
        title: {
          display: true,
          text: "Cities in world",
          fontSize: 25
        },
        legend: {
          display: true,
          position: "right"
        }
      }}
      height={50}
    />
    <div>
      <button onClick={() => this.demoFromHTML()}>PDF FILE</button>
    </div>
  </div>
);
  }
   }

    export default Chart;

And here is error i'm getting - enter image description here

Can someone help me understand why i'm getting error like this? As i have given argument to html2canvas with which document to target.

Ad

Answer

let input = window.document.getElementsByClassName("divToPDF"); actually gives you an array of HTML elements whereas html2canvas expect only one element.

Your problem is fixed with let input = window.document.getElementsByClassName("divToPDF")[0];

Here a working codesandbox

Ad
source: stackoverflow.com
Ad