How to Create a PDF with React

Ashen Wijesingha
MS Club of SLIIT
Published in
5 min readApr 7, 2022

Most current applications require the ability to produce PDF files from data. Regardless of what type of document you’re seeking to make — invoices, sales contracts, or certifications — you’ll almost always find yourself in need of a mechanism for programmatically building PDF files.

Refferance: https://github.com/diegomura/react-pdf.git

In this post, we’ll look at react-pdf by Diego Muracciole, which is a popular React-based solution that can be used to produce PDFs through the use of a declarative API and is written in React. This library simplifies the process of creating PDFs by utilizing components that are typical of the React framework.

Getting Started with react-pdf

react-pdfcan be used in the browser, on the server, or on mobile devices in the same way that your current React (or React Native) application can. Because we want to keep things simple for this post, we’ll utilize CodeSandbox to execute a straightforward React application right in the browser.

Remark: By default, react-pdf ships with a straightforward PDF viewer that displays the document in the browser using an HTML <iframe> element. The CodeSandbox examples, on the other hand, make use of our Javascript PDF library to display the PDFs.

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

yarn add @react-pdf/rendererORnpm 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.

You will now produce your very first PDF document. Begin with a straightforward two-column layout that makes use of Flexbox. In order to accomplish this, create a page view and set it flexDirectionto rowresulting in items being aligned in a row. Then, introduce a section view with the flexGrow: 1attribute to instruct the layout engine that the items should be expanded to the greatest extent feasible in terms of size. For example, if you have two things, they will now be equally distributed as follows:

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 is already sufficient for creating the PDF! To display it, you may make use of the <PDFViewer> React DOM component, which comes included with react-pdf. For rendering the content in the browser, it makes use of a <iframe> .

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

react-pdf’s Rendering Process

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

In this pipeline, the most noteworthy feature to note is that part of the work — such as the construction of internal structures and PDF documents — may begin even before all of the assets (fonts, photos, and other data) are imported over the network. The rendering process will be accelerated as a result of this.

You’ll now be able to experiment with some more powerful features. More precisely, you’ll be including pictures and hyperlinks into your PDF file.

Enhancing Your Content with Images and Links

You’ll now examine two additional components in addition to the ones you already examined:

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

A two-row layout with the sample logo in the middle and a tiny paragraph of text in the second row is what you’re looking for in this example.

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="/ms-club.png" />
</View>
</Page>
</Document>
);

Your text components will be placed below an centerImageview if you set its flexGrowvalue to true, ensuring that all available space is utilized. The <Link> element may be used to include hyperlinks in your content. This appears to be an HTML anchor element, but it will really provide correct link annotations in 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://msclubsliit.org/">msclubsliit.org</Link>
</Text>
</Page>
</Document>
);

Regardless of the platform, you’re using, react-pdf is a powerful tool for creating PDF files with React. Node.js servers and mobile phones can use React Native to run our examples, but they also function in a web browser right out of the box. Never before has the process of creating PDFs been so simple.

When you use React-pdf, you’ll be shown the PDF in a browser’s default PDF reader. You need to be able to employ PDF annotations, multiple views, and individual customization if your use case calls for consistent cross-browser behavior.

If you like this article please hit the clap button as many times as you like, as it keeps me motivated to write more articles. Have a great weekend, Happy Hacking 😉.

And Don’t forget to ping me on Linkedin.

--

--

Ashen Wijesingha
MS Club of SLIIT

I'm reading for my Software Engineering degree program at SLIIT. Also, I'm a driven individual with the ability to adapt to any situation.