好,爲子孫後代,這裏就是我解決了這個問題:
更新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
我聽到你的聲音。如果你這樣做,也許考慮對上述包作出貢獻,以便下一個人(也許我!!)不必:) –