I found this solution to convert html to a pdf via this Create PDF file from HTML text React. However, when I try to implement it myself, the ref can only be read as null within the helper function. I
have tried to have the component re-render with a useEffect hook but I don't believe that is allowing the component to access the new value of printRef.current. I also tried to see if this was occurring because of the ternary operator in the return statement but that doesn't seem to be the case either. Here is my current example:
import React, { useRef } from "react";
import { Button } from "@mui/material";
import { useState } from "react";
import makeStyles from "@mui/styles/makeStyles";
import { colors } from "../../../common/GlobalColors";
import Report from "../ExportPage/Report";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import { useEffect } from "react";
const useStyles = makeStyles((theme) => ({
fileDrop: {
width: 400,
color: `${colors.blue}`,
fontFamily: "Roboto",
borderRadius: 10,
},
fileContainer: {
display: "flex",
justifyContent: "center",
padding: 10,
},
fileWrapper: {},
exportWrapper: {
display: "flex",
justifyContent: "center",
paddingTop: "40px",
},
}));
const FileDropHandler: React.FC = () => {
const styles = useStyles();
const [isGeneratingReports, setIsGeneratingReports] =
useState<boolean>(false);
const [element, setElement] = useState<HTMLDivElement | null>(null);
const printRef = React.useRef(); //useRef<HTMLDivElement>(null);
const handleDownloadPdf = async () => {
const canvas = await html2canvas(printRef.current);
const data = canvas.toDataURL("image/png");
console.log("made it");
const pdf = new jsPDF();
const imgProperties = pdf.getImageProperties(data);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProperties.height * pdfWidth) / imgProperties.width;
pdf.addImage(data, "PNG", 0, 0, pdfWidth, pdfHeight);
pdf.save("print.pdf");
};
return (
<>
{isGeneratingReports ? (
<>
<div ref={(printRef) => setElement(printRef)}>
<Report />
</div>
</>
) : (
<div className={styles.fileWrapper}>
<Button variant="contained" onClick={() => {
handleDownloadPdf()
setIsGeneratingReports(true);
}}>
Convert Files
</Button>
</div>
)}
</>
);
};
export default FileDropHandler;