如何使用react-native-print打印API返回的Base64字符串?无需react-native-pdf转换
用react-native-print处理Base64内容打印的解决方案
方案一:直接打印Base64编码的PDF
react-native-print原生支持打印Base64格式的PDF,无需额外转换,直接传入base64参数即可。注意要先移除Base64字符串可能带有的data:application/pdf;base64,前缀:
import Print from 'react-native-print'; // 从接口获取的Base64字符串 const rawBase64 = apiResponse; // 清理前缀(如果存在) const pdfBase64 = rawBase64.replace(/^data:application\/pdf;base64,/, ''); // 调用打印方法 Print.print({ base64: pdfBase64, name: '打印文档', // 可选:设置打印文档名称 });
方案二:解码Base64为HTML字符串后打印
如果接口返回的Base64是HTML内容的编码,可通过原生JS方法解码,同时处理UTF-8编码避免中文乱码:
import Print from 'react-native-print'; // 解码Base64到HTML字符串的工具函数 function decodeBase64ToHTML(base64Str) { // 移除可能的data前缀 const cleanBase64 = base64Str.replace(/^data:text\/html;base64,/, ''); // 解码Base64 const decodedBinary = atob(cleanBase64); // 处理UTF-8编码,解决非ASCII字符乱码问题 const uint8Array = new Uint8Array(decodedBinary.length); for (let i = 0; i < decodedBinary.length; i++) { uint8Array[i] = decodedBinary.charCodeAt(i); } return new TextDecoder('utf-8').decode(uint8Array); } // 使用示例 const htmlBase64 = apiResponse; const htmlContent = decodeBase64ToHTML(htmlBase64); // 打印HTML内容 Print.print({ html: htmlContent, name: 'HTML文档', });
关键注意点
- 先确认接口返回的Base64对应的原始内容类型:是PDF就用方案一,是HTML就用方案二
- 必须移除Base64字符串中的
data:前缀,否则react-native-print无法正确解析 - 解码HTML时的UTF-8处理不可省略,否则中文等非ASCII字符会出现乱码
内容的提问来源于stack exchange,提问作者Vin
相关产品推荐
相关产品推荐

