如何将Base64转换为PDF React-Native

3

我使用react-native创建了一个应用程序,并从API获取了一些base64数据。 我想将base64数据转换为pdf格式。 如果您有任何想法,请帮助我。 谢谢。

2个回答

5
您可以使用 react-native-pdf 包 (https://www.npmjs.com/package/react-native-pdf)。如果您想在应用程序中显示 PDF,这个包将非常有帮助,因为它支持从 base64 字符串加载 PDF 文件,适用于 iOS 和 Android。您可以像他们的示例一样指定来自您的 base64 数据的 PDF 源:

{uri:"data:application/pdf;base64,JVBERi0xLjcKJc..."}


我该如何从fetch响应中获取base64字符串? - pokumars
FYI:不支持 Expo。 - ikiK
@ikiK 请查看 https://github.com/expo/examples/tree/master/with-pdf - Ho Chung Wong
我有很多base64图片,你怎么处理? - gshoanganh

1
我假设,“转换为PDF”是指“将base64格式的数据保存为PDF文件”。以下代码可以帮助你实现这一点。
let fPath = Platform.select({
   ios: fs.dirs.DocumentDir,
   android: fs.dirs.DownloadDir,
});

fPath = `${fPath}/pdfFileName.pdf`;

if (Platform.OS === PlatformTypes.IOS) {
    await fs.createFile(fPath, base64Data, "base64");
} else {
    await fs.writeFile(fPath, base64Data, "base64");
}
// RNFetchBlob can be used to open the file

fs 依赖从哪里来的? - Martinocom
1
以前我们有一个叫做 react-native-fs 的东西,你可以检查一下它是否仍然存在。 - senthil balaji
1
你可以查看这个链接 - https://www.npmjs.com/package/react-native-fs - senthil balaji
1
我使用了这个导入语句:import RNFS from 'react-native-fs';,在此之后,我可以直接使用 await RNFS.writeFile(path, fileContent, 'base64');。提醒:在iOS和Android上设置权限!对于“仅预览,稍后复制”的方法,可以使用 RNFS.DocumentDirectoryPath。要将文件复制到下载文件夹中,我使用了 import { FileSystem } from 'react-native-file-access'; 中的 await FileSystem.cpExternal(fullPath, fileName, 'downloads');。为了预览PDF,我使用了 import FileViewer from 'react-native-file-viewer'; 中的 await FileViewer.open(fullPath) - Martinocom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接