Hussain Arif Hussain is a CS student in Pakistan whose biggest interest is learning and teaching programming to make the world a better place.
Table of contentsLogRocket’s Galileo AI watches every session, surfacing impactful user struggle and key behavior patterns.
Editor’s note: This article was updated by David Omotayo on 11 March 2024 to outline some example use cases for generating PDFs in React, discuss the pros and cons of implementing this feature from scratch, update the react-pdf library’s stats, and compare react-pdf to other libraries.
There are several reasons why you might want to incorporate a PDF document generator feature in your application. Fortunately, the React ecosystem provides a wealth of tools offering simple ways to generate PDF documents directly within React applications.
One such tool is the react-pdf library, which simplifies the PDF generation process within your React project. In this article, we’ll explore why you might want to implement a PDF document generation feature, the fundamentals of react-pdf, and advanced concepts. We’ll also compare react-pdf to other libraries.
There are many use cases for a PDF generator feature in a React application, such as offline access to the application’s content, report generation, and more. However, the most common use case for such a feature in modern apps is data exports — for example, invoices or brochures.
To put it into perspective, consider a thriving online business. Every sale means generating an invoice, a process that can quickly become tedious. In order to create a receipt for each customer, you would need to follow steps such as:
Sure, that might work. But consider this: what if the business get hundreds of customers in a single day? This situation could result in a substantial waste of time and energy, as the same process would need to be repeated for each customer. So, how do we mitigate this problem?
The best way to solve this issue is to automate this operation by using an API. This is where react-pdf and other similar libraries comes in.
While building a PDF generator from the ground up is technically possible, it’s crucial to weigh the pros and cons before diving in. Let’s explore both approaches to see which aligns better with your project goals.
Pros of building from scratch include:
However, crafting a PDF document generator from the ground up can be tedious and time-consuming. You would need to consider implementing the following features:
As you can tell, this can be quite tedious. Additionally, beyond the initial development effort, maintaining a custom PDF generator requires ongoing upkeep. Bug fixes, compatibility updates, and potential security vulnerabilities all become your responsibility.
Although the customization and learning experience can be valuable, the time investment and ongoing maintenance burden can be significant. Using a library like react-pdf relieves you of the burden of implementing all these features, allowing you to focus on the core logic of your application.
To install the react-pdf package, run the following terminal command:
npm i @react-pdf/renderer
The following block of code renders a basic PDF document in the browser:
import < Document, Page, Text, View, StyleSheet, PDFViewer, >from "@react-pdf/renderer"; // Create styles const styles = StyleSheet.create(< page: < backgroundColor: "#d11fb6", color: "white", >, section: < margin: 10, padding: 10, >, viewer: < width: window.innerWidth, //the pdf viewer will take up all of the width and height height: window.innerHeight, >, >); // Create Document Component function BasicDocument() < return (>* Start of the document*/> ); > export default BasicDocument;*render a single page*/> > > Hello > World
Let’s test it out! As the next step, render the BasicDocument component to the DOM like so:
import BasicDocument from "./BasicDocument"; function App() < return (); > export default App;
You should see the following:
We can even reduce the viewer’s available space:
const styles = StyleSheet.create(< viewer: < width: window.innerWidth / 3, height: window.innerHeight / 2, >, //further code. >);
In this snippet, we restricted the viewport’s width and height properties. This will decrease their available sizes on the page:
The react-pdf library offers various components we can display in our generated PDF. Let’s discuss and demonstrate these components now.
We can display anchor links using the Link component. This is handy for cases where you want to redirect the user to a website:
import < Link >from "@react-pdf/renderer";Go to Facebook
Here, we are assigning the src prop to Facebook’s website. When the user clicks on this piece of text, the app will redirect them to the page:
To attach annotations in your document, use the Note component. One critical use case for this element is when you need to display comments in a file:
import < Note >from "@react-pdf/renderer";This will take the user to Facebook
Hovering over this annotation will display the text we set:
The Canvas component lets users draw content on the page. This is suitable for displaying simple diagrams and logos in SVG format.
This code snippet renders a triangle on the page:
import < Canvas >from "@react-pdf/renderer"; // Create styles const styles = StyleSheet.create(< canvas: < backgroundColor: "black", height: 500, width: 500, >, >); paint= < (painterObject) =>painterObject .save() .moveTo(100, 100) //move to position 100,100 .lineTo(300, 100) //draw a line till 300, 100 .lineTo(300, 300) //draw another line till 300,300 .fill("red") //when the diagram is drawn, set the background color to pink > />
In the above snippet, we used the Canvas component to display a diagram. The paint prop is a callback function. One of its parameters is a painterObject argument, which gives us access to drawing methods:
react-pdf also bundles an SVG component to render SVG diagrams. Just like Canvas , we can use this for rendering simple diagrams.
This piece of code renders a line on the page:
import < Line, Svg >from "@react-pdf/renderer"; // Create styles const styles = StyleSheet.create(< line: < x1: "0", //starting coords are x1 and y1 y1: "0", x2: "200", //ending coords: y2: "200", strokeWidth: 2, stroke: "rgb(255,255,255)", //stroke color >, >);
Here, we used Line to render a line in the document. Notice that Line is a child of the Svg component.
We can also use the Polygon component to render closed shapes like so:
import < Svg, Polygon >from "@react-pdf/renderer";
The points prop accepts a dataset of coordinates. This will help the app render the graphic:
The Image component gives us the ability to insert images over the network or on a local disk. This is great for displaying complex diagrams or screenshots.
This block of code renders a 500 by 500 pixel image on the PDF:
import < Image >from "@react-pdf/renderer"; const styles = StyleSheet.create(< image: < width: 500, height: 500, >, >); src="https://images.pexels.com/photos/20066389/pexels-photo-20066389/free-photo-of-a-bubble-is-floating-in-the-sky-over-trees.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2" />
The src prop contains the source URL of the image that we want to render:
Now that we’ve gone through the fundamentals, let’s discuss some advanced concepts related to using react-pdf to generate PDFs in a React project.
Just like CSS, react-pdf lets developers use the flex property, which allows for responsive design. This is handy for cases where you want your documents to scale up or down depending on the device’s screen size:
// Create styles. Notice that we have specified a flex direction. const styles = StyleSheet.create(< page: < flexDirection: "column", >, >);> >> )>>
In this piece of code, we used the flex property on both of our View components. This means that half the page will have a background color of black and the other half will have a pink colored background:
Page breaks are useful for ensuring that a certain element will always show up on the top of the page. We can enable page breaks via the break prop like so:
// Create styles const styles = StyleSheet.create(< text: < fontSize: 40, >, >); // Create Document Component> First PDF break > Second break
The result will appear as shown below:
With react-pdf, we can render dynamic text using the render prop of the Text component like so:
render=<(< pageNumber, totalPages >) => `Page $ of $` > fixed /> Hello, second page!
Here, the render prop has two arguments:
We are displaying both of their values to the client:
Note that the render function is executed twice for elements: once for layout on the page wrapping process, and again after it knows how many pages the document will have. Therefore, use it in cases where app performance is not a problem.
We can also use the render prop on our View element:
) => ( //detect if user is NOT on an even page: pageNumber % 2 === 0 && ( >>*If condition is fulfilled, display this component*/> ) )> />I'm only visible in odd pages!
The react-pdf library is just one of the various tools available in the React ecosystem that you can use to generate, render, annotate, or style PDF documents in a React application. Let’s explore other tools that you can use either in place of or alongside the react-pdf library and discuss their unique features and the ideal use cases.
At the top of the list is the wojtekmaj/react-pdf package, an easy-to-use PDF reader that enables you to display PDF documents in your React application. The package is designed solely for displaying or rendering PDF documents, making it suitable for use alongside a PDF generator such as the react-pdf package.
wojtekmaj/react-pdf has excellent community support and undergoes constant updates. Additionally, it boasts over 8K+ stars on Github and 900K+ weekly downloads on npm. With such popularity, you can be assured that it is suitable for use in your applications.
Learn more →
Features of the wojtekmaj/react-pdf library:
npm i react-pdf
react-pdf-highlighter is a lightweight PDF annotation library built on the PDF.js package by Mozilla. You can use this package alongside other libraries that generate or render PDF documents (such as react-pdf) by integrating annotation features such as highlighting text in PDF documents after generating them.
The react-pdf-highlighter package undergoes regular updates and has 900+ stars on GitHub and 5K+ weekly downloads on npm.
Features of react-pdf-highlighter:
npm i react-pdf-highlighter
react-pdf-tailwind is not exactly a PDF generator or renderer. It’s more of a utility tool that allows you to style PDF documents created with libraries such as the react-pdf library using Tailwind utility classes.
Since it’s built on Tailwind, it undergoes constant updates. It has over 400 stars on GitHub and 6K+ weekly downloads on npm. The react-pdf-tailwind library is basically a wrapper for Tailwind, so it doesn’t have any distinct features other than to style PDF documents using Tailwind utility classes.
npm i react-pdf-tailwind
react-print-pdf is an across-the-board solution for creating PDF documents in a React application. Unlike other solutions, react-print-pdf gives you full control over your document’s layout. You can design complex and customized layouts with features like footnotes, headers, margins, and more.
This open source package has good community support, undergoes constant updates, and has over 400+ stars on GitHub.
Features of react-print-pdf:
npm install @onedoc/react-print
In this article, we covered the fundamentals of the react-pdf library. Not only is it secure and robust, but it is also lightweight, thus bringing performance to the table.
Thank you so much for reading! Happy coding!
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: