好吧,为了子孙后代,我是这样解决这个问题的:
Updated September 13, 2017:
有一个新的NPM模块,使整个过程更加容易.我建议继续使用它,而不是下面我最初的答案:
react-native-pdf
安装后,呈现PDF非常简单:
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
文件夹中.
Original Answer:
iOS
render: function() {
return <WebView source={{uri: 'My.pdf'}}/>
}
诀窍是,你需要在Xcode中的项目中包含My.pdf
,并确保它被添加到你的构建目标中.
仅仅将其复制到React原生项目文件夹是不够的.它必须是Xcode项目本身的一部分.
Android
Android似乎直到5.0(棒棒糖)才提供原生PDF查看器.为了解决这个问题,我必须使用三个关键技术:
- 从我的APK包中取出PDF,并将其存储在我的应用程序的
files
文件夹中.这个答案对实现这一点非常有帮助:
Android: How to copy files from 'assets' folder to sdcard?
我对代码进行了一些调整,使文件不是sdcard
,而是我的应用程序的files
文件夹.以下是我在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
下的assets/pdf
文件夹中
然后,我使用react-native-fs程序包获取PDF的绝对URL,该文件现在位于files
文件夹中:
var RNFS = require('react-native-fs');
var absolutePath = RNFS.DocumentDirectoryPath + '/My.pdf';
所有这些就绪后,我使用react-native-pdf-view来实际加载和显示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} />
}
祝你好运