In my react code I’m using MUI5 to create my react components. As of now I’m using two buttons to print and download a pdf report, and of course the content of the pdf which can be viewed in this SCREENSHOT. The React components as shown in the first Screenshot have a parent
<Box ref={componentRef} id="pdf_vehicle_report_purchase_success">
When using Print PDF button i’m executing the following:
import { useReactToPrint } from 'react-to-print';
...
const handlePrint = useReactToPrint({
content: () => componentRef.current,
documentTitle: 'PDF Report',
pageStyle: () => `
@page { margin: 0mm; }
@media print {
...
#buttonPdfPrint {
display: none;
}
}
`
});
The above code is working fine:
- Is using the
react-to-print
library to prepare and open a Print Preview window which renders the React Components into a document. - This allows me to either download or print the document.
- Additional CSS is also applied(print icon not visible in this stage).
- It also renders the content as text and not as IMAGE.
See image for reference:
For the download button i have a similar function but in this case im returning an iframe and passing it to generateAndSavePDF
function. There im applying additional css to the iframe. and then printing the iframe:
const vehicleReportStyles2 = `
...
`;
const downloadPDF = useReactToPrint({
content: () => componentRef.current,
documentTitle: 'PDF Report',
print: async (printIframe) => {
await generateAndSavePDF(printIframe);
}
});
const generateAndSavePDF = async (iFrame) => {
const iframeDocument = iFrame.contentDocument || iFrame.contentWindow.document;
// Inject CSS Styles of Vehicle Report to the iframe
const styleElement = document.createElement('style');
styleElement.appendChild(document.createTextNode(vehicleReportStyles2));
iframeDocument.head.appendChild(styleElement);
// Wait for styles to be applied
await new Promise((resolve) => setTimeout(resolve, 100));
console.log(iframeDocument); //Returns an iframe with injected custom css
};
THE ISSUE:
Most of the libraries i have tried below is converting the iframe to an Image , or is completely entirely messing the design of the final result.
- jsPDF
- html2canvas
- react-to-pdf
- react-pdf
- @react-pdf/renderer
REQUIRED SOLUTION:
I simply want to do the following:
- Convert the React Components to a PDF which is not an image
- Open Print Preview (already completed unless better solution is given)
- Direct Download of the generated PDF
- Store PDF to be sent as email attachment (perhaps in a variable or React.useState)
Any feedback on the above will be highly appreciated.