前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React Native下载打开pdf文件

React Native下载打开pdf文件

作者头像
forrest23
发布2018-08-03 15:34:43
2.9K0
发布2018-08-03 15:34:43
举报

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

使用到的组件

  • react-native-fs 文件下载组件 GitHub - johanneslumpe/react-native-fs: Native filesystem access for react-native
  • react-native-pdf-view pdf显示组件 GitHub - cnjon/react-native-pdf-view: React Native PDF View


组件安装

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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事件获取到一共有多少页,然后动态加载后面的几页

代码语言:javascript
复制
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地址:https://github.com/forrest23/reacttest

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-11-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 ReactNative开发圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用到的组件
  • 组件安装
  • 示例代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档