Search code examples
javascriptreactjssvgrechartsreact-pdf

How to add recharts to react-pdf


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.


Solution

  • 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.