react-nativepdfexpo

View pdf from URL in Expo React Native Project


I have been trying to open a pdf file using react native, but every library that I try generates an error. I tried the code below:

import React, { Component } from 'react';
import Pdf from 'react-native-pdf';

class OpenBGReport extends Component {
  render() {
    const source = {uri:'http://samples.leanpub.com/thereactnativebook-sample.pdf',cache:true};

    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);
                    }}
                    style={styles.pdf}/>
      </View>
    );
  }
}

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,
    }
});

export default OpenBGReport;

However, after installing react-native-pdf, my project stop working and returns: null is not an object (evaluating 'rnfetchblob.documentdir')

What is the best way to open and display a pdf from a URL in react native?

Thanks


Solution

  • The best way I found to handle PDF files with Expo is to use buffer to turn them into base64 files, store them in the FileSystem and Share them:

      import { Buffer } from "buffer";
      import * as FileSystem from "expo-file-system";
      import * as Sharing from "expo-sharing";
    
      res = await // fetch PDF
    
      const buff = Buffer.from(res, "base64");
      const base64 = buff.toString("base64");
    
      const fileUri =
        FileSystem.documentDirectory + `${encodeURI("name-of-the-pdf")}.pdf`;
    
    
      await FileSystem.writeAsStringAsync(fileUri, base64, {
        encoding: FileSystem.EncodingType.Base64,
      });
    
    
      Sharing.shareAsync(res);
    

    Note: You need to install buffer, expo-file-system and expo-sharing