React Native应用如何生成PDF?expo-print调用printToFileAsync报错如何解决
问题根源
报错的核心原因有2个:
expo-print的导入方式错误,当前版本的expo-print不存在命名导出的Print对象,错误的解构导入导致Print为undefined,调用方法时自然抛出异常- 异步函数
createPDF没有做异常捕获,一旦执行出错就会触发unhandled promise rejection提示
修复步骤
- 先确认已正确安装
expo-print依赖:
npx expo install expo-print
- 修改导入语句,使用正确的导入规则
- 给异步函数加上
try/catch捕获运行时错误 - 如果你是在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
相关产品推荐
相关产品推荐

