React PDF — Generate PDFs with React
Advertisement
React PDF — Generate PDFs with React
React PDF enables generating PDFs from React components on the server or client.
Installation
npm install @react-pdf/renderer
Basic PDF
import {
Document,
Page,
Text,
View,
StyleSheet
} from '@react-pdf/renderer'
import { pdf } from '@react-pdf/renderer'
const styles = StyleSheet.create({
page: { padding: 30 },
heading: { fontSize: 24, fontWeight: 'bold', marginBottom: 10 },
text: { fontSize: 12, marginBottom: 5 }
})
export const InvoicePDF = ({ invoice }: { invoice: any }) => (
<Document>
<Page size="A4" style={styles.page}>
<Text style={styles.heading}>Invoice</Text>
<View>
<Text style={styles.text}>Invoice #: {invoice.number}</Text>
<Text style={styles.text}>Date: {invoice.date}</Text>
<Text style={styles.text}>Total: ${invoice.total}</Text>
</View>
</Page>
</Document>
)
// Generate and save
async function generatePDF() {
const blob = await pdf(<InvoicePDF invoice={data} />).toBlob()
// Download or send
}
Server Route
// app/api/generate-invoice/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { InvoicePDF } from '@/components/invoice-pdf'
import { pdf } from '@react-pdf/renderer'
export async function POST(request: NextRequest) {
const { invoice } = await request.json()
const doc = pdf(<InvoicePDF invoice={invoice} />)
const buffer = await doc.toBuffer()
return new NextResponse(buffer, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="invoice.pdf"'
}
})
}
Tables
import { Document, Page, Table, TableCell, TableHead, TableBody, TableRow } from '@react-pdf/renderer'
export function ReportPDF({ data }: { data: any[] }) {
return (
<Document>
<Page>
<Table>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Amount</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map((row, i) => (
<TableRow key={i}>
<TableCell>{row.name}</TableCell>
<TableCell>${row.amount}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Page>
</Document>
)
}
FAQ
Q: Can I embed images in PDFs? A: Yes, use Image component with base64 or URL.
Q: Does React PDF work in the browser? A: Yes, for small documents. Server generation recommended.
Q: How do I add headers/footers? A: Use Header and Footer render props on Page component.
React PDF enables generating professional documents programmatically.
Advertisement