How to Display PDF files in React Native

The Portable Document Format (PDF) is one of the most popular formats used for documents. In this blog post, let’s check how to show pdf files in react native.

React Native Pdf is a third party that helps us to open and read pdf files from a URL or local assets in react native. It has important features such as drag and zoom, password-protected pdf support, etc. In short, you can create a pdf viewer with this library.

Firstly, install react native pdf using the following command.

npm install react-native-pdf

This library has a dependency on other libraries namely rn fetch blob, progress bar android, and react native progress view. Install these libraries using the following command.

npm install rn-fetch-blob @react-native-community/progress-bar-android @react-native-community/progress-view --save

Now, you can create a simple pdf viewer in react native as given below.

import React from 'react';
import {StyleSheet, Dimensions, View} from 'react-native';
import Pdf from 'react-native-pdf';

const source = {
  uri: 'http://samples.leanpub.com/thereactnativebook-sample.pdf',
  cache: true,
};
const App = () => {
  return (
    <View style={styles.container}>
      <Pdf
        source={source}
        onLoadComplete={(numberOfPages, filePath) => {
          console.log(`number of pages: ${numberOfPages}`);
        }}
        onPageChanged={(page, numberOfPages) => {
          console.log(`current page: ${page}`);
        }}
        onError={(error) => {
          console.log(error);
        }}
        onPressLink={(uri) => {
          console.log(`Link presse: ${uri}`);
        }}
        style={styles.pdf}
      />
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginTop: 25,
  },
  pdf: {
    flex: 1,
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
});

The output of this react native pdf viewer example is as given below.

This is just a basic example and you can go through the official documentation of react native pdf library to do advanced things.

This react native example is tested with react native version 0.63.4 and react native pdf version 6.2.2.

1 thought on “How to Display PDF files in React Native”

  1. Pingback: How to Create Thumbnails for PDF Files in React Native – REACT NATIVE FOR YOU

Leave a Reply

%d bloggers like this: