react-native-pdf-view - How to populate pdfView with base64 or blob

Larney picture Larney · Jul 29, 2016 · Viewed 7.6k times · Source

I am using the react-native-pdf-view library and I am having trouble populating the PDFView with a pdf.

How my project works is that I receive a base64 pdf from the server where I then save to the android file system by using the library react-native-fs like so:
(This works fine)

saveFile(filename){

   var base64Image = this.state.imageBase64;

   // create a path you want to write to
   var path = RNFS.DocumentDirectoryPath + '/' + filename;

   // write the file
   RNFS.writeFile(path, base64Image, 'base64').then((success) => {
     console.log('FILE WRITTEN!');
     this.setState(
       {pdf_dirPath: path}
     );
     this._display_fileAttachment()
   })
   .catch((err) => {
     console.log(err.message);
   });
 }

I then try populate the pdf view with this:

<PDFView
  ref={(pdf)=>{this.pdfView = pdf;}}
  src={"path/To/base64/pdf"}
  style={styles.pdf}
 />

Question

Does the react-native-pdf-view have to take a file location or can it take a base64 pdf or a blob.

If it can take a base64 or blob please explain or give sample code on how to do it.
Thanks

Nb: This StackOverflow question is very similar but I need to know how in what form to save or retrieve the base64 from the file system and how to populate the pdf.

Answer

Pedram picture Pedram · Oct 19, 2016

It seems like there's a much easier way to do this. Just tell RNFletchBlob to save directly to disk like so. Note that you'll have to clean up the file later.

RNFetchBlob
  .config({
    // add this option that makes response data to be stored as a file. 
    fileCache : true,
    appendExt : 'pdf'
  })
  .fetch('GET', 'http://www.example.com/file/example.zip', {
    //some headers ..
  })
  .then((res) => {
    // the temp file path 
    this.setState({fileLocation: res.path()});
    console.log('The file saved to ', res.path())
  })

And then later

<PDFView 
  ref={(pdf)=>{this.pdfView = pdf;}}
  path={this.state.fileLocation}
  onLoadComplete = {(pageCount)=>{
    this.pdfView.setNativeProps({
      zoom: 1.0
    });
    console.log("Load Complete. File has " + pageCount + " pages.");
  }}
  style={styles.pdf}/>