I am using React hooks and the react-pdf from react-pdf
I tried 3 different React pdf converters, and this is the one that has been working best so far. It still isn't working great tho - I can't see how to make it not either run out of memory or produce blank pdfs.
I have a component that produces the pdf:
import React from 'react';
import { Page, Text, View, Document, StyleSheet, Font } from '@react-pdf/renderer';
Font.register({
family: 'Roboto',
src: 'https://fonts.googleapis.com/css?family=Roboto+Mono:100i,300,300i,400,400i,500,500i,700,700i&display=swap'
});
// Create styles
const styles = StyleSheet.create({
page: {
backgroundColor: '#F5F8FA',
display: 'flex',
// flexDirection: 'column',
// alignItems: 'flex-start',
marginTop: 40,
marginLeft: 20,
marginRight: 20,
width: 555
},
section: {
margin: 50,
padding: 50,
},
reportHeader: {
marginLeft: 0,
fontStyle: 'normal',
fontWeight: 'bold',
fontSize: 24,
lineHeight: 43,
color: '#BF802F',
},
reportIntro: {
width: 555,
height: 132,
paddingLeft: 0,
paddingTop: 10,
paddingBottom: 30,
fontStyle: 'normal',
fontWeight: 'normal',
fontSize: 16,
lineHeight: 22,
color: '#0C3957',
}
});
// Create Document Component
export const ReportPDF = ({ name, adviser }) => {
return (
<Document >
<Page style={styles.page} wrap={false}>
<View style={{ textAlign: 'flex-start', marginBottom: 20 }}>
<Text style={styles.reportHeader}>Your goals report</Text>
</View>
</Page>
</Document>
)
}
And I have another compoonent that has a button to download the pdf file. I found someone else who claimed useMemo helps this situation, but I can't make it work this way either:
const stuff = useMemo(
() => (
<PDFDownloadLink document={<ReportPDF />} fileName="somename.pdf">
{({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
), [])
I then have {stuff} inside a div in the JSX.
When I click the download link I get a blank PDF. What is happening?
If I don't set wrap={false} it runs out of memory?
One of the reasons this can happens is, pdf render before fetching the data. Therefore you can add condition before rendering the PDFDownloadLink to prevent this.
!loadingReportData && <PDFDownloadLink document={<ReportPDF />} fileName="somename.pdf">
{({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
(here loadingReportData is the state, which you set to true before fetching the report data, and set to false after the completion of fetching report data)
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