Export react component into pdf and download it automatically

222 Views Asked by At

I am using react-to-pdf (or jsPdf, html2canvas) library to achieve my task.

const ExportPDF = () => {
    const ref = useRef();

    const convertToPdf = async () => {
        const pdf = new jsPDF();
        const canvas = await html2canvas(ref.current);
        const imgData = canvas.toDataURL('image/png');
        pdf.addImage(imgData, 'PNG', 0, 0);
        pdf.save('ExportPDF.pdf');
    };

    return (
        <div>
            {/* <ReactToPdf targetRef={ref} filename="mypdf.pdf">
                {({ toPdf }) => (
                    <Button variant="contained" color="secondary" onClick={toPdf}>Export PDF</Button>
                )}
            </ReactToPdf> */}
            <Button variant="contained" color="secondary" onClick={convertToPdf}>Export PDF</Button>
            <div style={{ position: 'absolute', left: '-9999px' }}>
                <div style={{ display: 'none' }} ref={ref} >
                    <MyComponent />
                </div>
            </div>
        </div>
    );
};

function MyComponent () {
    return (
        <div>
            {/* <Typography variant="h4">My PDF Document</Typography>
            <Typography variant="body1">This is some sample text.</Typography>
            <Button variant="contained" color="primary">
                Click Me!
            </Button> */}
            <h1>Hello World!</h1>
            <p>This is my existing React component.</p>
        </div>
    );
}

export default ExportPDF;

myComponent is my react component that I want to export. It contains multiple MUI components in it (ex: commented code).

In ExportPDF, with react-to-pdf library, I am using <ReactToPdf> to achieve my task. But it is throwing invalid arguments passed to jsPdf.scale error. Also I tried to achieve my task with simple component and with jsPdf and html2canvas libraries. But itis throwing Incomplete or corrupt PNG file error.

Kindly guide me to solve this error and complete the implementation. Any help is appreciated.

0

There are 0 best solutions below