Unlock the Power of Direct PDF Editing with WebViewer 10.7

How to Build a PDF Viewer with React Native PDF

By Apryse | 2018 Oct 22

Sanity Image
Read time

5 min

This tutorial addresses how to use React Native to display or preview PDFs for both Android and iOS users.

What Is React Native?

Copied to clipboard

React Native is an open source framework for building native mobile apps using JavaScript. The resulting apps are indistinguishable from those built in Swift, Objective-C, Kotlin, or Java, because they don't run inside of a webview. The UI for React Native PDF apps is rendered using native views, which provides users with the fluid look and feel of traditional native applications.

Why Build a React Native PDF Viewer?

Copied to clipboard

Building a React Native PDF reader is fairly simple, as long as your needs are also somewhat simple. It’s an easy way to create a basic PDFs. For comparison, we’ll also discuss alternative products that implement more advanced features and high-fidelity rendering if you need those.

In this tutorial, we describe how to build a PDF viewer in React Native with react-native-view-pdf to render PDFs on Android and WKWebView for rendering PDFs on iOS. The react-native-view-pdf library uses Android PdfViewer, and by extension PdfiumAndroid as the underlying rendering engine, while WKWebView uses Apple's proprietary PDF renderer.

Creating a PDF in React Native involves a few steps. First, create a new app, add the libraries, and then link the libraries. Once you’ve completed those steps, you can implement the PDF viewer using the example provided. Use the following steps to build your PDF viewer in React Native.

Step 1 - Create a New App

Copied to clipboard

We're going to use the command line, so make sure you have react-native-cli installed. From the command line:

react-native init PDFDemo
cd PDFDemo

Step 2 - Add the Libraries

Copied to clipboard

React Native uses one of the best PDF libraries. Add the react-native-view-pdf library to the project:

yarn add react-native-view-pdf

If you use npm:

npm install react-native-view-pdf --save
Copied to clipboard

After that, you need to link the library:

react-native link react-native-view-pdf

Step 4 - Implement the React Native PDF Reader

Copied to clipboard

The resourceType can be 'file', 'url', or 'base64'. If the resourceType is 'file', the library tries to load the file from the app bundle, so add the PDF file to the project using this example, and add it to the app target. For Android, it loads the file from SDCard.

import PDFView from 'react-native-view-pdf';

const resources = {
  file: Platform.OS === 'ios' ? 'test-pdf.pdf' : '/sdcard/Download/test-pdf.pdf',
  url: 'https://www.ets.org/Media/Tests/TOEFL/pdf/SampleQuestions.pdf',
  base64: 'JVBERi0xLjMKJcfs...',
};

export default class App extends React.Component {
  render() {
    const resourceType = 'base64';

    return (
      <View style={{ flex: 1 }}>
        {/* Some Controls to change PDF resource */}
        <PDFView
          fadeInDuration={250.0}
          style={{ flex: 1 }}
          resource={resources[resourceType]}
          resourceType={resourceType}
          onLoad={() => console.log(`PDF rendered from ${resourceType}`)}
          onError={() => console.log('Cannot render PDF', error)}
        />
      </View>
    );
  }
}

And you're done. You can now open a PDF, as shown in the React Native PDF example below.

Open a React Native PDF

This is a great solution for basic viewing use cases, but if you need more robust functionality in a PDF editor, like annotation, real-time collaboration, form filling, text search, page manipulation, or others, you have to implement them yourself. Also beware that the Apple and PDFium rendering engines only work well if your documents are simple and you can afford to have some rendering inconsistencies or failures.

For more robust functionality and high fidelity rendering, Apryse offers both an Android & iOS React Native PDF library. Some of the features include:

The PDF generator also supports viewing other file extensions such as .docx, .doc, .pptx, .xlsx, and various image formats (learn more about office viewing library on Android & iOS). It allows stream conversion of these non-PDF documents to PDF format so you can view the document while conversion happens. Undo/redo and reflow mode are also available on Android & iOS.

Building a PDF Viewer with Apryse

Copied to clipboard

Use the Apryse DocumentView component just like any other React Native PDF component:

import { DocumentView } from 'react-native-pdftron';
const RNPdftron = NativeModules.RNPdftron;

export default class App extends Component<Props> {

  onLeadingNavButtonPressed = () => {
    console.log('leading nav button pressed');
    if (Platform.OS === 'ios') {
      Alert.alert(
        'App',
        'onLeadingNavButtonPressed',
        [
          {text: 'OK', onPress: () => console.log('OK Pressed')},
        ],
        { cancelable: true }
      )
    } else {
      BackHandler.exitApp();
    }
  }

  render() {
    const path = Platform.OS === 'ios' ? "sample" : "android.resource://com.myapp/raw/sample.pdf";

    return (
      <DocumentView
        document={path}
        showLeadingNavButton={true}
        leadingNavButtonIcon={Platform.OS === 'ios' ? 'ic_close_black_24px.png' : 'ic_arrow_back_white_24dp'}
        onLeadingNavButtonPressed={this.onLeadingNavButtonPressed}
      />
    );
  }
}

Android Preview:

Android preview

iOS Preview:

iOS preview

You can view the API documentation for DocumentView. To get started, clone Apryse's React Native open source wrapper.

Conclusion

Copied to clipboard

Building a PDF Viewer with React Native can be straightforward, but once you need more advanced features or high-fidelity rendering, open source may not be the best approach. Apryse has hundreds of features, 30+ file formats, and a proven rendering engine built right in, and it's just as simple to implement.

Apryse SDK for mobile comes with many out-of-the-box controls and tools that can be wrapped in React Native. To learn about even more functionality, check out the complete Apryse PDF SDK.

Note: Interested in what Apryse SDK for Web offers? Check out our Everything WebViewer blog.

If you are interested in seeing any of the controls and tools in React Native, feel free to contact us or submit a feature request. You are also welcome to improve our open source React Native wrapper. Please submit a pull request if you are interested. Stay tuned for future improvements on the Apryse React Native wrapper!

Sanity Image

Apryse

Share this post

email
linkedIn
twitter