【问题标题】:How to view and share a pdf from an URL in a react native app?如何从反应原生应用程序中的 URL 查看和共享 pdf?
【发布时间】:2020-01-22 10:39:22
【问题描述】:

我的 react 本机应用程序中有一个用例,其中我必须从端点加载和显示 pdf,并使用本机共享选项将其与附件共享(到 Gmail 应用程序或 WhatsApp,甚至下载它) (iOS和Android)。

我目前正在使用react-native-pdf 库在应用程序上加载和显示 pdf,它工作正常。问题在于共享选项。我尝试使用 facebook 的 Share API 来实现这一点,但不幸的是,它不符合我的目的,因为 pdf 文件作为链接共享,并且在 Android 中,我必须通过两个 message and pdfUrl 相同的值(至少要获得跨平台的结果相同)。我希望在单击任何共享选项时将 pdf 文件作为附件共享。

下面是我的代码:

class ViewPdfScreen extends Component<Props, {}> {
  render() {

    const pdfUrl = 'http://samples.leanpub.com/thereactnativebook-sample.pdf'

    const source = {
      uri: pdfUrl,
      cache: true,
      expiration: 900, // cache file expired seconds (0 is not expired)
    };

    return (
      <View style={styles.container}>
        <View style={styles.subContainer}>
          <Text>{title}</Text>
          <TouchableOpacity onPress={() => this.sharePdf(title, pdfUrl)}>
            <Image source={shareBtn} />
          </TouchableOpacity>
        </View>
        <View style={styles.pdfContainer}>
          <Pdf
            source={source}
            onLoadComplete={(numberOfPages, filePath) => {
              console.log(`number of pages: ${numberOfPages}`);
            }}
            onPageChanged={(page, numberOfPages) => {
              console.log(`current page: ${page}`);
            }}
            onError={error => {
              console.log(error);
            }}
            onPressLink={uri => {
              console.log(`Link presse: ${uri}`);
            }}
            style={styles.pdf}
          />
        </View>
      </View>
    );
  }

  shareBill = (title: string, billUrl: string) => {
    Share.share(
      {
        message: billUrl,
        url: billUrl,
        title: title,
      },
      {
        // Android only:
        dialogTitle: `Share ${title}`,
        // iOS only:
        excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
      },
    )
      .then(res => console.log(res))
      .catch(error => console.log(error));
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  subContainer: {
    elevation: 4,
    height: 100,
    flexDirection: 'row',
    backgroundColor: colors.orange,
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    padding: 16,
  },
  pdfContainer: {
    flex: 1,
  },
  pdf: {
    flex: 1,
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
});

export default connect()(ViewPdfScreen);

有没有人遇到过类似的情况或对此有任何解决方案?

想要与下面类似的东西(取自谷歌)

【问题讨论】:

    标签: react-native pdf react-native-android share react-native-ios


    【解决方案1】:

    我已经设法使用react-native-share 库解决了这个问题。 但是很遗憾,这在Android上分享有问题,并抛出错误Cannot attach the file

    在这里分享答案,因为我无法在 cmets 部分发布整个代码。

    shareBill = async (title: string) => {
        const billPdfPath = this.props.billPdfDataFetched?.path;
    
        if (!billPdfPath) {
          return;
        }
    
        const newPath = `${RNFetchBlob.fs.dirs.CacheDir}/${title}_bill.pdf`;
    
        await RNFetchBlob.fs.cp(billPdfPath, newPath);
    
        const shareOptions = {
          title: title,
          subject: `${strings('emailSubject')} – ${title}`,
          message: `${title} bill`,
          url: `file://${newPath}`,
          type: 'application/pdf',
          failOnCancel: true,
        };
    
        try {
          await RNShare.open(shareOptions);
        } catch (err) {
          // do something here
        } finally {
          RNFetchBlob.fs.unlink(newPath);
        }
      };
    

    AndroidManifest 文件的权限

    <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission tools:node="remove" android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission tools:node="remove" android:name="android.permission.READ_EXTERNAL_STORAGE" />
    

    如果其他人在与 Android 共享它时遇到类似问题,请帮助我。

    【讨论】:

      【解决方案2】:

      react-native-file-share 是一个提供此功能的库。

      或者

      https://github.com/react-native-community/react-native-share 您也可以尝试 react-native-share。

      Share file directly
      
      When share a local file directly, please follow the format below:
      
      url: "file://<file_path>",
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2018-02-27
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多