React Native下載開啟pdf檔案
使用到的元件
-
react-native-fs 檔案下載元件 GitHub - johanneslumpe/react-native-fs: Native filesystem access for react-native
-
react-native-pdf-view pdf顯示元件 GitHub - cnjon/react-native-pdf-view: React Native PDF View
元件安裝
cd到你的專案目錄下,執行下面的命令安裝
npm install react-native-fs --save react-native link react-native-fs npm i react-native-pdf-view --save react-native link react-native-pdf-view
示例程式碼
首先下載pdf檔案到本地,react-native-pdf-view元件現在只能支援顯示手機本地pdf。
varDownloadFileOptions={
fromUrl: pdfDownloadURL,// URL to download file from
toFile:this.pdfPath // Local filesystem path to save the file to
}
var result = RNFS.downloadFile(DownloadFileOptions);
console.log
var _this =this;
result.then(function(val){
_this.setState({
isPdfDownload:true,
});
},function(val){
console.log('Error Result:'+ JSON.stringify(val));
}
).catch(function(error){
console.log(error.message);
});
顯示pdf,因為可能有多頁,所以在開啟第一頁後,利用onLoadComplete事件獲取到一共有多少頁,然後動態載入後面的幾頁
render(){
if(!this.state.isPdfDownload){
return(
<View style={styles.container}>
<Text>Downloading</Text>
</View>
);
}
var pages =[];
for(var i =2; i <this.state.pageCount +1; i++){
pages.push(
<PDFViewref={(pdf)=>{this.pdfView = pdf;}}
key={"sop"+ i}
path={this.pdfPath}
pageNumber={i}
style={styles.pdf}/>
);
}
return(
<ScrollView style={styles.pdfcontainer}>
<PDFViewref={(pdf)=>{this.pdfView = pdf;}}
key="sop"
path={this.pdfPath}
pageNumber={1}
onLoadComplete={(pageCount)=>{
this.setState({ pageCount: pageCount });
console.log(`pdf共有: ${pageCount}頁`);
}}
style={styles.pdf}/>
{pages.map((elem, index)=>{
return elem;
})}
</ScrollView>
)
}
完整程式碼: GitHub地址:https://github.com/forrest23/reacttest