7

I am using 'recharts' to create graphs for my project, and 'react-pdf' for generating a report. 'Recharts' creates a svg on the DOM when using it and a graph is displayed.

Is there a way I can use these two together, and add my 'recharts' component to my report via react-pdf? for example - inside a <Document/> tag.

react-pdf link to website

recharts link to website

I have seen a solution which offers to convert the rechart's svg to a png, save it locally and then import it and use via <Image/> component in react-pdf.

Looking for a more straightforward approach to this issue.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Daniel Cohen
  • 121
  • 1
  • 7

2 Answers2

5

Here is how I solved it : I have used this article - https://betterprogramming.pub/heres-why-i-m-replacing-html2canvas-with-html-to-image-in-our-react-app-d8da0b85eadf

It recommends using html-to-image package.

So I've given an id to the container of the rechart component, and selected it with docoument.getElementById(). Then, used the selected id when querying html-to-image, like so -

  const response = await htmlToImage.toPng(myId);

The response then contained a url, which was used as an src for the react-pdf Image component.

Daniel Cohen
  • 121
  • 1
  • 7
  • When you say contained a url, did were you saving it somewhere or did the PDF handle dame/png blob? I am trying now, and have generated a blob (so i have the image available on browser, but PDF is ignoring it. – Spirconi Jan 07 '22 at 16:18
  • typo: data:image/png;base64 – Spirconi Jan 07 '22 at 16:38
  • The response from htmlToImage has a url. I pushed the url into a local array state. Then, used the url at the Image component which belongs to react-pdf – Daniel Cohen Jan 08 '22 at 19:33
  • Thank you for responding. I found it was because I wasn't awaiting the image callback, so i was generating the PDF before the image existed. So it works now. Thanks again. – Spirconi Jan 10 '22 at 09:47
2

I just created https://github.com/EvHaus/react-pdf-charts which allows for recharts to be rendered into react-pdf. It had only very basic support at the moment, but I'm hoping with some help from the community -- we can get to full support.

Ev Haus
  • 1,578
  • 1
  • 11
  • 23