从 Expo React Native Project 中的 URL 查看 pdf



我一直在尝试使用 react native 打开一个 pdf 文件,但我尝试的每个库都会产生错误。我尝试了下面的代码:

import React, { Component } from 'react';
import Pdf from 'react-native-pdf';
class OpenBGReport extends Component {
render() {
const source = {uri:'http://samples.leanpub.com/thereactnativebook-sample.pdf',cache:true};
return (
<View style={styles.container}>
<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);
}}
style={styles.pdf}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 25,
},
pdf: {
flex:1,
width:Dimensions.get('window').width,
height:Dimensions.get('window').height,
}
});
export default OpenBGReport;

但是,在安装 react-native-pdf 后,我的项目停止工作并返回:null is not an object (evaluating 'rnfetchblob.documentdir')

在 react native 中从 URL 打开和显示 pdf 的最佳方式是什么?

谢谢

Expo 不支持安装本机模块,react-native-pdf是本机模块。可能的解决方案:

  1. 如果你真的想使用原生模块,你应该使用react-native-cli或弹出世博会项目。您可以在存储库常见问题解答部分 (https://github.com/wonday/react-native-pdf#faq( 中找到更详细的答案。

  2. 您始终可以使用 react-native 的LinkingAPI 在手机浏览器中打开 PDF 文件。

  3. 有一个包可以在世博会项目中显示 PDF 文件 (https://github.com/xcarpentier/rn-pdf-reader-js(。从未使用过该软件包,而且它看起来也很粗略,因为它仅支持Android平台,并且在iOS上,您需要使用WebView来显示pdf。此外,它在 npm 上没有很多下载,项目本身很漂亮过时。

您可以使用 "react-native-webview" (https://github.com/react-native-webview/react-native-webview( 中的<WebView/>我在ios上用expo测试了这个,它的工作!

<WebView 
originWhitelist={['*']} 
source={{uri: uri}}

url可以是本地文件的 Web 链接或路径("file:///..."(

我发现使用 Expo 处理 PDF 文件的最佳方法是使用缓冲区将它们转换为 base64 文件,将它们存储在文件系统中并共享它们:

import { Buffer } from "buffer";
import * as FileSystem from "expo-file-system";
import * as Sharing from "expo-sharing";
res = await // fetch PDF
const buff = Buffer.from(res, "base64");
const base64 = buff.toString("base64");
const fileUri =
FileSystem.documentDirectory + `${encodeURI("name-of-the-pdf")}.pdf`;

await FileSystem.writeAsStringAsync(fileUri, base64, {
encoding: FileSystem.EncodingType.Base64,
});

Sharing.shareAsync(res);

注意:您需要安装bufferexpo-file-systemexpo-sharing

我通过在用户网络浏览器中打开 PDF 解决了这个问题。

import React from 'react';
import { Button, Linking } from 'react-native';
const PermitViewer = ({ downloadUrl }) => {
const handlePress = async () => {
const supported = await Linking.canOpenURL(downloadUrl);
if (supported) {
await Linking.openURL(downloadUrl);
} else {
console.log(`Don't know how to open this URL: ${downloadUrl}`);
}
};
return <Button title="Open PDF" onPress={handlePress} />;
};
export default PermitViewer;

最新更新