好,为子孙后代,这里就是我解决了这个问题:
更新2017年9月13日:
有一个新的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
您项目的文件夹。
原来的答案:
的iOS
render: function() {
return <WebView source={{uri: 'My.pdf'}}/>
}
的技巧是,你需要包括My.pdf
到Xcode中的项目,并确保它添加到您的构建目标。
仅将其复制到您的React Native项目文件夹中是不够的。它必须是Xcode项目本身的一部分。
的Android
看来,Android的没有提供原生PDF浏览器,直到5.0(棒棒堂)。为了解决这个问题,我不得不使用三个关键技术:
- 的PDF拉出我的APK包并将其存放在我的应用程序的文件夹
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);
}
}
我也android/app/src/main
下完全相信我的PDF是在
assets/pdf
文件夹
我则利用react-native-fs包来获得绝对URL到我的PDF,这是现在在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} />
}
祝你好运!
我认为你已经发现了这一点,这是一个只有android的解决方案https://github.com/cnjon/react-native-pdf-view,尽管它看起来像是在iOS上工作。他们已经桥接本地解决方案。如果您花时间深入了解,您可能会获得洞察力。我很想知道是否可以将pdf本地加载到webview中。 –
@ChrisGeirman我见过。我是一位本地iOS开发者,所以我可以在那里搭建一座桥梁。我知道我可以以这种方式工作。只是希望我不需要跳过那些篮球。 – Axeva
我听到你的声音。如果你这样做,也许考虑对上述包作出贡献,以便下一个人(也许我!!)不必:) –