react- native下载并打开pdf
【代码】react- native下载并打开pdf。
·
首先安装
npm install rn-fetch-blob
代码示例
import { View, Text,Button } from 'react-native'
import React from 'react'
import RNFetchBlob from 'rn-fetch-blob';
export default function main03() {
const downloadAndOpenPDF = async () => {
const { dirs } = RNFetchBlob.fs;
const pdfUrl = 'https://example.com/path/to/pdf.pdf';
let path=`${dirs.DocumentDir}/pdf.pdf`
const exists = await RNFetchBlob.fs.exists(path);//判断文件里是否有该文件路径
if(exists){
//有直接打开
RNFetchBlob.android.actionViewIntent(path, 'application/pdf');
}else{
//没有下载后打开
try {
const response = await RNFetchBlob.config({
fileCache: true,
appendExt: 'pdf',
path: `${dirs.DocumentDir}/pdf.pdf`,
}).fetch('GET', pdfUrl);
if (Platform.OS === 'ios') {
await RNFetchBlob.ios.openDocument(response.path());
} else {
await RNFetchBlob.android.actionViewIntent(response.path(), 'application/pdf');
}
} catch (error) {
console.log('Error:', error);
}
}
};
return (
<View>
<Button title="Download and Open PDF" onPress={downloadAndOpenPDF} />
</View>
)
}
更多推荐
所有评论(0)