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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容