react native 如何查看 pdf文件 ?现在有pdf url,但是浏览器打开该链接会直接下载pdf文件

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 属性可启用内置缓存机制,提升重复加载速度。
‌权限处理‌
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值