React Native 下載並打開pdf文件

本文原創首發於公衆號:ReactNative開發圈,轉載需註明出處。react

使用到的組件

組件安裝

cd到你的項目目錄下,執行下面的命令安裝git

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組件如今只能支持顯示手機本地pdfgithub

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事件獲取到一共有多少頁,而後動態加載後面的幾頁npm

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!react-native

舉手之勞關注個人微信公衆號:ReactNative開發圈微信

相關文章
相關標籤/搜索