在 React Native 中查看 PDF [英] View a PDF in React Native

查看:115
本文介绍了在 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'}}/>
}

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

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 似乎直到 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 文件夹中.这个 SO 答案对实现这一点非常有帮助:
  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:如何将文件从assets"文件夹复制到 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,现在位于 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆