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

React Native应用如何生成PDF?expo-print调用printToFileAsync报错如何解决

问题根源

报错的核心原因有2个:

  • expo-print的导入方式错误,当前版本的expo-print不存在命名导出的Print对象,错误的解构导入导致Print为undefined,调用方法时自然抛出异常
  • 异步函数createPDF没有做异常捕获,一旦执行出错就会触发unhandled promise rejection提示

修复步骤

  1. 先确认已正确安装expo-print依赖:
npx expo install expo-print
  1. 修改导入语句,使用正确的导入规则
  2. 给异步函数加上try/catch捕获运行时错误
  3. 如果你是在Expo Go之外的原生构建环境运行,需要重新构建安装包让依赖生效

修复后完整可运行代码

import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight } from 'react-native';
// 修正导入方式,使用全量导入
import * as Print from 'expo-print';

export default function Pdf() {
  async function createPDF() {
    // 新增异常捕获
    try {
      const filePath = await Print.printToFileAsync({
        html: "<h1>PDF TEST</h1>",
        width : 612,
        height : 792,
        base64 : false
      });
      alert('PDF Generated: ' + filePath.uri);
    } catch (err) {
      console.error('生成PDF失败: ', err);
      alert('生成PDF失败: ' + err.message);
    }
  }

  return(
    <View>
      <TouchableHighlight onPress={createPDF} style={styles.Main}>
        <Text>Create PDF</Text>
      </TouchableHighlight>
    </View>
  )
}

const styles = StyleSheet.create({
  Main : { marginTop : 100 }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:51:02