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,
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:
chartjs-to-image packageYou 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With