Blog Post

How to Build a React Native PDF Viewer

Illustration: How to Build a React Native PDF Viewer

There are several PDF libraries for React Native, and it can be challenging to evaluate all the offerings.

So in this tutorial, we’ll build a React Native PDF viewer using one of the most popular open source libraries, react-native-pdf, and our solution, React Native PDF SDK.

Then, we’ll open and view a PDF in a React Native project that uses both react-native-pdf and PSPDFKit so you can compare the experiences and capabilities of the two libraries yourself.

And finally, at the end of the article, we’ll discuss the differences between the two libraries so you can make an informed decision based on your requirements and use case.

So, let’s get started!

The Use Case

This post assumes you’re familiar with React Native and that you’ve previously developed apps using React Native. If that isn’t the case, you can use our getting started guides to create a new React Native project that uses PSPDFKit. Or, if you’re in a hurry, you can download our ready-to-run example project and follow the instructions from its README.

In the video below, you can see how we open a PDF file using react-native-pdf and PSPDFKit for React Native.

Now, let’s take a look at the steps involved!

Step 1: Creating a React Native Project

In the terminal app, change the current working directory to the location you wish to save your project. In this example, we’ll use the ~/Documents/ directory:

cd ~/Documents

Then, create the React Native project by running the following command:

react-native init ReactNativePDFViewer

Next, you’ll add the required dependencies.

Step 2: Adding the Required Dependencies

Change the location of the current working directory inside the project:

cd ReactNativePDFViewer

Then, add the PSPDFKit dependency:

yarn add github:PSPDFKit/react-native

Add the required react-native-pdf dependencies, like so:

yarn add react-native-pdf rn-fetch-blob @react-native-community/progress-bar-android @react-native-community/progress-view fbjs

Next, install all the dependencies for the project:

yarn install

Open the project’s build.gradle file:

open android/build.gradle

Add the PSPDFKit repository to download the PSPDFKit library:

...
 allprojects {
     repositories {
         mavenLocal()
+        maven {
+            url 'https://customers.pspdfkit.com/maven/'
+        }
...

Open the app’s build.gradle file:

open android/app/build.gradle

Enable multidex support and update the packagingOptions for compatibility with react-native-pdf like so:

android {
...

+ packagingOptions {
+     pickFirst 'lib/x86/libc++_shared.so'
+     pickFirst 'lib/x86_64/libjsc.so'
+     pickFirst 'lib/arm64-v8a/libjsc.so'
+     pickFirst 'lib/arm64-v8a/libc++_shared.so'
+     pickFirst 'lib/x86_64/libc++_shared.so'
+     pickFirst 'lib/armeabi-v7a/libc++_shared.so'
+ }
  defaultConfig {
      applicationId "com.pspdfkitdemo"
      minSdkVersion rootProject.ext.minSdkVersion
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
+     multiDexEnabled true
  }
}
...

Open your project’s Podfile in a text editor to update the platform to iOS 13:

open ios/Podfile

Your Podfile should look like this:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

- platform :ios, '11.0'
+ platform :ios, '13.0'

...

Change the location of the current working directory to the ios folder:

cd ios

Install the CocoaPods dependencies:

pod install

Open your project’s workspace in Xcode:

open ReactNativePDFViewer.xcworkspace

Make sure the deployment target is set to 13.0 or higher:

Screenshot showing where to update the deployment target in Xcode

Change View controller-based status bar appearance to YES in your project’s Info.plist:

Screen shot indicating where to find the view controller-based status bar appearance property to change the value in Xcode

With that, you’re ready to open a PDF.

Step 3: Opening a PDF Document

Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

Xcode window showing where to drag-and-drop the document to display in the application

Change the location of the current working directory back to the root project folder:

cd ..

Create the assets directory if you don’t have one already:

mkdir android/app/src/main/assets

Copy a PDF document into your assets directory:

cp ~/Downloads/Document.pdf android/app/src/main/assets/Document.pdf

Open your App.js file:

open App.js

Replace the entire contents of App.js with the following code snippet:

import React, { Component } from 'react';
import {
	AppRegistry,
	Button,
	Dimensions,
	StyleSheet,
	View,
} from 'react-native';
import PSPDFKitView from 'react-native-pspdfkit';
import Pdf from 'react-native-pdf';

const DOCUMENT =
	Platform.OS === 'ios'
		? 'Document.pdf'
		: 'file:///android_asset/Document.pdf';
const source =
	Platform.OS === 'ios'
		? require('./ios/Document.pdf')
		: { uri: 'bundle-assets://Document.pdf' };

export default class ReactNativePDFViewer extends Component<Props> {
	constructor(props) {
		super(props);
		this.state = {
			pdfViewer: null,
		};
	}

	render() {
		if (this.state.pdfViewer == null) {
			renderView = (
				<View style={styles.container} ref="Welcome">
					<Button
						onPress={async () => {
							this.setState({
								pdfViewer: 'react-native-pdf',
							});
						}}
						title="Open a PDF with react-native-pdf"
					/>
					<Button
						onPress={async () => {
							this.setState({
								pdfViewer: 'PSPDFKit',
							});
						}}
						title="Open a PDF with PSPDFKit"
					/>
				</View>
			);
		} else if (this.state.pdfViewer == 'PSPDFKit') {
			renderView = (
				<PSPDFKitView
					ref="PSPDFKit"
					// Set the document.
					document={DOCUMENT}
					// Show the back button on Android.
					showNavigationButtonInToolbar={true}
					// Show the back button on iOS.
					showCloseButton={true}
					// The configuration is optional.
					configuration={{
						showThumbnailBar: 'scrollable',
					}}
					// Set the document to `null` on Android.
					onNavigationButtonClicked={(event) => {
						this.setState({ pdfViewer: null });
					}}
					// Set the document to `null` on iOS.
					onCloseButtonPressed={(event) => {
						this.setState({ pdfViewer: null });
					}}
					style={styles.pdf}
				/>
			);
		} else if (this.state.pdfViewer == 'react-native-pdf') {
			renderView = (
				<View style={{ flex: 1 }}>
					<Pdf
						ref="react-native-pdf"
						source={source}
						enablePaging={true}
						horizontal={true}
						style={styles.pdf}
					/>
					<View style={styles.closeButton}>
						<View>
							<Button
								onPress={() => {
									this.setState({ pdfViewer: null });
								}}
								title="Close"
							/>
						</View>
					</View>
				</View>
			);
		}

		return <View style={{ flex: 1 }}>{renderView}</View>;
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#F5FCFF',
	},
	pdf: {
		flex: 1,
		width: Dimensions.get('window').width,
		height: Dimensions.get('window').height,
	},
	closeButton: {
		position: 'absolute',
		left: 10,
		top: 30,
		flexDirection: 'row',
		height: 60,
		alignItems: 'center',
		padding: 10,
	},
});

AppRegistry.registerComponent(
	'ReactNativePDFViewer',
	() => ReactNativePDFViewer,
);

That’s all! The app is now ready to launch! Go back to the terminal app and run:

npx react-native run-android
npx react-native run-ios

You’re done!

Conclusion

We hope this post will help you build a PDF viewer using react-native-pdf and PSPDFKit for React Native in your React Native project. As you can see, react-native-pdf is a great solution for many use cases.

However, sometimes your business may require more complex features for handling PDFs in your React Native project, such as:

  • PDF Annotation Supportreact-native-pdf will only render annotations that were already in the source file. It doesn’t have annotation editing support, so your users won’t be able to create, update, or delete annotations to review a PDF document.

  • Interactive PDF Forms — Just like with annotations, react-native-pdf will only render forms and their values that were already in the source file. It doesn’t have form editing support, so your users won’t be able to fill forms in a PDF document.

  • Digital Signaturesreact-native-pdf currently has no support for digital signatures, which are used to verify the authenticity of a filled-out PDF.

  • Long-Term Support — Currently, the latest update for react-native-pdf dates back to October 2020. At PSPDFKit, we release regular updates to add new features and enhancements, fix bugs, and maintain compatibility with the latest React Native changes, dependencies, and operating system updates.

If your business relies on any of the above features, consider looking into alternatives. At PSPDFKit, we offer a commercial, feature-rich, and completely customizable React Native PDF viewer library that’s easy to integrate and comes with well-documented APIs to handle advanced use cases. Check out our demos to see it in action.

If you have any questions about our React Native PDF library, please don’t hesitate to reach out to us. We’re happy to help!

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

Related Articles

Explore more
PRODUCTS  |  React Native • Releases

PSPDFKit 2.3 for React Native Adds Toolbar Customization

DEVELOPMENT  |  Android • iOS • Cordova • Flutter • Ionic • React Native • Xamarin

Cross-Platform Mobile Frameworks — An iOS Engineer's Perspective

TUTORIALS  |  React Native • How To

Why and How to Fork the PSPDFKit for React Native Repository