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

React Native+Expo环境下,如何用expo-print将HTML转PDF并本地下载?

在Expo中实现HTML转PDF并下载到本地设备

要实现PDF下载到用户本地设备,你需要结合expo-file-system处理文件操作、expo-media-library获取存储权限并将文件保存到系统存储目录。以下是完整实现步骤:

1. 安装所需依赖

expo install expo-print expo-file-system expo-media-library

2. 配置权限

在app.json中添加权限声明,确保应用能访问设备存储:

{
  "expo": {
    "ios": {
      "infoPlist": {
        "NSPhotoLibraryAddUsageDescription": "需要访问相册以保存PDF文件"
      }
    },
    "android": {
      "permissions": ["WRITE_EXTERNAL_STORAGE"],
      "package": "com.your.app.package"
    }
  }
}

3. 修改代码实现下载功能

替换原有仅支持分享的代码,改为以下逻辑:

import * as Print from 'expo-print';
import * as FileSystem from 'expo-file-system';
import * as MediaLibrary from 'expo-media-library';
import { Alert } from 'react-native';

const downloadFromUrl = async (activityLogs) => {
  try {
    // 生成HTML内容
    const htmlContent = createHtmlContent(activityLogs);

    // 将HTML转为PDF文件
    const pdfFile = await Print.printToFileAsync({
      html: htmlContent,
      base64: false // 无需base64,直接处理文件URI即可
    });

    // 请求存储权限
    const { status } = await MediaLibrary.requestPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('权限不足', '需要允许访问存储才能保存PDF');
      return;
    }

    // 将PDF保存到系统相册
    await MediaLibrary.saveToLibraryAsync(pdfFile.uri);
    Alert.alert('保存成功', 'PDF已保存到相册');
  } catch (error) {
    console.error('下载PDF失败:', error);
    Alert.alert('错误', '保存PDF时出现问题,请重试');
  }
};

可选:保存到自定义目录

如果不想保存到相册,可将文件复制到应用文档目录,用户可通过文件管理器访问:

// 替换上述代码中MediaLibrary.saveToLibraryAsync的逻辑
const customFilePath = `${FileSystem.documentDirectory}activity-logs.pdf`;
await FileSystem.copyAsync({
  from: pdfFile.uri,
  to: customFilePath
});
Alert.alert('保存成功', `文件路径:${customFilePath}`);

内容的提问来源于stack exchange,提问作者Build Though

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:13:08