Rover
Rover

Reputation: 768

React native html to pdf

I am using this code and it works fine in simulator as I am getting a location and can get pdf file from there

async createPDF() {
    let options = {
     html: '<h1>PDF          TEST</h1>',
      fileName: 'test',
     directory: 'Documents',
  };

   let file = await       RNHTMLtoPDF.convert(options)
   //     console.log(file.filePath);
      alert(file.filePath);
 }

But the above code problem in the real iOS mobile as it is saving the pdf file somewhere. I don’t know where but I am not able to see that file in my mobile. So can anyone tell me how can I save my file in the downloads or documents in the iOS . So that I can see the downloaded file.

Upvotes: 4

Views: 2531

Answers (2)

Mahmoud Al-Saleh -
Mahmoud Al-Saleh -

Reputation: 21

You can solve this issue by using base64 as the following:

let options = {
        html:
        `
        <h2 style="text-align: center">${'Some text and dynamic value'}</h2>
        `,
        fileName: 'TestingPDF',
        directory: 'Documents',
        base64: true
      };
    let file = await RNHTMLtoPDF.convert(options);

You shoud use 'react-native-file-access' to copy the file and move it to Downloads directory, so let's install it by: npm i react-native-file-access --save

Lets copy the file to the Downloads directory by the following:

const fileName = 'PMA_CurrentBalanceFile.pdf'; //whatever you want to call your file
const filePath = `${Dirs.DocumentDir}/${fileName}`;
const base64Data = file.base64; //our base64 encode file which done by RNHTMLtoPDF;

Then write the following code to do your job:

if (Platform.OS === 'android') {
        const permissionGranted = await permissionWriteExternalStorage();
        if (permissionGranted) {
           await FileSystem.writeFile(filePath, base64Data, 'base64');
    
           if (!FileSystem.exists(filePath)) return;// check to see if our filePath was created
    
           await FileSystem.cpExternal(filePath, fileName,'downloads');// copies our file to the downloads folder/directory
           // file should now be visible in the downloads folder
           ToastAndroid.show("", "One File Downloaded", ToastAndroid.SHORT);
        }
    
        return;
    }

    if (Platform.OS === 'ios') {
      // IOS version
      await FileSystem.writeFile(filePath, base64Data, 'base64');
      Alert.alert('', 'One File Downloaded');
    }

Upvotes: 0

Rover
Rover

Reputation: 768

Found the answer to convert file in base64 string

Upvotes: 2

Related Questions