Reputation: 63
How can I conver the MUI component to html string, so all the styles we be included as well? My main goal is to create a dynamic template form and to save as PDF file on server side. i'm trying to send the component as html string, in order to generate PDF file. There is only one problem, all mui styles got lost in pdf file
This is what I'm doing now:
client:
const formTemplate = (user)=>{
return (
<Grid container>
<Grid item lg={4} xs={12}>
<TextField fullWidth
defaultValue={user.firstName} label={"First Name"} />
</Grid>
<Grid item lg={4} xs={12}>
<TextField fullWidth
defaultValue={user.familyName} label={"FamilyName"} />
</Grid>
</Grid>)
}
function saveForm(user){
const formTamplate = ReactDOMServer.renderToString(formTemplate(user))
try {
const response = await axios.post(`${url}/consent/sign`, {
email: user.email,
formTamplate: formTamplate
});
dispatch({
type: ActionType.setEnvelopeInfo,
payload: {
envelope: response.data.envelope,
},
});
} catch (err) {
console.log(err);
}
}
server:
router.post("/sign", async (req, res) => {
const { email, formTamplate } = req.body;
const formTemplatePath = `${signed_docs}\\${name}.pdf`;
let options = { format: "A4" };
let file = { content: formTamplate};
try {
await html_to_pdf.generatePdf(file, options).then((pdfBuffer: any) => {
console.log({ pdfBuffer: pdfBuffer });
console.log(typeof pdfBuffer);
fs.writeFile(formTemplatePath, pdfBuffer, (err) => {
if (err) {
console.log({ files_err: err });
return;
}
});
console.log("PDF Buffer:-", pdfBuffer);
});
} catch (err) {
console.log({ pdf_err: err });
}
Upvotes: 0
Views: 1819
Reputation: 11
import { useRef } from 'react';
import './App.css';
import { Button, Box, Link, Typography, Grid } from '@mui/material'
import ReactToPrint from 'react-to-print';
function App() {
const reference = useRef();
return (
<>
<Button onClick={()=>{
console.log(reference.current)
}}>ref</Button>
<Box sx={{textAlign:'center'}}>
<ReactToPrint
trigger={() => <Link>Print</Link>}
content={() => reference.current!}/>
{/* Place the component here and set the reference */}
<Box ref={reference} sx={{textAlign:"center"}}>
<br/>
<Typography variant='h4'>Booking details</Typography>
<Grid container direction="column" spacing={1}>
<Grid container item direction="row" justifyContent='space-around'>
<Typography variant="body1" color="initial">VAT</Typography>
<Typography variant="body1" color="initial">$XXX</Typography>
</Grid>
<Grid container item direction="row" justifyContent='space-around'>
<Typography variant="body1" color="initial">VAT</Typography>
<Typography variant="body1" color="initial">$XXX</Typography>
</Grid>
</Grid>
</Box>
</Box>
</>
);
}
export default App;
console.log(reference.current) logs this output click here to see
useRef hook can be used and the reference has that everything converted to html.
suggestion: react-to-print can be used to directly convert mui components easily, have a look into it. Hope this helps!
Upvotes: 0