patternjavascriptReactModerate
react-pdf: rendering React components to PDF documents
Viewed 0 times
react-pdf@react-pdf/rendererreact pdf generationpdf react componentrendertobuffer
Problem
Generating PDFs from React applications either requires a headless browser (heavyweight) or switching to an entirely different templating system. Developers want to use React's component model and props system for PDF templates.
Solution
Use @react-pdf/renderer to define PDF documents as React components using PDF-specific primitives (Document, Page, View, Text, Image, StyleSheet). Render to a Buffer server-side with renderToBuffer() or to a blob client-side with pdf().toBlob().
Why
@react-pdf/renderer uses its own PDF rendering engine (not a browser) and outputs proper PDF with selectable text, not rasterized images. Components are composable and props-driven, fitting naturally into React data flow.
Gotchas
- @react-pdf/renderer uses a different set of components than React DOM — HTML tags like <div> and <p> do not work
- StyleSheet.create() uses a React Native-like subset of CSS — not all properties are supported
- External images must be either base64 data URIs or publicly accessible URLs (no localhost in serverless)
- Custom fonts must be registered with Font.register() before use
- renderToBuffer() is async and returns a Node.js Buffer — use it server-side for streaming responses
Code Snippets
Simple invoice PDF with @react-pdf/renderer
import { Document, Page, Text, View, StyleSheet, renderToBuffer } from '@react-pdf/renderer';
const styles = StyleSheet.create({
page: { padding: 40, fontFamily: 'Helvetica' },
title: { fontSize: 24, marginBottom: 20 },
row: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 8 },
label: { fontSize: 12, color: '#555' },
value: { fontSize: 12 },
});
function InvoicePdf({ invoice }) {
return (
<Document>
<Page size="A4" style={styles.page}>
<Text style={styles.title}>Invoice #{invoice.number}</Text>
<View style={styles.row}>
<Text style={styles.label}>Due Date</Text>
<Text style={styles.value}>{invoice.dueDate}</Text>
</View>
<View style={styles.row}>
<Text style={styles.label}>Amount Due</Text>
<Text style={styles.value}>${invoice.amount}</Text>
</View>
</Page>
</Document>
);
}
// Express route
app.get('/invoice/:id/pdf', async (req, res) => {
const invoice = await db.getInvoice(req.params.id);
const buffer = await renderToBuffer(<InvoicePdf invoice={invoice} />);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="invoice-${invoice.number}.pdf"`);
res.send(buffer);
});Context
React applications generating PDFs (invoices, certificates, reports) using a component-based approach
Revisions (0)
No revisions yet.