react-native-pdf-view - 如何使用base64或blob填充pdfView

时间:2016-07-29 12:21:07

标签: pdf react-native pdf-viewer react-native-android react-native-fs

我正在使用react-native-pdf-view库,而我无法使用pdf填充PDFView。

我的项目是如何工作的,我从服务器收到base64 pdf,然后使用库react-native-fs保存到android文件系统,如下所示:
(这很好用)

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);
   });
 }

然后我尝试用这个填充pdf视图:

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

问题

react-native-pdf-view是否必须采用文件位置,或者是否需要base64 pdf或blob。

如果可以使用base64或blob,请解释或提供有关如何操作的示例代码 感谢

Nb:This StackOverflow question非常相似,但我需要知道如何从文件系统中保存或检索base64以及如何填充pdf。

2 个答案:

答案 0 :(得分:2)

对于有同样问题的人,这是解决方案。

解决方案

react-nativive-pdf-view必须获取pdf_base64的文件路径。

首先,我使用react-native-fetch-blob从服务器请求pdf base64。(因为RN fetch API还不支持BLOB)。

此外,我发现react-native-fetch-blob还有一个FileSystem API,与“反应原生”fs相比,它更好地记录并更易于理解。图书馆。 (Check out its FileSystem API documentation

接收base64 pdf并将其保存到文件路径:

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)
   });
}

我错误的是将pdf_base64Str保存到文件位置,而不是像上面的示例中那样。我是这样保存的:

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

这是错误的。

使用文件路径填充PDF视图:

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

答案 1 :(得分:2)

似乎有一种更简单的方法可以做到这一点。告诉RNFletchBlob直接保存到磁盘就像这样。请注意,您以后必须清理该文件。

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())
  })

然后是

<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}/>