Get started with ReactPDF
Table of Contents
- Introduction
- Installing React PDF
- Creating the PDF Component
- Styling the PDF Document
- Adding Images to the PDF
- Adding Text to the PDF
- Adding Page Numbers
- Creating the Download Button
- Testing and Final Adjustments
- Conclusion
Introduction
In this article, we will learn how to use and set up React PDF. We will be creating a basic React PDF template and exploring various features and functionalities. By the end of this tutorial, you will have a clear understanding of how to generate and style PDF documents in a React application. Let's get started!
Installing React PDF
To begin, we need to install the React PDF package. Open your terminal and navigate to your React project directory. Run the following command to install the required dependencies:
npm install @react-pdf/renderer --save
This command will install the React PDF package and save it as a dependency in your project's package.json file. Once the installation is complete, we can proceed to the next step.
Creating the PDF Component
Now, let's create a new file called PDFFile.js
inside a folder called components
. This file will contain our PDF document. In this component, we'll import the necessary modules from the React PDF package. Here's how your PDFFile.js
file should look like:
import React from 'react';
import { Page, Text, Image, Document, StyleSheet } from '@react-pdf/renderer';
const styles = StyleSheet.create({
body: {
paddingTop: 35,
paddingBottom: 65,
paddingHorizontal: 35,
},
title: {
fontSize: 24,
textAlign: 'center',
marginBottom: 24,
},
text: {
margin: 12,
fontSize: 14,
textAlign: 'justify',
fontFamily: 'Times-Roman',
},
image: {
marginVertical: 15,
marginHorizontal: 100,
},
});
const PDFFile = () => {
return (
<Document>
<Page style={styles.body}>
<Text style={styles.title}>My React PDF</Text>
<Image style={styles.image} src="./path/to/image.jpg" />
<Text style={styles.text}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in tincidunt augue. Phasellus non turpis eget purus malesuada semper. Curabitur dictum blandit risus, in mollis dolor congue et. Duis rutrum vehicula iaculis. In vitae viverra neque. Nulla facilisi. Curabitur facilisis enim eget mauris bibendum, et volutpat leo eleifend. Donec id justo sed felis maximus finibus. Fusce tristique, metus a vulputate interdum, lectus eros feugiat sem, a hendrerit tortor elit eu justo. Donec nunc lacus, iaculis id odio in, pretium dapibus odio.</Text>
</Page>
</Document>
);
}
export default PDFFile;
In this component, we define the styles for our PDF document using the StyleSheet.create
method. We can customize the styles according to our requirements. We add a title, an image, and some text content to our PDF document. Feel free to modify this template to suit your needs.
Styling the PDF Document
Now, let's define the styles for our PDF document. Open the PDFFile.js
file and add the following code above the PDFFile
component:
const styles = StyleSheet.create({
body: {
paddingTop: 35,
paddingBottom: 65,
paddingHorizontal: 35,
},
title: {
fontSize: 24,
textAlign: 'center',
marginBottom: 24,
},
text: {
margin: 12,
fontSize: 14,
textAlign: 'justify',
fontFamily: 'Times-Roman',
},
image: {
marginVertical: 15,
marginHorizontal: 100,
},
});
In this code, we define the styles for the body, title, text, and image elements of our PDF document. You can adjust these styles as per your design preferences.
Adding Images to the PDF
To add an image to our PDF document, we'll use the Image
component from the React PDF package. Open the PDFFile.js
file and add the following code inside the Page
component:
<Image style={styles.image} src="./path/to/image.jpg" />
Replace ./path/to/image.jpg
with the actual file path of your image. You can adjust the image style according to your requirements. Make sure to use a self-closing tag for the Image
component.
Adding Text to the PDF
To add text content to our PDF document, we'll use the Text
component from the React PDF package. Open the PDFFile.js
file and add the following code inside the Page
component:
<Text style={styles.text}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in tincidunt augue. Phasellus non turpis eget purus malesuada semper. Curabitur dictum blandit risus, in mollis dolor congue et. Duis rutrum vehicula iaculis. In vitae viverra neque. Nulla facilisi. Curabitur facilisis enim eget mauris bibendum, et volutpat leo eleifend. Donec id justo sed felis maximus finibus. Fusce tristique, metus a vulputate interdum, lectus eros feugiat sem, a hendrerit tortor elit eu justo. Donec nunc lacus, iaculis id odio in, pretium dapibus odio.</Text>
Replace the placeholder text with your own content. You can adjust the text style according to your preferences. Make sure to provide a self-closing tag for the Text
component.
Adding Page Numbers
If you want to display page numbers in your PDF document, you can do so by adding a Text
component at the bottom of each page. Open the PDFFile.js
file and modify the Page
component as follows:
<Page style={styles.body}>
{/* Other content */}
<Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => `${pageNumber} / ${totalPages}`} />
</Page>
This code will display the current page number and the total number of pages at the bottom of each page. The render
prop of the Text
component is a function that receives the pageNumber
and totalPages
as arguments. You can customize the style of the page number text using the pageNumber
style defined in the styles
object.
Creating the Download Button
To enable users to download the generated PDF document, we need to add a download button. Open the App.js
file (or any other component where you want to place the download button) and import the PDFFile
component:
import React from 'react';
import PDFFile from './components/PDFFile';
const App = () => {
const downloadPDF = () => {
// Code to trigger the PDF download
};
return (
<div>
<h1>React PDF Tutorial</h1>
<button onClick={downloadPDF}>Download PDF</button>
<PDFFile />
</div>
);
}
export default App;
In this example, we have a simple button that triggers the downloadPDF function when clicked. You can customize the function according to your needs. The <PDFFile />
component is rendered below the download button and displays the content of the PDF document.
Testing and Final Adjustments
Now, run your React application and test the functionality of the download button. When you click the button, it should trigger the download of the PDF document generated by the PDFFile
component. Make any final adjustments to the styling and content of the PDF document as required.
Conclusion
Congratulations! You have successfully learned how to use and set up React PDF in your application. You can now generate PDF documents with custom styles, images, and text content. Feel free to explore more advanced features and functionalities of the React PDF package to enhance your PDF generation capabilities. Happy coding!
Highlights
- Learn how to set up and use React PDF
- Generate PDF documents with custom styles, images, and text content
- Add page numbers to your PDF documents
- Create a download button for downloading the generated PDF
- Customize the styling and content of your PDF documents
Frequently Asked Questions
Q: Can I add multiple pages to my React PDF document?
A: Yes, you can add multiple pages to your React PDF document by using multiple Page
components within the Document
component. Each Page
component can have its own content and styles.
Q: Can I customize the font style and size of the text in my React PDF document?
A: Yes, you can customize the font style, size, and other properties of the text in your React PDF document by modifying the styles defined in the StyleSheet.create
method. Use the fontFamily
, fontSize
, and other CSS properties to make the desired changes.
Q: How can I add more advanced features, such as tables or charts, to my React PDF document?
A: React PDF provides a rich set of components and features that allow you to add complex elements like tables and charts to your PDF documents. You can explore the React PDF documentation and experiment with different components to achieve your desired results.