React Native Tutorial to Save PDF Document to Android/IOS File System and View PDF in PDF Viewer Full Project For Beginners

 

Solution

react-nativive-pdf-view must take the file path to the pdf_base64.

Firstly, I used the react-native-fetch-blob to request the pdf base64 from the server.(Because RN fetch API does not yet support BLOBs).

Also I discovered that react-native-fetch-blob also has a FileSystem API which is way better documented and easier to understand than the ‘react-native-fs’ library. (Check out its FileSystem API documentation)

Receiving base64 pdf and saving it to a file path:

var RNFetchBlob = require('react-native-fetch-blob').default;

const DocumentDir = RNFetchBlob.fs.dirs.DocumentDir;

getPdfFromServer: function(uri_attachment, filename_attachment) {
   return new Promise((RESOLVE, REJECT) => {

      // Fetch attachment
      RNFetchBlob.fetch('GET', config.apiRoot+'/app/'+uri_attachment)
      .then((res) => {

          let base64Str = res.data;
          let pdfLocation = DocumentDir + '/' + filename_attachment;

          RNFetchBlob.fs.writeFile(pdfLocation, pdf_base64Str, 'base64');
          RESOLVE(pdfLocation);
      })
   }).catch((error) => {
       // error handling
       console.log("Error", error)
   });
}

What I was doing wrong was instead of saving the pdf_base64Str to the file location like I did in the example above. I was saving it like this:

var pdf_base64= 'data:application/pdf;base64,'+pdf_base64Str;

which was wrong.

Populate PDF view with file path:

<PDFView
    ref={(pdf)=>{this.pdfView = pdf;}}
    src={pdfLocation}
    style={styles.pdf}
/>

Leave a Reply