skip to Main Content

I’m currently building a React Native application that should be able to work in offline mode. The data will be fetched from the API whenever user has internet connection and call "refresh" action.

So I would like to know the best approach to download the pdf`s files to the mobile storage, where user will be able to view them in aplication preview.

My apprehension is mostly about the pdf files, because application will download more than 100+ pdf files on update, once a month.

I’m currently having data in async storage, with the name of the pdf files, and also ready server with all the pdf files that I need to download on user`s mobile.

2

Answers


  1. To download pdf you can use react-native-blob-util,
    there is also an alternative option rn-fetch-blob.

    For upload files you can use
    react-native-fs

    You can get an example from the package repository.

    Login or Signup to reply.
  2. To download multiple PDF files in a React Native application, you can make use of the react-native-fs library, which provides a set of file system APIs for React Native. Here’s a step-by-step guide on how to achieve this:

    Step 1: Install the required dependencies.

    npm install react-native-fs --save
    

    Step 2: Link the library to your project.

    react-native link react-native-fs
    

    Step 3: Request the necessary permissions for file storage.
    On Android, you need to add the following permissions to your AndroidManifest.xml file:

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

    On iOS, you don’t need to request explicit permissions.

    Step 4: Import the necessary components.

    import RNFS from 'react-native-fs';
    import { PermissionsAndroid } from 'react-native';
    

    Step 5: Create a function to download the PDF files.

    const downloadPDFs = async () => {
      // Check and request permissions on Android
      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        ]);
      
        if (
          granted['android.permission.WRITE_EXTERNAL_STORAGE'] === PermissionsAndroid.RESULTS.GRANTED &&
          granted['android.permission.READ_EXTERNAL_STORAGE'] === PermissionsAndroid.RESULTS.GRANTED
        ) {
          // Proceed with the download
          downloadFiles();
        } else {
          // Handle permission denied
          console.log('Permission denied');
        }
      } else {
        // Proceed with the download on iOS
        downloadFiles();
      }
    };
    

    Step 6: Implement the downloadFiles function to download the PDF files.

    const downloadFiles = async () => {
      const fileUrls = ['url1.pdf', 'url2.pdf', 'url3.pdf']; // Replace with your actual file URLs
      
      const downloadDir = `${RNFS.DownloadDirectoryPath}/pdfs`; // Directory path where PDFs will be downloaded
      
      try {
        // Create the download directory if it doesn't exist
        await RNFS.mkdir(downloadDir);
      
        // Download each PDF file
        for (let i = 0; i < fileUrls.length; i++) {
          const url = fileUrls[i];
          const fileName = `pdf_${i}.pdf`; // Rename the file as per your requirements
      
          const filePath = `${downloadDir}/${fileName}`;
      
          await RNFS.downloadFile({
            fromUrl: url,
            toFile: filePath,
          }).promise;
      
          console.log(`File downloaded successfully: ${filePath}`);
        }
      
        console.log('All files downloaded successfully');
      } catch (error) {
        console.log('Error downloading files:', error);
      }
    };
    

    Step 7: Trigger the download process.
    You can call the downloadPDFs function when a button is pressed or as per your application’s logic.

    <Button title="Download PDFs" onPress={downloadPDFs} />
    

    Make sure to replace the fileUrls array with the actual URLs of the PDF files you want to download. Additionally, you can customize the file names and download directory to fit your requirements.

    Remember to handle error cases, such as when the file URL is invalid or the download fails.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search