React-PDF

Learn via video courses
Topics Covered

Overview

A common feature required in many applications is the ability to generate PDFs. The majority of well-known programming languages typically have established libraries and tooling that enable programmatic PDF generation. Creating PDF files from data is a requirement for the majority of modern applications. It doesn't matter what kind of document you want to create—invoices, sales contracts, or certifications—you'll almost always require a method for automatically creating PDF files.

Prerequisites

  • Node js should be installed locally on your system. You can download Node from their official website. A Node version least greater than 14.X, you can check the version of node using command node -v.
  • A package manager like npm (Node package manager), which is typically installed with Node js installation. NPM version should be at least greater than 5.X, you can check the version of npm using command npm -v.
  • A text editor should be present of your choice to manage your react project directories. VS code is recommend.

Open Source React.js PDF Viewer Libraries

A few open source React PDF viewer libraries are available. With 170K weekly downloads on npm, the @react-pdf/renderer library is among the most widely used. On the server, in the browser, or on mobile devices, it is used to create PDF files. React-pdf by Wojciech Maj is another well-liked library, with about 400K weekly downloads on npm. It is utilised to display current PDFs. We'll examine how to employ this library in order to develop a PDF viewer.

React components can open PDF files and render them with the help of the react-pdf component API. An open source JavaScript library for rendering PDF files is called PDF.js.

Before starting our project, let's take a closer look at some of the features of this library :

  • Easy to use
  • support for non-Latin characters, text selection, and custom events
  • various rendering techniques
  • compatibility with multiple browsers
  • Accessibility
  • Free and open-source software

The main advantage of this package is that it can be used on a server with Node and in a browser. This enables you to utilise JavaScript's isomorphism, which we have all grown to love, and share document templates across your stack. It's simple to create a report with a straightforward layout using React PDF. However, rendering more complicated layouts becomes a little bit of a hassle.

React-pdf’s Rendering Process

React-pdf goes through a number of steps to lay out the pages and encode them as a legitimate PDF before producing one. The rendering pipeline is depicted in a graphic on the official website.

react pdf rendering

The most intriguing feature of this pipeline is that some work, like creating internal structures and PDF documents, can be started even before all assets (such as fonts and images) are loaded over the network. The rendering process will go more quickly as a result. You will now test out some more potent features. You will specifically include images and links in your PDF file.

  1. Internal structures creation : The React element tree must first be converted into the proper internal instances for each type of component in order to proceed. This entails preserving the parent-child relationship between these nodes. Other than Document, each node will represent a block with a height, width, paddings, and margins inside a document (yet to be discovered). React-pdf will now use this data structure to determine where each block will appear in the finished Document.
  2. Resolve styles : Pre-processing node styles and defining default values for the required properties that the user did not supply are both done in this step. All subsequent steps can then be built on the premise that the tree contains definitions for all necessary styles. Unit conversion, style expansion, and style inheritance are all a part of the pre-processing.
  3. Fetching assets : It's time to request all the necessary resources. In order to obtain any necessary font, image, or emoji, we navigate the internal nodes tree. We run each of these requests asynchronously, but we won't proceed until each one has been completed (with success or failure).
  4. Layout text We can arrange text into paragraphs now that all of the fonts have loaded. This is a crucial and difficult step where characters are first turned into glyphs using the right font family and size. Images or emojis are then embedded, if necessary, and finally, characters are broken into lines either on whitespaces or by breaking words according to language (or custom) rules.
  5. Wrapping pages : This process takes the longest because it not only involves figuring out where each element is in the Document and how much room it will require but also dividing those elements into separate pages. We perform page breaking based on a set of programmable heuristics and internally use Yoga layout to compute the size and coordinates of each node inside the Document.
  6. Rendering : The process of making the PDF file. We make use of the fantastic pdfkit for this task. At this point, we have our internal tree structure and all the information required to produce our Document. The only thing left to do is choose what we want to do with the data. Depending on the binding you're using, this will vary, but in general, it refers to either showing it or saving it.

Getting Started

  • Browser support All current browsers are supported by React-PDF. The most recent versions of Chrome, Edge, Safari, Firefox, and Opera are used for testing.

    React-PDF v6 is compatible with the following browsers :

    • Chrome ≥76
    • Edge (Chromium-based)
    • Safari ≥14.1
    • Firefox ≥90(?)

By providing additional polyfills (for example, for Promise.allSettled) and configuring your bundler to transpile pdfjs-dist, you can increase the number of supported browsers.

Use React-PDF v5 if you need to support earlier browser versions. React-PDF v4 must be used if support for Internet Explorer 11 is required.

  • React Your project must use React 16.8 or later in order to use the most recent version of React-PDF. Please use the table below to find the appropriate React-PDF version if you are using an older version of React.
React versionNewest compatible React-PDF version
≥16.8latest
≥16.35.x
≥15.54.x
  • Preact Preact and React-PDF are both compatible.

  • Installation With react-pdf, getting started is incredibly easy.

    Using Yarn

    Using npm

You still need React to use a renderer because it only implements how elements render into something (and react-dom for client-side document generation).

Building a React.js PDF Viewer with react-pdf

You can easily set up a react application with the help of create-react-app. So first setup a react application using the create-react-app by the below command :

Change the directory to the project folder once the project has been created :

Adding react-pdf :

From the terminal, you can now install the npm package for the react-pdf library :

In the react-pdf-tutorial project's public directory, place the file you want to render.

Displaying a PDF :

Document and Page are the two components that make up react-pdf. A document must be present in order to open a PDF. Pages that are used to render the PDF page can be mounted within the document. Open src/App.js and replace its contents with the following to incorporate this into your example project :

React-pdf requires a PDF.js worker in order to function. There are several ways to accomplish this. React-pdf/dist/esm/Document entry.webpack's and Page were imported, so Webpack 5 will automatically provide the worker.

Now you can start the application by running :

You will see the following output on http://localhost:3000/ :

displaying pdf output

React-pdf lacks a user interface, which is one of its drawbacks. In this illustration, you rendered two page-navigation buttons and displayed the overall number of pages.

React-pdf is a wonderful open source project overall, but it does have some drawbacks :

  • It doesn't have a user interface when you first get it. You will have to create a UI from scratch if you need it to aid users in reading a PDF.
  • The text selection function is broken. It's not an enjoyable user experience if you try to select some text in the PDF.

Adding Some More Capabilities

  • Annotation Library

    PSPDFKit for Web is a JavaScript library that is used for creation, removal and editing of the PDF annotations. It is fully compatible with React thereby offering a robust API and a beautiful user-interface.

    Key Functionalities are as folows:

    • Types of annotation — Highlight, text, ink, note, shapes etc.
    • Create, edit, remove can be programmatically done or by using the UI
    • Import and export
    • Annotation events
    • Cloudy annotations
    • Custom appearances
    • Synchronize
    • Customizable UI
  • PDF Editor Library

    We can use the PDF editor library to perform various operations. The functionalities of this library are listed below.

    Key functionalities of editor library include:

    • Create, edit, or remove
    • Rotate, merge, split, delete, or add pages
    • Edit PDFs directly in the browser
    • Works on all modern browsers and devices
    • Programmatically edit PDFs without the UI
    • Hide buttons, match your look and feel, and more
    • Add forms, signing, annotation, etc
  • PDF Form Library

    The PDF Form Library is fully compatible with React and offers an API to access the PDF form objects, as well as a UI for filling forms in a react application.

    Key features of PDF form library are as follows:

    • Fill forms
    • Export, submit, or embed data into the PDF
    • Drag & drop fields to turn PDFs into fillable forms
    • Create APIs to generate forms and fields
    • Style colors, backgrounds, borders, and widths
    • Execute JavaScript to validate form data
    • Trigger workflows or automations
    • Add signing, annotation, editing, and more
  • Digital Signature Library

    The Digital Signature Library is used for signing PDF documents with an electronic signature or with encrypted certificate-based digital signatures.

    The key features of Digital Signature Library are as follows:

    • Creating digital signatures
    • Validating digital signatures
    • Add drawn, scanned, or typed e-signatures
    • Store the signature locaaly for future use
    • Trigger events for workflows or automations
    • Hide buttons, create your own looks and feel etc.
    • Sign PDFs directly in the browser
  • Instant Sync and Collaboration

    Instant Sync and Collaboration is used for synchronizing annotations across multiple concurrent users, devices, or sessions.

    The features of this library are as follows:

    • Real time Sync edits
    • It is self hosted
    • It can handle concurrent changes
    • It provides Secure authentication
  • PDF Redaction Library

    The PDF Redaction Library is used for permanently redacting content in PDF documents.

    Key features are as follows:

    • Programmatically use the user-interface
    • Remove the content permanently
    • Search and redact
    • Userscan customise according to their needs
    • It works on all modern browsers
  • User Interface Customization

    It is used to customize every part of the user interface. It provides an API for configuring the behavior and appearance. It allows the users to delete or add buttons, change the theme, etc.

    Key features are as follows:

    • It allows to modify CSS, add dark theme, or replace icons
    • It allows to remove, rearrange, and create new tools or toolbars
    • It allows customisation of thumbnails, outline, and bookmarks
    • it makes the application available in other languages

Conclusion

  • Similar to how your existing React (or React Native) application works, React-pdf can be used in browsers, servers, and on mobile devices.
  • An easy-to-use PDF viewer is included by default with react-pdf, which uses an HTML <iframe> element to display the document in the browser.
  • React-pdf by Wojciech Maj is another well-liked library, with about 400K weekly downloads on npm. It is utilised to display current PDFs.
  • Document and Page are the two components that make up react-pdf. A document must be present in order to open a PDF. Pages that are used to render the PDF page can be mounted within the document.
  • The features of react pdf library are easy to use, support for non-Latin characters, text selection, and custom events, various rendering techniques, compatibility with multiple browsers and Free and open-source software.
  • The main advantage of this package is that it can be used on a server with Node and in a browser. This enables you to utilise JavaScript's isomorphism.
  • React-pdf goes through a number of steps to lay out the pages and encode them as a legitimate PDF before producing one.
  • All current browsers are supported by React-PDF. The most recent versions of Chrome, Edge, Safari, Firefox, and Opera are used for testing.