如何将 base64 转换为 pdf React-Native

How convert base64 to pdf React-Native

我使用 react-native 创建了一个应用程序,并且有一些来自 base64 的数据 api。我想将 base64 数据转换为 pdf 格式。如果你有什么想法 请帮我。谢谢。

我假设 converting to PDFsaving the base64 format data as PDF in some file 相同。

下面的代码可以帮助你做同样的事情,

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

您可以使用 react-native-pdf 包 (https://www.npmjs.com/package/react-native-pdf)。如果你想在你的应用程序中显示 pdf,这个包会非常有用,因为它支持从 ios 和 android 的 base64 字符串加载 PDF。您可以从您的 base64 数据中指定 pdf 的来源,如他们的示例所示:

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

文档转换:

  pickDocument = async (resolve: (payload: any) => void, reject: (payload: any) => void) => {
    try {
      const result = await DocumentPicker.pick({
        type: [DocumentPicker.types.images, DocumentPicker.types.pdf]
      });
      const fileType = result[0].type;
      const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
      const realURI = Platform.select({ android: result[0].uri, ios: decodeURI(result[0].uri), })
      const b64 = await RNFS.readFile(realURI, "base64")
      const filename = result[0].name.replace(/\s/g, '')
      resolve({ b64, fileType, fileExtension, filename });
    } catch {
      reject(new Error('Action cancelled!'));
    }
  }

图片转换:

  pickImage = (resolve: (payload: any) => void, reject: (payload: any) => void) => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true,
    }).then(async response => {
      const { path: b64Content, mime: fileType, filename:name } = response;
      const b64 = await RNFS.readFile(b64Content, "base64")
      const fileExtension = String(fileType).substr(String(fileType).indexOf('/') + 1);
      const filename = name.replace(/\s/g, '')
      resolve({ b64, fileType, fileExtension, filename });
    }).catch(({message})=>{
      console.log('ERROR',message)
      reject(new Error('Action cancelled!'));
    });
  }