ionic实现在线阅读pdf

最近客户有个需求是在线阅读pdf,项目用的是ionic1,所以就写了个小demo,这里通过两种方式实现.pdf文件是放在自己本机上的tomcat目录下了,把地址改成服务器地址即可

第一种 : 使用内置浏览器在线阅读pdf

代码如下:

// pdf地址
var url = 'http://192.168.202.216:8088/test.pdf';
/**
   * 在浏览器上阅读pdf
   * 使用插件:
   * cordova plugin add cordova-plugin-inappbrowser
   */
    $scope.readPdfInBrowser = function () {
        var defaultOptions = {
            location: 'no',
            clearcache: 'no',
            toolbar: 'yes'
        };
        $cordovaInAppBrowser.open(url, '_blank', defaultOptions)
            .then(function (event) {
                // success
                console.log('success');
                console.log(event);
            })
            .catch(function (event) {
                // error
                console.log('error');
                console.log(event);
            });
    };

个人不推荐这种方式,因为每次都得要从服务器上去读取,并且如果pdf文件如果太大,体验会很差

第二种 : 将服务器上的文件下载到本地,然后再调用本地app打开

代码如下:

// pdf地址
var url = 'http://192.168.202.216:8088/test.pdf';
// 存放下载文件的目录名
    var localDirName = 'Gemkey';
    /**
     * 从服务器上下载pdf
     * 然后再用软件打开
     * 使用插件:
     * cordova plugin add cordova-plugin-file
     * cordova plugin add cordova-plugin-file-transfer
     * cordova plugin add cordova-plugin-file-opener2
     * cordova-plugin-android-permissions
     */
    $scope.readPdfLocal = function () {
        // 获取文件名
        var fileName = url.substr(url.lastIndexOf('/') + 1);
        // 文件最终存储的文件夹路径
        var filePath = '';
        // 获取设备信息,判断是ios或android
        var platform = getPlatform();
        if (platform === 'android') {
            filePath = cordova.file.externalRootDirectory + localDirName + "/";
        } else if (platform === 'iphone') {
            filePath = cordova.file.tempDirectory + localDirName + "/";
        }
        // 检测权限
        checkPermission(platform).then(function () {
            // 如果在ios真机上无法使用,则需要把下面的注释打开,ios 模拟器上测试没问题
            // filePath = filePath.replace("file:///", "/");
            console.log(filePath + fileName);
            // 判断本地是否存在该文件
            $cordovaFile.checkFile(filePath, fileName).then(function (success) {
                console.log(success);
                // 文件存在,直接预览
                openPdf(filePath + fileName);
            }, function (error) {
                // 文件不存在,下载文件
                downloadFile(url, filePath, fileName).then(function (filePathName) {
                    // 打开pdf
                    openPdf(filePathName);
                });
            });
        }, function (error) {
            console.log(error);
        });
    };

    /**
     * 权限检测 android 需要,ios不需要
     * @param platform
     * @returns {*|null|d}
     */
    function checkPermission(platform) {
        var defer = $q.defer();
        if (platform === 'android') {
            // 安卓6.0之后需要显示的去获取权限,否则会出现提示权限不足的问题
            // 安卓需要检测权限
            var permissions = cordova.plugins.permissions;
            // 写入存储设备权限
            permissions.checkPermission(permissions.WRITE_EXTERNAL_STORAGE, function (checkSuccess) {
                console.log(checkSuccess);
                // 没有权限,则申请权限
                if (!checkSuccess.hasPermission) {
                    permissions.requestPermission(permissions.WRITE_EXTERNAL_STORAGE, function (requestSuccess) {
                        console.log(requestSuccess);
                        defer.resolve();
                    }, function (requestError) {
                        console.log(requestError);
                        defer.reject(requestError);
                    });
                } else {
                    defer.resolve();
                }
            }, function (checkError) {
                console.log(checkError);
                defer.reject(checkError);
            });
        } else if (platform === 'iphone') {
            // ios 无需检测权限,在xcode中配置好就行了
            defer.resolve();
        }
        return defer.promise;
    }

    function downloadFile(downloadUrl, filePath, fileName) {
        var fileTransfer = new FileTransfer();
        // 下载文件的url
        downloadUrl = encodeURI(downloadUrl);
        var defer = $q.defer();
        // 检查文件夹是否存在
        checkDir(filePath).then(function (fileEntry) {
            // 文件最终保存路径(带文件名)
            var saveFilePath = encodeURI(fileEntry.nativeURL + fileName);
            console.log(saveFilePath);
            fileTransfer.download(
                downloadUrl,
                saveFilePath,
                function (entry) {
                    // 下载完成
                    console.log('下载完成');
                    console.log(entry);
                    // 将当前文件路径返回
                    defer.resolve(entry.toURL());
                },
                function (error) {
                    // 下载失败
                    console.log('下载失败');
                    console.log(error);
                },
                false,
                {
                    headers: {}
                }
            );
            // 获取下载进度,有需要可以再界面上做进度条
            fileTransfer.onprogress = function (progressEvent) {
                if (progressEvent.lengthComputable) {
                    console.log(progressEvent.loaded / progressEvent.total);
                } else {
                    loadingStatus.increment();
                }
            };

        }, function (error) {
            console.log(error);
        });
        return defer.promise;
    }

    /**
     * 检查文件夹是否存在
     * @param filePath
     * @returns {*|null|d}
     */
    function checkDir(filePath) {
        var defer = $q.defer();
        // filePath = filePath.replace("file:///", "/").replace(localDirName,'');
        filePath = filePath.replace(localDirName, '');
        console.log(filePath);
        $cordovaFile.checkDir(filePath, localDirName)
            .then(function (success) {
                // 文件夹已经存在,无需创建
                console.log(success);
                defer.resolve(success);
            }, function (error) {
                // 文件夹不存在,创建文件夹
                createNewDir(filePath).then(function (fileEntry) {
                    // 创建成功
                    defer.resolve(fileEntry);
                }, function (error) {
                    console.log(error);
                    // 创建失败
                    defer.reject(error);
                });
            });
        return defer.promise;
    }

    /**
     * 创建文件夹
     * @param filePath
     * @returns {*|null|d}
     */
    function createNewDir(filePath) {
        var defer = $q.defer();
        $cordovaFile.createDir(filePath, localDirName, false)
            .then(function (success) {
                console.log(success);
                //该文件夹的路径
                console.log("创建文件夹成功!路径:" + success.nativeURL);

                defer.resolve(success);
            }, function (error) {
                // error
                console.log("创建文件夹失败!");
                defer.reject(error);
            });
        return defer.promise;
    }

    /**
     * 打开本地pdf
     * @param filePath 本地文件路径
     */
    function openPdf(filePath) {
        // 这里只能打开pdf,限制文件类型
        $cordovaFileOpener2.open(
            filePath,
            'application/pdf'
        ).then(function (success) {
            console.log(success);
        }, function (err) {
            console.log(err);
        });
    }

    /**
     * 获取平台信息
     * @returns {string}
     */
    function getPlatform() {
        var ua = navigator.userAgent.toLowerCase();
        var platform = '';
        if (/(micromessenger)/i.test(ua)) {
            platform = 'weixin';
        } else if (/(iphone)/i.test(ua)) {
            // ipad pro上会检测成iPhone,所以再加一个判断,其他pad设备仍旧走下面代码
            if (navigator.platform === 'iPad') {
                platform = 'ipad';
            } else {
                platform = 'iphone';
            }
        } else if (/(ipad)/i.test(ua)) {
            platform = 'ipad';
        } else if (/(android)/i.test(ua)) {
            platform = 'android';
        } else {
            platform = 'web';
        }
        return platform;
    }

安卓的已经通过测试,是可以成功打开,ios在模拟器上测试通过了.如果真机有问题,问题应该就出在文件路径上,只要把对应文件路径地址该对即可.
项目地址:
https://gitee.com/477939838/readPdf

你可能感兴趣的:(ionic实现在线阅读pdf)