React Native Download Pdf

 Run the following command with your project directory

    npm i rn-fetch-blob   

AndroidManifest.xml

Add below permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

Code for download pdf

    open index.js and replace the code with the following code

Index.js

    import React,{Component} from 'react';                  
    import { View, Button, Alert,  PermissionsAndroid} from "react-native";
    import styles from './styles';                                      
    import RNFetchBlob from 'rn-fetch-blob';               

    class PdfDownload extends Component {               

        actualDownload = (pdf_url,ID) => {
            const { config, fs } = RNFetchBlob;
            const downloads = fs.dirs.DownloadDir;
            return config({
                fileCache : true,
                addAndroidDownloads : {
                  useDownloadManager : true,
                  notification : true,
                  mediaScannable: true,
                  mime : 'application/pdf',
                  path:  downloads + '/' + 'id' + '.pdf',
                  description : 'Downloading pdf file.'
            }
        })
        .fetch('GET', pdf_url)
        .then((res) => {
              Alert.alert('The file saved to ', res.path());
         })
         .catch((e) => {
              console.log(e)
        });
      }

        async downloadFile(pdf_url) {
            try {
                const granted = await       PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                  this.actualDownload(pdf_url);
            } else {
                  Alert.alert('Permission Denied!', 'You need to give storage permission to download the file');
            }
         } catch (err) {
            console.warn(err);
          } 
      }

        render() {
            return (
                <View style={styles.container}>
                    <Button title="open" onPress={this.downloadFile}></Button>
                </View>
            );
        }
    }

    export default PdfDownload;

    To Run the App

        react-native run-android   

Comments

Popular posts from this blog

React Native Floating Label Textinput

React Native Tab View

React Native Modal box