Is it possible to download PDF and save to mobile filesystem in React Native using Expo?

Viewed 2101

I'm using Expo and React Native, but can't download PDF file and save it to filesystem. I don't find any examples and exact answer.

Is it possible to download PDF and then save it to docs?

1 Answers

Your goal can be achieved using expo-media-library and expo-file-system. Have a try this.

import React from 'react';
import { View, Button } from 'react-native';
import * as FileSystem from 'expo-file-system';
import * as Permissions from 'expo-permissions';
import * as MediaLibrary from 'expo-media-library';

class TestClass extends React.Component {
    constructor(props) {
        super(props)
    }

    async saveFile() {
        const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
        if (status === "granted") {

            FileSystem.downloadAsync("http://www.pdf995.com/samples/pdf.pdf", FileSystem.documentDirectory + 'test.pdf')
            .then( async ({uri}) => {
                await MediaLibrary.createAssetAsync(uri)
            }).catch((err) => {
               console.log(err)
            })
        }
    }
    render(){
        return(
            <View style={{flex : 1, justifyContent : 'center', alignItems: 'center'}}>
                <Button title="Create PDF" onPress={() => this.saveFile()}/>
            </View>
        )
    }
    
}
export default TestClass
Related