React Native 查看 PDF 文件

React Native 查看 PDF 文件
  • 场景需求:
    手机查看 PDF 文件

  • RN 版本:

      "react": "16.6.1",
      "react-native": "0.57.5",
      "react-native-pdf": "^5.0.9",
      "react-native-fetch-blob": "^0.10.8"
    
  • RN 和 插件对应的版本:

react-native-pdf 4.x.x-5.0.x 5.0.9+
React Native 0.47-0.56 ^0.57
  • 用组件:react-native-pdf

  • 安装
    npm install rn-fetch-blob --save
    npm install react-native-pdf --save

    然后 link
    react-native link rn-fetch-blob
    react-native link react-native-pdf

  • 问题 :

    1. 我当时 link 后,Android 版本没 link 上去,所以就手动加了一遍。

    2. Android Studio 运行的时候出现 Warning:Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.是因为 AS 升级到 3.0 官网出现更新了,只需要 compile project(':react-native-pdf') ===> implementation project(':react-native-pdf')


  • 效果图:


    查看 PDF 效果图.gif
  • 完整代码示例:
/**
 * Created by pis on 2018/11/27.
 */
import React, {Component}from 'react';
import {StyleSheet, Dimensions, View, Text} from 'react-native';

import Pdf from 'react-native-pdf';

export default class PDFExample extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page: 0, //当前第几页
            numberOfPages: 0 //pdf 共有几页
        }
    }

    render() {
        const source = {
            uri: 'http://samples.leanpub.com/thereactnativebook-sample.pdf', //pdf 路径
            cache: true, // 是否需要缓存,默认 false
            expiration: 0, // 缓存文件过期秒数,默认 0 为未过期
            method: 'GET', //默认 'GET',请求 url 的方式
            headers: {} // 当 uri 是网址时的请求标头
        };
        //const source = require('./test.pdf');  // ios only
        //const source = {uri:'bundle-assets://test.pdf'};

        //const source = {uri:'file:///sdcard/test.pdf'};
        //const source = {uri:"data:application/pdf;base64,..."};

        return (
            <View style={styles.container}>
                <Pdf
                    source={source}
                    fitWidth={true} //默认 false,若为 true 则不能将 fitWidth = true 与 scale 一起使用
                    fitPolicy={0} // 0:宽度对齐,1:高度对齐,2:适合两者(默认)
                    page={1} //初始化第几页,1 开始
                    scale={1} //页面加载出来 pdf 时的比例
                    minScale={1} //最小模块
                    maxScale={3} //最大模块
                    onLoadComplete={(numberOfPages,filePath,width,height,tableContents)=>{
                        console.log(`number of pages: ${numberOfPages}`); //总页数
                        console.log(`number of filePath: ${filePath}`); //本地返回的路径
                        console.log(`number of width: `,JSON.stringify(width));
                        console.log(`number of height: ${JSON.stringify(height)}`);
                        console.log(`number of tableContents: ${tableContents}`);
                    }}
                    onPageChanged={(page,numberOfPages)=>{
                        this.setState({
                            page:page,
                             numberOfPages:numberOfPages
                        });
                        console.log(`current page: ${page}`); //返回当前页
                        console.log(`current numberOfPages: ${numberOfPages}`); //返回总页面,其实在 onLoadComplete() 可以获取到
                        //所以不建议在这里获取总页数,因为页面滑动就会触发
                    }}
                    onError={(error)=>{
                        console.log(error);
                    }}
                    password='111' //pdf 密码,如果密码错误,会触发 onError() 并显示密码不正确或需要密码
                    spacing={10} // 页面之间的间隔大小,默认为 10
                    horizontal={true} //横向
                    activityIndicator={null}
                    // activityIndi​​catorProps={{backgroundColor:'red'}} 文档里有这个属性,但是我看源码里面没有
                    enablePaging={true} //在屏幕上只能显示一页
                    enableAntialiasing={true} //在低分辨率屏幕上改进渲染,针对 Android 4.4 上可能会出现的一些问题
                    enableRTL={false} //倒序滑动
                    enableAnnotationRendering={true} //启用渲染注视,iOS 仅支持初始设置,不支持实时更改
                    onLoadProgress={(number)=>console.log(number)} //加载时回调,返回加载进度(0-1)
                    onPageSingleTap={()=>{
                        console.log('页面被点击的时候回调')
                    }}
                    onScaleChanged={()=>{
                        console.log('页面缩放的时候回调')
                    }}
                    style={styles.pdf}/>
                <Text>
                    当前第 {this.state.page} 页,共 {this.state.numberOfPages} 页
                </Text>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
        marginTop: 25,
    },
    pdf: {
        flex: 1,
        width: Dimensions.get('window').width,
    }
});

  • debugger 调试模式下 web 的跨域问题 :


    报错
  • 相关解决文章 --- 但是我试过了,没啥卵用

  • 我的解决方法:
    新装了一个 react-native-debugger 调试工具

由于篇幅原因,具体想要知道整个效果图的代码或者有补充地方的可以加技术群:631730313


推荐链接
IT 界寄来的书信系列
IT 界寄来的段子系列
IT 界起来的书籍系列
搞笑我们是用心系列

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容