View a PDF in React Native

Viewed 80647

Can anyone please provide sample code for displaying a PDF in React Native? iOS and Android.

This is what I've tried:

  render: function() {
    return <WebView
      source={require('./my.pdf')}
      />
  }

^ This results in a Red Screen of Death with the "Unable to resolve module" error.

  render: function() {
    return <WebView
      source={{uri: 'my.pdf'}}
      />
  }

^ This gives an "Error Loading Page" message in the WebView. "The requested URL was not found on this server"

I know iOS is capable of showing a PDF in a UIWebView. I assume Android can do the same. There must be something in how the source is specified that I'm missing.

5 Answers

A simple solution for this problem is to set <WebView> source/uri to this:

https://drive.google.com/viewerng/viewer?embedded=true&url={your pdf url}’

Just add style={{flex:1}} in the opening View Tag of your return and you should be fine.

The Amazon S3 Presigned URL contains query string contains "?" and "&" which confuses the outer URL.

So you have to Encode the S3 Presigned URL before passing it to the Google Doc Viewer.

Like this:

var encodedUrl = encodeURIComponent(presigned_url);

var iFrameUrl = 'https://docs.google.com/gview?url=' + encodedUrl;

In case of pdf url this will do

openLink(url) {
    return Linking.canOpenURL(url)
      .then(supported => {
        if (!supported) {
          console.log("Can't handle url: " + url);
          this.showFlashMessage('Not supported in your device');
        } else {
          return Linking.openURL(url);
        }
      })
      .catch(err => console.error('An error occurred', err));
  }
Related