Copy Code
yarn add react-native-pdf
二、核心代码实现
javascript
Copy Code
import React, { useState } from 'react';
import { View, ActivityIndicator } from 'react-native';
import Pdf from 'react-native-pdf';
import ReactNativeBlobUtil from 'react-native-blob-util';
const PDFViewer = ({ pdfUrl }) => {
const [localPath, setLocalPath] = useState(null);
const [loading, setLoading] = useState(false);
// 下载并缓存 PDF
const downloadPDF = async () => {
setLoading(true);
try {
const { dirs } = ReactNativeBlobUtil.fs;
const filePath = `${dirs.DocumentDir}/temp_${Date.now()}.pdf`;
// 下载文件
const config = ReactNativeBlobUtil.config({ fileCache: true, path: filePath });
const response = await config.fetch('GET', pdfUrl);
// 更新本地路径
setLocalPath(response.path());
} catch (error) {
console.error('下载失败:', error);
} finally {
setLoading(false);
}
};
// 首次加载触发下载
React.useEffect(() => {
downloadPDF();
}, []);
return (
<View style={{ flex: 1 }}>
{loading ? (
<ActivityIndicator size="large" />
) : localPath ? (
<Pdf
source={{ uri: localPath, cache: true }}
style={{ flex: 1 }}
onError={(error) => console.log('渲染失败:', error)}
/>
) : null}
</View>
);
};
export default PDFViewer;
三、关键点说明
文件缓存逻辑
通过 react-native-blob-util 将远程 PDF 下载到应用沙盒目录(如 DocumentDir),避免浏览器拦截下载行为28。
使用唯一文件名(如 temp_${Date.now()}.pdf)防止缓存冲突。
PDF 渲染优化
react-native-pdf 支持加载本地文件路径,通过 source.uri 直接渲染本地文件78。
添加 cache: true 属性可启用内置缓存机制,提升重复加载速度。
权限处理