使用文件系统从EXPO应用程序中的BLOB生成pdf时出现问题 [英] Problem to generate pdf from a blob in an expo app using FileSystem

查看:25
本文介绍了使用文件系统从EXPO应用程序中的BLOB生成pdf时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个斑点,然后这样处理它:

const file = response.data;
  var blob = new Blob([file], {
    type: 'application/pdf',
  });

  const fileReaderInstance = new FileReader();
  fileReaderInstance.readAsDataURL(blob);
  fileReaderInstance.onload = async () => {
    const fileUri = `${FileSystem.documentDirectory}file.pdf`;
    await FileSystem.writeAsStringAsync(
      fileUri,
      fileReaderInstance.result.split(',')[1],
      {
        encoding: FileSystem.EncodingType.Base64,
      }
    );
    console.log(fileUri);
    Sharing.shareAsync(fileUri);
  };

但是,当我生成并共享文件时,我无法访问它,如果我获得它的URI并在Web上搜索,它将返回:

推荐答案

我是这样解决问题的:

这是一个函数,它获取要请求的其他数据,执行请求(generate PDF())并处理数据,并通过接收到的blob在Sharing.shareAsync()中共享的(fileReaderInstance.result)上生成缓冲区

  const generatePDF = async () => {
    setAnimating(true);
    const companyReponse = await CompanyService.getCompany();
    const peopleResponse = await PeopleService.getPerson(sale.customerId);

    const company = companyReponse.response.company;
    const people = peopleResponse.response;
    const quote = false;

    const json = await SaleService.generatePDF({
      sale,
      company,
      people,
      quote,
    });

    if (json && json.success) {
      try {
        const fileReaderInstance = new FileReader();
        fileReaderInstance.readAsDataURL(json.data);
        fileReaderInstance.onload = async () => {
          const base64data = fileReaderInstance.result.split(',');
          const pdfBuffer = base64data[1];

          const path = `${FileSystem.documentDirectory}/${sale._id}.pdf`;
          await FileSystem.writeAsStringAsync(`${path}`, pdfBuffer, {
            encoding: FileSystem.EncodingType.Base64,
          });

          await Sharing.shareAsync(path, { mimeType: 'application/pdf' });
        };
      } catch (error) {
        Alert.alert('Erro ao gerar o PDF', error.message);
      }
    }
    setAnimating(false);
  }

这是SaleServicegeneratePDF中的函数,它向API发出请求,并使用axios传递返回pdf blob的参数:

 generatePDF: async ({ sale, company, people, quote }) => {
    const token = await AsyncStorage.getItem('token');
    const body = { sale, company, people, quote };
    try {
      const response = await axios(`${BASE_API}/generate-sale-pdf`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: token,
        },
        responseType: 'blob',
        data: body,
      });

      return {
        success: true,
        data: response.data,
      };
    } catch (err) {
      return err.error;
    }
  },

这篇关于使用文件系统从EXPO应用程序中的BLOB生成pdf时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆