ionic實(shí)現(xiàn)在線閱讀pdf

最近客戶有個需求是在線閱讀pdf,項(xiàng)目用的是ionic1,所以就寫了個小demo,這里通過兩種方式實(shí)現(xiàn).pdf文件是放在自己本機(jī)上的tomcat目錄下了,把地址改成服務(wù)器地址即可

第一種 : 使用內(nèi)置瀏覽器在線閱讀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);
            });
    };

個人不推薦這種方式,因?yàn)槊看味嫉靡獜姆?wù)器上去讀取,并且如果pdf文件如果太大,體驗(yàn)會很差

第二種 : 將服務(wù)器上的文件下載到本地,然后再調(diào)用本地app打開

代碼如下:

// pdf地址
var url = 'http://192.168.202.216:8088/test.pdf';
// 存放下載文件的目錄名
    var localDirName = 'Gemkey';
    /**
     * 從服務(wù)器上下載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 = '';
        // 獲取設(shè)備信息,判斷是ios或android
        var platform = getPlatform();
        if (platform === 'android') {
            filePath = cordova.file.externalRootDirectory + localDirName + "/";
        } else if (platform === 'iphone') {
            filePath = cordova.file.tempDirectory + localDirName + "/";
        }
        // 檢測權(quán)限
        checkPermission(platform).then(function () {
            // 如果在ios真機(jī)上無法使用,則需要把下面的注釋打開,ios 模擬器上測試沒問題
            // filePath = filePath.replace("file:///", "/");
            console.log(filePath + fileName);
            // 判斷本地是否存在該文件
            $cordovaFile.checkFile(filePath, fileName).then(function (success) {
                console.log(success);
                // 文件存在,直接預(yù)覽
                openPdf(filePath + fileName);
            }, function (error) {
                // 文件不存在,下載文件
                downloadFile(url, filePath, fileName).then(function (filePathName) {
                    // 打開pdf
                    openPdf(filePathName);
                });
            });
        }, function (error) {
            console.log(error);
        });
    };

    /**
     * 權(quán)限檢測 android 需要,ios不需要
     * @param platform
     * @returns {*|null|d}
     */
    function checkPermission(platform) {
        var defer = $q.defer();
        if (platform === 'android') {
            // 安卓6.0之后需要顯示的去獲取權(quán)限,否則會出現(xiàn)提示權(quán)限不足的問題
            // 安卓需要檢測權(quán)限
            var permissions = cordova.plugins.permissions;
            // 寫入存儲設(shè)備權(quán)限
            permissions.checkPermission(permissions.WRITE_EXTERNAL_STORAGE, function (checkSuccess) {
                console.log(checkSuccess);
                // 沒有權(quán)限,則申請權(quán)限
                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 無需檢測權(quán)限,在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);
                    // 將當(dāng)前文件路徑返回
                    defer.resolve(entry.toURL());
                },
                function (error) {
                    // 下載失敗
                    console.log('下載失敗');
                    console.log(error);
                },
                false,
                {
                    headers: {}
                }
            );
            // 獲取下載進(jìn)度,有需要可以再界面上做進(jìn)度條
            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) {
                // 文件夾已經(jīng)存在,無需創(chuàng)建
                console.log(success);
                defer.resolve(success);
            }, function (error) {
                // 文件夾不存在,創(chuàng)建文件夾
                createNewDir(filePath).then(function (fileEntry) {
                    // 創(chuàng)建成功
                    defer.resolve(fileEntry);
                }, function (error) {
                    console.log(error);
                    // 創(chuàng)建失敗
                    defer.reject(error);
                });
            });
        return defer.promise;
    }

    /**
     * 創(chuàng)建文件夾
     * @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("創(chuàng)建文件夾成功!路徑:" + success.nativeURL);

                defer.resolve(success);
            }, function (error) {
                // error
                console.log("創(chuàng)建文件夾失敗!");
                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設(shè)備仍舊走下面代碼
            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;
    }

安卓的已經(jīng)通過測試,是可以成功打開,ios在模擬器上測試通過了.如果真機(jī)有問題,問題應(yīng)該就出在文件路徑上,只要把對應(yīng)文件路徑地址該對即可.
項(xiàng)目地址:
https://gitee.com/477939838/readPdf

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容