I’m working on a PDF generation feature using the @react-pdf/renderer package in my React application. I need to display an image only on the first page of the PDF. Below is the relevant portion of my code:
import { Document, Page, Text, View, StyleSheet, pdf, Image } from '@react-pdf/renderer'
import moment from 'moment'
import { headerImgPdfQuote } from '../../../Clients/devisTemplate'
const styles = StyleSheet.create({
page: {
flexDirection: 'column',
backgroundColor: '#FFFFFF',
padding: '0 40px'
},
header: {
position: 'absolute',
top: 0,
left: 0,
right: 0
},
headerImage: {
width: '100%',
height: 'auto'
}
})
const QuotePDF = () => (
<Document>
<Page size="A4" style={styles.page} wrap>
<View style={styles.header}>
<View render={({ pageNumber }) => (
pageNumber === 1 && (
<Image src={headerImgPdfQuote} style={styles.headerImage} />
)
)} />
<View render={({ pageNumber }) => (
pageNumber === 1 && (
<Text>Reference: {quoteData.ref}</Text>
)
)} />
<View render={({ pageNumber }) => (
pageNumber === 1 && (
<Text>{moment(quoteData.createdAt).format('DD/MM/YYYY')}</Text>
)
)} />
</View>
<Text render={({ pageNumber, totalPages }) => `${pageNumber}/${totalPages}`} fixed />
</Page>
</Document>
)
const generatePDF = async () => {
const blob = await pdf(<QuotePDF />).toBlob()
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `quote_${moment(quoteData.createdAt).format('DD_MM_YYYY')}.pdf`
link.click()
}
The headerImgPdfQuote
is a base64 encoded image. I converted an image to base64 and stored it in a variable which I then exported and imported here.
The image and some text should only appear on the first page. However, the image does not appear at all. What am I doing wrong, and how can I ensure the image displays only on the first page?
What did you try?
I tried using the render prop to conditionally render the Image component based on the page number. Specifically, I used render={({ pageNumber }) => (pageNumber === 1 && )} to attempt to display the image only on the first page.
What were you expecting?
I expected the image to appear only on the first page of the generated PDF, but it does not appear at all.
What am I doing wrong, and how can I ensure the image displays only on the first page?