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.