React Native 下载并打开pdf文件

发布时间:2019-06-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React Native 下载并打开pdf文件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文原创首发于公众号ReactNative开发圈,转载需注明出处。

使用到的组件

组件安装

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开发圈

脚本宝典总结

以上是脚本宝典为你收集整理的React Native 下载并打开pdf文件全部内容,希望文章能够帮你解决React Native 下载并打开pdf文件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。