React Native 下载并打开pdf文件

作者: forrest23 | 来源:发表于2016-12-13 09:37 被阅读3566次

使用到的组件


组件安装

cd到你的项目目录下,执行下面的命令安装

npm install react-native-fs --save
react-native link react-native-fs

npm i react-native-pdf-view --save
react-native link react-native-pdf-view

示例代码

首先下载pdf文件到本地,react-native-pdf-view组件现在只能支持显示手机本地pdf

   var DownloadFileOptions = {
            fromUrl: pdfDownloadURL,          // URL to download file from
            toFile: this.pdfPath         // Local filesystem path to save the file to
        }
        var result = RNFS.downloadFile(DownloadFileOptions);
        console.log(result);

        var _this = this;
        result.then(function (val) {
            _this.setState({
                isPdfDownload: true,
            });
        }, function (val) {
            console.log('Error Result:' + JSON.stringify(val));
        }
        ).catch(function (error) {
            console.log(error.message);
        });

显示pdf,因为可能有多页,所以在打开第一页后,利用onLoadComplete事件获取到一共有多少页,然后动态加载后面的几页

render() {
        if (!this.state.isPdfDownload) {
            return (
                <View style={styles.container}>
                    <Text>Downloading</Text>
                </View>
            );
        }

        var pages = [];
        for (var i = 2; i < this.state.pageCount + 1; i++) {
            pages.push(
                <PDFView ref={(pdf) => { this.pdfView = pdf; } }
                    key={"sop" + i}
                    path={this.pdfPath}
                    pageNumber={i}
                    style={styles.pdf} />
            );
        }

        return (
            <ScrollView style={styles.pdfcontainer}>
                <PDFView ref={(pdf) => { this.pdfView = pdf; } }
                    key="sop"
                    path={this.pdfPath}
                    pageNumber={1}
                    onLoadComplete={(pageCount) => {
                        this.setState({ pageCount: pageCount });
                        console.log(`pdf共有: ${pageCount}页`);
                    } }
                    style={styles.pdf} />

                {pages.map((elem, index) => {
                    return elem;
                })}
            </ScrollView>
        )
    }

完整代码GitHub - forrest23/reacttest: Another React Native Project!

传送门

微信公众号:ReactNative开发圈

image.png

相关文章

网友评论

  • 爱情的逃兵:请问一下,这个组件可以打开excel和word文档吗
  • JsLin_:0.42版本Android报错 erroy while updating property 'path' of view managed by :"RCTPDFViewAndroid"
  • 8a1d14916178:只能打开pdf文件吗?
  • 9bb759d7d685:为什么我在安卓手机使用PDFView展示pdf 在放大的时候会出现字体模糊的现象

本文标题:React Native 下载并打开pdf文件

本文链接:https://www.haomeiwen.com/subject/yovvmttx.html