Expo开发中rn-pdf-reader-js离线无法加载本地PDF问题求助
解决Expo环境下离线打开本地PDF的问题
问题分析
rn-pdf-reader-js离线时无法加载本地PDF,核心原因大概率是该包依赖的WebView在离线模式下对本地文件路径解析异常,或是未正确适配Expo文件系统的权限规则。
可行解决方案
方案1:改用兼容Expo的react-native-pdf
若之前安装失败,大概率是没选对适配Expo的版本,按以下步骤操作:
- 安装依赖:
expo install react-native-pdf expo-file-system - 调整代码读取本地文件:
Expo文件系统返回的URI无需手动拼接file://,直接使用即可:
该包原生支持本地文件读取,离线状态下可正常运行。import PDF from 'react-native-pdf'; import * as FileSystem from 'expo-file-system'; // 若props.route.params.pdfUri是相对路径,用documentDirectory拼接完整URI const fileUri = FileSystem.documentDirectory + props.route.params.pdfUri; // 若已存储完整URI,直接赋值即可 // const fileUri = props.route.params.pdfUri; return ( <PDF source={{ uri: fileUri }} style={{ flex: 1 }} enablePaging={true} enableAntialiasing={true} /> );
方案2:用expo-web-view直接加载本地PDF
如果上述包仍有问题,可尝试Expo官方WebView方案:
- 确保文件存储在Expo有权限访问的目录(如
DocumentDirectory):import * as FileSystem from 'expo-file-system'; const ensureLocalPath = async (sourceUri) => { // 若源路径不是DocumentDirectory下的,复制一份到该目录 if (!sourceUri.startsWith(FileSystem.documentDirectory)) { const destUri = FileSystem.documentDirectory + 'local_pdf.pdf'; await FileSystem.copyAsync({ from: sourceUri, to: destUri }); return destUri; } return sourceUri; }; - 用WebView加载处理后的路径:
WebView离线时可直接读取本地文件,路径正确即可正常显示PDF。import { WebView } from 'expo-web-view'; const localPdfUri = await ensureLocalPath(props.route.params.pdfUri); return ( <WebView source={{ uri: localPdfUri }} style={{ flex: 1 }} allowsInlineMediaPlayback={true} /> );
方案3:修复路径编码问题
你提供的路径中存在双重编码(如%2540是@的二次编码),会导致路径解析错误,先解码再使用:
const decodedUri = decodeURIComponent(props.route.params.pdfUri); const fileUri = `file://${decodedUri}`;
同时在app.json中配置必要权限:
{ "expo": { "ios": { "infoPlist": { "NSFileProtectionCompleteUntilFirstUserAuthentication": true } }, "android": { "permissions": ["READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"] } } }
注意事项
- 优先使用
expo-file-system提供的documentDirectory/cacheDirectory构建路径,避免手动拼接file://引发权限或解析问题。 - 测试离线模式时,需完全断开设备网络(关闭Wi-Fi和移动数据),排除缓存干扰。
内容的提问来源于stack exchange,提问作者Anuj Todankar
相关产品推荐
相关产品推荐

