如何在Cordova / Ionic应用程序中打开PDF文件?

时间:2015-05-18 10:41:34

标签: cordova pdf ionic-framework ionic inappbrowser

我试图在我的应用中打开一个PDF文件,我正在使用Ionic构建。我知道我可以使用inAppBrowser来做到这一点。

我首先从api端点获取PDF,然后将其写入文件系统。一旦将其写入文件系统,我想使用inAppBrowser打开它。我现在的代码如下:

$http.get(window.apiUrl + '/doc/54bfcc7b879c686969d2bbfe')
    .success(function(data){
        console.log('PDF GOTTEN SUCCESFULLY. NOW WRITE IT TO A FILE.');
        $cordovaFile.writeFile('ticket.pdf', data, true)
            .then(function (success) {
                console.log('PDF WAS WRITTEN TO THE FILE SYSTEM');
                console.log(JSON.stringify(success));
                $cordovaFile.readAsText('ticket.pdf')
                    .then(function (data) {
                        console.log('PDF COULD BE READ FROM THE SYSTEM');
                        window.open('cdvfile://localhost/persistent/ticket.pdf', '_system', 'location=no');
                        console.log('AFTER OPENING THE PDF');
                    }, function (error) {
                        console.log(JSON.stringify(error));
                    });
            }, function (error) {
                console.log(JSON.stringify(error));
            });
    })
    .error(function(error){
        console.log('IMAGE GET FAILURE.');
    });

我在控制台中没有任何错误,但屏幕上没有任何反应。我在console.log中看到的输出如下:

file:///android_asset/www/js/controllers.js: Line 104 : PDF GOTTEN SUCCESFULLY. NOW WRITE IT TO A FILE.
file:///android_asset/www/js/controllers.js: Line 110 : PDF WAS WRITTEN TO THE FILE SYSTEM
file:///android_asset/www/js/controllers.js: Line 111 : {"type":"writeend","bubbles":false,"cancelBubble":false,"cancelable":false,"lengthComputable":false,"loaded":0,"total":0,"target":{"fileName":"","length":598874,"localURL":"cdvfile://localhost/persistent/ticket.pdf","position":598874,"readyState":2,"result":null,"error":null,"onwritestart":null,"onprogress":null,"onwrite":null,"onabort":null,"onerror":null}}
file:///android_asset/www/js/controllers.js: Line 115 : PDF COULD BE READ FROM THE SYSTEM
file:///android_asset/www/js/controllers.js: Line 119 : AFTER OPENING THE PDF

正如您所看到的,我将故障单名称(ticket.pdf)和打开时的路径(cdvfile://localhost/persistent/ticket.pdf)硬编码。我从json成功输出得到的文件路径,如第111行的输出所示(见上文)。

有人知道为什么这不起作用吗?欢迎所有提示!

1 个答案:

答案 0 :(得分:0)

url cdvfile://localhost/persistent/ticket.pdf不正确。您将需要一个以file://。

开头的nativeurl路径

试试这些:

'文件:///storage/emulated/0/ticket.pdf' 要么 '文件:///storage/sdcard0/ticket.pdf'