Blog Post

How to Create a PDF with React

Illustration: How to Create a PDF with React

Most modern apps need ways to generate PDF files from data. Regardless of what you’re trying to create — invoices, sales contracts, or certificates — you’ll often end up in need of a method for programmatically assembling PDF documents.

In this article, we’ll examine a popular React-based solution that can be used to generate PDFs by using a declarative API: react-pdf by Diego Muracciole. This library makes it easy to create PDFs by using typical React-style components.

Getting Started with react-pdf

React-pdf works in the browser, on the server, or on mobile devices, just like your existing React (or React Native) application does. To keep things simple for this article, we’ll use CodeSandbox to run a simple React application directly in the browser.

ℹ️ Note: By default, react-pdf comes with a simple PDF viewer that uses an <iframe> to render the document in the browser. However, the CodeSandbox examples use our Javascript PDF library to view the PDFs.

To get started with react-pdf, first add it as a dependency to your JavaScript application:

yarn add @react-pdf/renderer
npm install @react-pdf/renderer

To create a PDF, you have to use the basic components exposed by react-pdf, which are used as primitives (like DOM elements in React DOM and <View> in React Native). These can be composed into custom components as well. The following components are the most important ones:

  • <Document> is the root of a PDF file.

  • <Page> describes an individual page. It must have a dimension (you’re using A4 in this example).

  • <View> is a general-purpose container used for styling and formatting. You can use StyleSheet.create() similar to how this API is used in React Native to style your views with the full power of Flexbox for laying out PDFs.

  • <Text> is used to display text.

Now you’ll create your first PDF. Start with a simple two-column layout using Flexbox. To do this, use a page view and set its flexDirection to row so that items are aligned in a row. Then, insert a section view with flexGrow: 1 to tell the layout engine that the items should expand to the biggest possible width. If you have two items, they’ll now be evenly distributed:

import React from 'react';
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';

const styles = StyleSheet.create({
	page: {
		flexDirection: 'row',
	},
	section: {
		flexGrow: 1,
	},
});

const MyDocument = (
	<Document>
		<Page size="A4" style={styles.page}>
			<View style={styles.section}>
				<Text>Hello World!</Text>
			</View>
			<View style={styles.section}>
				<Text>We're inside a PDF!</Text>
			</View>
		</Page>
	</Document>
);

That’s already enough to create the PDF! To render it, you can use the <PDFViewer> React DOM component that ships with react-pdf. It uses an <iframe> to render the document in the browser:

ReactDOM.render(
	<PDFViewer>{MyDocument}</PDFViewer>,
	document.getElementById('root'),
);

You can also refer to our PSPDFKit for Web in React example and use a more advanced PDF viewer, like we did in the CodeSandbox example.

Edit Create PDFs with React — Getting Started

react-pdf’s Rendering Process

Before a PDF is generated, react-pdf goes through several steps to lay out the pages and encode them as a valid PDF. The official website features a wonderful graphic (shown below) that explains the rendering pipeline.

Internal structures creation — PDF document creation & metadata — Fetching assets — Wrapping pages — Rendering — Finish document

The most interesting aspect of this pipeline is that some of the work — the creation of internal structures and PDF documents — can already be started before all assets (fonts, images) are loaded via the network. This will speed up the rendering process.

Now you’ll try some more powerful features. More specifically, you’ll add images and links to your PDF document.

In addition to the components you used before, you’ll now take a look at two more:

  • <Image>, which is used to place images inside the PDF file.

  • <Link>, which is used to create hyperlink annotations.

For this example, you want to create a two-row layout, where the first row will show the PSPDFKit logo centered, and the second row will show a small paragraph of text, followed by a link to the website.

Start by changing the flexDirection of the page view to column instead of row, and create a new centerImage view that uses alignItems: "center" to center the logo. After that, use an <Image> element to load a PNG image directly into the PDF:

const styles = StyleSheet.create({
	page: {
		flexDirection: 'column',
	},
	image: {
		width: '50%',
		padding: 10,
	},
	centerImage: {
		alignItems: 'center',
		flexGrow: 1,
	},
});

const MyDocument = (
	<Document>
		<Page style={styles.page} size="A4">
			<View style={styles.centerImage}>
				<Image style={styles.image} src="/pspdfkit-logo.png" />
			</View>
		</Page>
	</Document>
);

The flexGrow property on the centerImage view will make sure the image view uses all the available height and pushes the text elements that you’re adding next to the bottom. To add links, use the <Link> element inside text elements. This looks similar to an HTML anchor tag, but it’ll create proper link annotations inside the PDF:

const styles = StyleSheet.create({
	text: {
		width: '100%',
		backgroundColor: '#f0f0f0',
		color: '#212121',
	},
});

const MyDocument = (
	<Document>
		<Page style={styles.page} size="A4">
			<Text style={styles.text}>Some text...</Text>
			<Text style={styles.text}>Some more text...</Text>
			<Text style={styles.text}>
				Learn more at <Link src="https://pspdfkit.com/">pspdfkit.com</Link>
			</Text>
		</Page>
	</Document>
);

You can see that adding links and images to a PDF is as simple as adding links and images to your React application. Feel free to play around with the setup using the CodeSandbox link below!

Edit Create PDFs with React — Images and Links

Conclusion

As you saw, react-pdf is a powerful tool for generating PDF files with React, no matter the platform you’re on. Our examples work out of the box in a web browser, but they can also easily be ported to a Node.js server or a mobile phone using React Native. Generating PDFs has never been easier.

React-pdf uses an <iframe> to show the PDF using the browser’s default PDF viewer. If your use case requires consistent cross-browser behavior and more advanced PDF features like PDF annotations, different view settings, and individual customization, we recommend reading our other React-themed blog posts: Open a PDF in React on the Web with react-pdf and How to Add PDF Support to Your Web App in No Time.

Our React PDF Library comes with more than 30 out-of-the-box features and has well-documented APIs to handle advanced use cases. Try our PDF library using our free trial, and check out our demos to see what’s possible.

Related Products
Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
PRODUCTS  |  Web • Releases • Components

PSPDFKit for Web 2024.3 Features New Stamps and Signing UI, Export to Office Formats, and More

PRODUCTS  |  Web • Releases • Components

PSPDFKit for Web 2024.2 Features New Unified UI Icons, Shadow DOM, and Tab Ordering

PRODUCTS  |  Web

Now Available for Public Preview: New Document Authoring Experience Provides Glimpse into the Future of Editing