1

I'm trying to export a chart to an image and I want the chart image to have a custom legend that is not being displayed on screen.

How can I do that?

For now I have tried to export using react-component-export-image but if the component is not displayed the ref is null and It cannot be exported. See component export implementation src-code.

Example of my current code: codesandbox

PauCasademont
  • 279
  • 4
  • 18
  • the only way to do this is to edit the canvas (the chart) to display very briefly the legend to export it then hide it again or duplicate that chart and do the same process on a hidden div – savageGoat Jun 03 '21 at 11:26

1 Answers1

2

The only way you can achieve that by manipulating the canvas before render. You can do that by setting the onclone option in html2CanvasOptions.

import { Line } from "react-chartjs-2";
import { exportComponentAsPNG } from "react-component-export-image";
import React, { useRef } from "react";
import { data } from "./data";

const Chart = React.forwardRef((props, ref) => {
  return (
    <div ref={ref} style={{ maxWidth: "800px" }}>
      <Line data={data} height={80} />
      <div id="legend" style={{ textAlign: "center", visibility: "hidden" }}>
        Legend
      </div> {/* Visibility set to hidden using css */}
    </div>
  );
});

const App = () => {
  const componentRef = useRef();

  return (
    <React.Fragment>
      <Chart ref={componentRef} />
      <button
        style={{ margin: "30px" }}
        onClick={() => exportComponentAsPNG(componentRef, {
            html2CanvasOptions: {
              onclone: (clonedDoc) => {
                clonedDoc.getElementById("legend").style.visibility = "visible";
                // Visibility set to visible using `onclone` method
              },
            },
          })
        }
      >
        Export As PNG
      </button>
    </React.Fragment>
  );
};

export default App;

https://codesandbox.io/s/export-chart-821kc?file=/src/App.js

This will do the job. Let me know if you need further support.

Yushan
  • 1,029
  • 1
  • 9
  • 12
  • This works well, but the screen shows a white space where the custom legend is hidden. To solve it for now I have two charts, one to display on screen and the other hidden to export with the custom legend. I get rid of the white space using a negative margin top in the hidden div so I need the copy of the chart to not overlap the elements to export. – PauCasademont Jun 03 '21 at 14:33