In modern web development, generating PDFs on the fly has become a common need. Whether you need to create invoices, reports, contracts, or user manuals, generating PDFs directly from a React app can save time and improve efficiency. React-PDF is a popular library that allows developers to generate PDF files easily in their React projects.
In this article, we’ll explore React-PDF, its features, how to install it, and provide practical examples to help you get started.
What is React-PDF?
React-PDF is a library that helps developers create PDF documents within their React applications. It offers a simple and declarative way to build PDFs using familiar React components. You can construct PDF layouts with ease, making it useful for a wide range of applications.
With React-PDF, you can:
- Display PDFs in your React app.
- Generate dynamic PDFs based on user data.
- Create PDF documents using a JSX-like syntax.
Key Features of React-PDF
Here are some of the key features that make React-PDF stand out:
- Declarative Syntax: With JSX-style components, creating PDFs becomes more intuitive for React developers.
- Cross-Platform Support: React-PDF works seamlessly on both web and Node.js.
- Customizable Layouts: The library allows you to control layouts using flexbox, providing flexibility for different designs.
- Embedding Images and Fonts: You can easily add custom fonts and images to your PDFs.
- Event Handling: React-PDF allows you to handle events and triggers, making it possible to create dynamic PDFs based on user interactions.
- Multiple Rendering Options: You can render PDFs directly in the browser or generate them on the server using Node.js.
Installation
To start using React-PDF, you’ll first need to install the package. Here’s how you can do that:
npm install @react-pdf/renderer
Alternatively, if you’re using yarn:
yarn add @react-pdf/renderer
After installation, you’re ready to build PDF documents by importing the necessary components into your project.
Basic Usage Example
Let’s begin with a simple example. In this example, we’ll create a basic PDF document using React-PDF.
import React from 'react';
import { PDFViewer, Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
// Define styles
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4',
},
section: {
margin: 10,
padding: 10,
flexGrow: 1,
},
});
// Create a PDF document component
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Hello, World!</Text>
</View>
<View style={styles.section}>
<Text>Generating PDF files in React is simple!</Text>
</View>
</Page>
</Document>
);
// Render PDF using the PDFViewer
const App = () => (
<PDFViewer width="100%" height="600">
<MyDocument />
</PDFViewer>
);
export default App;
Explanation:
- PDFViewer: This component is used to display the generated PDF in the browser.
- Document: This serves as the root container for the PDF.
- Page: Represents individual pages in the PDF document. You can define the page size (e.g., A4).
- Text and View: Basic components used to add text and layout elements to your PDF document.
Rendering a PDF in the Browser
React-PDF allows you to render PDFs directly in the browser using the PDFViewer component. This is especially useful when you want to display a generated PDF dynamically, like an invoice or report based on user input.
<PDFViewer width="100%" height="600">
<MyDocument />
</PDFViewer>
Advanced Example: Generating Dynamic PDF from User Data
Let’s move on to a more advanced example where we create a dynamic PDF based on user-provided data. In this case, we’ll generate a simple invoice.
import React from 'react';
import { PDFDownloadLink, Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
// Define styles
const styles = StyleSheet.create({
page: { padding: 30 },
section: { marginBottom: 10 },
header: { fontSize: 20, marginBottom: 20 },
footer: { marginTop: 50, fontSize: 12 },
});
// Component to generate invoice
const Invoice = ({ invoiceData }) => (
<Document>
<Page size="A4" style={styles.page}>
<Text style={styles.header}>Invoice</Text>
<View style={styles.section}>
<Text>Customer: {invoiceData.customerName}</Text>
<Text>Date: {invoiceData.date}</Text>
</View>
<View style={styles.section}>
<Text>Items:</Text>
{invoiceData.items.map((item, index) => (
<Text key={index}>
{item.name}: ${item.price}
</Text>
))}
</View>
<View style={styles.footer}>
<Text>Total: ${invoiceData.total}</Text>
</View>
</Page>
</Document>
);
// App component with dynamic data
const App = () => {
const invoiceData = {
customerName: "John Doe",
date: "2024-10-11",
items: [
{ name: "Product 1", price: 50 },
{ name: "Product 2", price: 30 },
],
total: 80,
};
return (
<div>
<h1>Download Your Invoice</h1>
<PDFDownloadLink document={<Invoice invoiceData={invoiceData} />} fileName="invoice.pdf">
{({ loading }) => (loading ? "Loading document..." : "Download Invoice")}
</PDFDownloadLink>
</div>
);
};
export default App;
Explanation:
- PDFDownloadLink: This component allows users to download the PDF file directly.
- Document and Page: These build the structure of the PDF file.
- Dynamic Data: The
Invoice
component acceptsinvoiceData
as a prop and dynamically generates the content.
Styling and Layout with Flexbox
React-PDF uses flexbox for layout, making it easy to design complex layouts. You can define containers, align items, and distribute space using flexDirection
, just like in a regular React project.
const styles = StyleSheet.create({
page: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
text: {
margin: 10,
fontSize: 18,
textAlign: 'center',
},
});
Handling Images and Fonts
React-PDF allows you to embed images and use custom fonts within your PDFs. You can add base64 images or URLs and even register custom fonts for a personalized look.
Embedding an Image:
import { Image } from '@react-pdf/renderer';
const MyDocument = () => (
<Document>
<Page>
<Image src="https://example.com/logo.png" />
</Page>
</Document>
);
Using Custom Fonts:
import { Font } from '@react-pdf/renderer';
Font.register({
family: 'Roboto',
src: 'https://example.com/fonts/roboto.ttf',
});
Conclusion
React-PDF is a powerful tool for generating PDFs within your React applications. Whether you need to display PDFs, generate dynamic documents, or add custom fonts and images, React-PDF makes it easy to integrate these features. The library’s flexibility and ease of use make it a great choice for developers looking to create PDFs directly from React.
With React-PDF, you can:
- Display PDFs directly in the browser.
- Generate dynamic PDFs based on user data.
- Easily style your PDFs using flexbox layouts.
- Integrate custom fonts and images for a professional touch.
By following this guide, you can start using React-PDF in your projects to build highly customizable and functional PDFs in no time.