本文介绍了在React Native中查看PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以提供在React Native中显示PDF的示例代码吗? iOS和Android.

Can anyone please provide sample code for displaying a PDF in React Native? iOS and Android.

这是我尝试过的:

  render: function() {
    return <WebView
      source={require('./my.pdf')}
      />
  }

^这会导致出现红色的死亡屏幕,并显示无法解析模块"错误.

^ This results in a Red Screen of Death with the "Unable to resolve module" error.

  render: function() {
    return <WebView
      source={{uri: 'my.pdf'}}
      />
  }

^这会在WebView中显示错误加载页面"消息. 在此服务器上找不到请求的URL"

^ This gives an "Error Loading Page" message in the WebView. "The requested URL was not found on this server"

我知道iOS能够在UIWebView中显示PDF.我认为Android可以做到这一点.在如何指定来源方面一定存在我所缺少的东西.

I know iOS is capable of showing a PDF in a UIWebView. I assume Android can do the same. There must be something in how the source is specified that I'm missing.

推荐答案

好,对于子孙后代,这是我解决此问题的方法:

Okay, for future generations, here's how I solved this problem:

更新于2017年9月13日:

有一个新的NPM模块,使整个过程更加容易.我建议继续使用它,而不是下面的原始答案:

There is a new NPM module that makes this entire process much easier. I would suggest using it going forward instead of my original answer below:

react-native-pdf

安装后,渲染PDF就像这样简单:

Once installed, rendering the PDF is as easy as this:

export default class YourClass extends Component {
  constructor(props) {
    super(props);
    this.pdf = null;
  }

  render() {
    let yourPDFURI = {uri:'bundle-assets://pdf/YourPDF.pdf', cache: true};

    return <View style={{flex: 1}}>
      <Pdf ref={(pdf)=>{this.pdf = pdf;}}
        source={yourPDFURI}
        style={{flex: 1}}
        onError={(error)=>{console.log(error);}} />
    </View>
  }
}

只需将您的实际pdf文件放入项目的android/app/src/main/assets/pdf文件夹中即可.

Just put your actual pdf in the android/app/src/main/assets/pdf folder of your project.

原始答案:

iOS

render: function() {
  return <WebView source={{uri: 'My.pdf'}}/>
}

诀窍在于,您需要将My.pdf包含在Xcode项目中,并确保将其添加到构建目标中.

The trick is that you need to include My.pdf into your project in Xcode and make sure it's added to your build target.

仅将其复制到您的React Native项目文件夹中是不够的.它必须是Xcode项目本身的一部分.

Just copying it into your React Native project folder wasn't enough. It had to be part of the Xcode project itself.

Android

Android直到5.0(Lollipop)才提供本机PDF查看器.为了解决这个问题,我不得不利用三种关键技术:

It appears that Android did not provide a native PDF viewer until 5.0 (Lollipop). To get around this, I've had to make use of three key techniques:

  1. 从我的APK包中提取PDF并将其存储在我的应用程序的files文件夹中.这样的答案对完成此任务非常有帮助:
  1. Pull the PDF out of my APK bundle and store it in the files folder for my app. This SO answer was very helpful in accomplishing this:

Android:如何将文件从资产"文件夹复制到sdcard?

我稍微调整了代码,以使文件不会进入sdcard,而是进入应用程序的files文件夹.这是我添加到MainActivity.java

I tweaked the code a bit so that the file wasn't going to an sdcard but to my app's files folder. Here's what I added to my MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  AssetManager assetManager = getAssets();
  String[] files = null;

  try {
      files = assetManager.list("pdf");
  } catch (IOException e) {
      Log.e("tag", "Failed to get asset file list.", e);
  }

  if (files != null) for (String filename : files) {
      InputStream in = null;
      OutputStream out = null;

      try {
        in = assetManager.open("pdf/" + filename);

        File outFile = new File(getFilesDir(), filename);
        out = new FileOutputStream(outFile);
        copyFile(in, out);
        Log.e("tag", "Copy was a success: " + outFile.getPath());
      } catch(IOException e) {
        Log.e("tag", "Failed to copy asset file: " + "pdf/" + filename, e);
      }
      finally {
          if (in != null) {
              try {
                  in.close();
              } catch (IOException e) {
                  // NOOP
              }
          }
          if (out != null) {
              try {
                  out.close();
              } catch (IOException e) {
                  // NOOP
              }
          }
      }
  }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

我还确保我的PDF位于android/app/src/main

I also made sure my PDF is in the assets/pdf folder under android/app/src/main

  1. 然后,我使用 react-native-fs 包来获取我的PDF的绝对URL,该URL现在位于files文件夹中:

  1. I then utilized the react-native-fs package to get the absolute URL to my PDF, which is now in the files folder:

var RNFS = require('react-native-fs');
var absolutePath = RNFS.DocumentDirectoryPath + '/My.pdf';

  • 所有这些都准备就绪,我使用了反应-native- pdf-view 实际加载并显示PDF:

  • With all of this in place, I used react-native-pdf-view to actually load and display the PDF:

    import PDFView from 'react-native-pdf-view';
    
    render: function() {
      var absolutePath = RNFS.DocumentDirectoryPath + '/My.pdf';
    
      return <PDFView
        ref={(pdf)=>{this.pdfView = pdf;}}
        src={absolutePath}
        style={ActharStyles.fullCover} />
    }
    

  • 祝你好运!

    这篇关于在React Native中查看PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-24 17:50