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

React Native FS iOS端文件移动失效,PDF下载保存异常求助

iOS端PDF生成/保存失败排查与修复

针对你遇到的Android正常、iOS无法工作的问题,结合代码分析出几个核心问题,对应修复方案如下:

1. Base64图片格式不兼容iOS WebView

RNHTMLtoPDF依赖iOS的WebView渲染HTML,纯Base64字符串作为img的src无法被识别,必须添加data:image/[格式];base64,前缀。

修复代码:

const pdfContent = imageArray
  .map((base64Image: any) => `<img src="data:image/jpeg;base64,${base64Image}" style="width:100%;height:auto;" />`)
  .join('');

(注:如果图片是PNG格式,替换为data:image/png;base64,)

2. iOS未处理文件移动逻辑

当前代码仅在Android执行RNFS.moveFile,但iOS端RNHTMLtoPDF生成的PDF默认存放在临时目录,不会自动保留到Documents目录,需要补充iOS的文件移动逻辑。

修复代码:

try {
  // Android和iOS都执行文件移动
  await RNFS.moveFile(pdfFile.filePath, downloadsPath);
  
  // iOS额外处理:让用户能访问到文件(可选,通过分享弹窗让用户选择保存位置)
  if (Platform.OS === 'ios') {
    Share.share({
      url: `file://${downloadsPath}`,
      title: '保存PDF文件'
    });
  }
  
  setDownloadingToDevice(false);
} catch (error) {
  // 打印详细错误信息,方便排查
  console.error('PDF保存失败:', error.message, error.stack);
  setDownloadingToDevice(false);
}

3. RNHTMLtoPDF的iOS配置检查

确认iOS端依赖是否正确集成:

  • 检查Podfile中是否包含RNHTMLtoPDF依赖,执行过pod install
  • 确认info.plist中添加了必要的权限描述(如需要保存到相册,添加NSPhotoLibraryAddUsageDescription;如需访问文件,添加NSDocumentsFolderUsageDescription)

4. HTML样式兼容性优化

iOS WebView对HTML样式的容错性更低,建议补充基础样式避免渲染异常:

const htmlContent = `
  <!doctype html>
  <html>
    <head>
      <style>
        body { margin: 0; padding: 10px; }
        .header { text-align: center; margin-bottom: 20px; }
        .pdf-content img { display: block; margin: 0 auto 10px; max-width: 100%; }
      </style>
    </head>
    <body>
      <div class="header">
        <h3>${
          toggleCheckBox
            ? t('10017') && t('10017') !== '10017'
              ? t('10017') + ': ' + voucher.archiveNo
              : 'Archive number: ' + voucher.archiveNo
            : ''
        }</h3>
      </div>
      <div class="pdf-content">
        ${pdfContent}
      </div>
    </body>
  </html>
`;

额外排查点

  • 打印pdfFile.filePath和downloadsPath,确认iOS端路径是否正确
  • 检查RNFS的iOS权限配置,确保NSFileProviderDomainUsageDescription已添加(如需访问外部存储)

内容的提问来源于stack exchange,提问作者Ruchira Swarnapriya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:58:55