You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-native-view-pdf无法加载本地PDF文件的问题排查

问题原因及解决方案

你出错的核心原因是:直接用项目开发时的相对路径指向assets目录下的PDF,并设置resourceType='file'是无效的。resourceType='file'要求的是设备本地文件系统的绝对路径,而assets目录下的文件在React Native打包后,不会以你写的相对路径存在于设备中,所以组件找不到文件报错。

下面是几种可行的解决方案:

方案一:将PDF放到原生资源目录直接访问

安卓端操作

  1. 把new.pdf复制到项目的android/app/src/main/assets目录(如果没有assets文件夹就新建一个)
  2. 修改代码如下:
<PDFView
  style={{flex: 1}}
  onError={error => console.log('onError', error)}
  onLoad={() => console.log('PDF rendered from file')}
  resource={'file:///android_asset/new.pdf'}
  resourceType={'url'} // 这里用url类型,因为安卓asset的URI格式是file://开头
/>

iOS端操作

  1. 把new.pdf复制到项目的ios/你的项目名称/Resources目录
  2. 修改代码如下:
<PDFView
  style={{flex: 1}}
  onError={error => console.log('onError', error)}
  onLoad={() => console.log('PDF rendered from file')}
  resource={'new.pdf'}
  resourceType={'file'}
/>

方案二:用react-native-fs复制assets文件到设备目录后加载

  1. 先安装依赖:
npm install react-native-fs --save
# 或者用yarn:yarn add react-native-fs
  1. 编写代码复制并加载:
import React, { useState, useEffect } from 'react';
import PDFView from 'react-native-view-pdf';
import RNFS from 'react-native-fs';

export default function PDFScreen() {
  const [pdfPath, setPdfPath] = useState(null);

  useEffect(() => {
    const loadLocalPDF = async () => {
      // 获取assets中PDF的资源路径
      const assetUri = require('../../assets/pdf/new.pdf').uri;
      // 定义目标路径(设备文档目录)
      const destPath = `${RNFS.DocumentDirectoryPath}/new.pdf`;
      
      try {
        // 复制文件到设备目录
        await RNFS.copyFileAssets(assetUri, destPath);
        setPdfPath(destPath);
      } catch (err) {
        console.log('复制文件出错:', err);
      }
    };

    loadLocalPDF();
  }, []);

  if (!pdfPath) {
    return null; // 或者显示加载中组件
  }

  return (
    <PDFView
      style={{flex: 1}}
      onError={error => console.log('onError', error)}
      onLoad={() => console.log('PDF rendered from file')}
      resource={pdfPath}
      resourceType={'file'}
    />
  );
}

方案三:将PDF转为base64加载

  1. 直接导入PDF文件获取base64字符串(需确保项目打包配置支持导入PDF为base64格式)
  2. 修改代码:
import PDFView from 'react-native-view-pdf';

// 导入PDF并获取base64内容
const pdfBase64 = require('../../assets/pdf/new.pdf').default;

export default function PDFScreen() {
  return (
    <PDFView
      style={{flex: 1}}
      onError={error => console.log('onError', error)}
      onLoad={() => console.log('PDF rendered from file')}
      resource={pdfBase64}
      resourceType={'base64'}
    />
  );
}

内容的提问来源于stack exchange,提问作者pratteek shaurya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 10:07:44