How to Use Chart.js or recharts in react-pdf/renderer

3.3k Views Asked by At

I want to create pdf using react-pdf ,but for charts/graphs i have to use Chart.js or recharts ,but directly i can not implement into react-pdf , another option i have seen from a qs: How to add recharts to react-pdf

but here html-to-image( const response = await htmlToImage.toPng(myId) ) uses but I can not find out how to put that html for docoument.getElementById() and where to put that,

I expect to put chart/graph in my created react-pdf pages,In any way. here html-to-image( const response = await htmlToImage.toPng(myId) ) uses but I can not find out how to put that html for docoument.getElementById() and where to put that,

1

There are 1 best solutions below

0
On

To add charts/graphs to your react-pdf document, you can convert your chart to an image and then add it to the PDF using an Image tag.

Here's how you can do it:

Step 1: Install the chartjs-to-image package

You can use either chartjs-to-image or chartjs-node-canvas to convert your chart to an image. I prefer to use chartjs-to-image because I use Next.js + webpack and chartjs-node-canvas doesn't support it.

npm install chartjs-to-image

Step 2: Convert your chart to a base64 image

import { useState, useEffect } from 'react';
import { Document, Page, Image, View } from '@react-pdf/renderer';
import ChartJsImage from 'chartjs-to-image';

export const MyComponent = () => {
  const [imageSrc, setImageSrc] = useState<string | null>(null);

  useEffect(() => {
    const myChart = new ChartJsImage();
    myChart.setConfig({
      type: 'bar',
      data: { 
        labels: ['Hello world', 'Foo bar'], 
        datasets: [{ label: 'Foo', data: [1, 2] }]
      },
    });
    myChart.toDataUrl().then((data) => setImageSrc(data));
  }, []);

  return (
    <Document>
      <Page>
        <View>
          <Image src={`${imageSrc}`} />
        </View>
      </Page>
    </Document>
  );
};

In this example, we're creating a bar chart using ChartJsImage, setting its configuration, and then converting it to a base64 image using toDataUrl(). We then set the imageSrc state to the base64 string so that we can use it in the Image tag.