在Android / iOS App中显示PDF

时间:2015-10-27 00:01:56

标签: android ios cordova pdf

我已经在我的手机中下载了一个PDF文件作为Base64字符串,如SO Thread所述,但我不知道如何将其渲染为实际的PDF以便最终用户可以看到它?我写了以下代码来写在文件上:

var tempResponse = null;
function downloadFileOK(response){
var invocationResult = response['invocationResult'];
        tempResponse = invocationResult;
        var size = parseInt(invocationResult["responseHeaders"]["Content-Length"]);     
        window.requestFileSystem(LocalFileSystem.PERSISTENT, size, onSuccessFileHandler, onErrorFileHandler);
}

//Success
function onSuccessFileHandler(fileSystem) {
    alert("inside onSuccessFileHandler START");
    fileSystem.root.getFile("test2.pdf", {create: true, exclusive: false}, fileWriter, fail);
    alert("inside onSuccessHandler END");
}

// Failure
function onErrorFileHandler(error) {
    alert("inside onErrorFileHandler");
}

function fileWriter(entry){
    alert("inside fileWriter START");

    entry.createWriter(function(writer){
        writer.onwriteend = function(evt) {
            console.log("done written pdf :: test1.pdf");
            alert("Inside onwriteend : START");
        };

        var temp = atob(tempResponse["text"]);
        alert(temp);

        writer.write(temp);
    },fail);

    alert("inside fileWriter END");
}

function fail(error) {
    alert("inside fail");
    console.log(error.code);
}

我做错了吗?如何使用javascript / jquery / cordova从iOS / Android OS中的应用程序打开PDF?

1 个答案:

答案 0 :(得分:2)

下载base64编码文件后,您应对其进行解码并将其保存到文件系统中,以便以后查看。你不应该用它的base64编码形式保存基础。

您可以使用下面的效用函数来完成此操作。顺便说一句,你应该查看Download PDF file from through MobileFirst Adapter上的上一个答案,因为我对它进行了更新,它没有正确编码PDF。

var AppUtils = (function(){

    // get the application directory. in this case only checking for Android and iOS
    function localFilePath(filename) {
        if(device.platform.toLowerCase() === 'android') {
            return cordova.file.externalDataDirectory + filename;
        } else if(device.platform.toLowerCase() == 'ios') {
            return cordova.file.dataDirectory + filename;
        }
    }

    // FileWritter class
    function FileWritter(filename) {
        this.fileName = filename;
        this.filePath = localFilePath(filename);
    }

    // decode base64 encoded data and save it to file
    FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
        var byteData = atob(data);

        var byteArray = new Array(byteData.length);

        for (var i = 0; i < byteData.length; i++) {
            byteArray[i] = byteData.charCodeAt(i);
        }

        var binaryData = (new Uint8Array(byteArray)).buffer;

        this.saveFile(binaryData, ok, fail);
    }

    // save file to storage using cordova
    FileWritter.prototype.saveFile = function(data, ok, fail) {
        this.fileData = data;

        var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));

        var that = this;

        // Write file on local system
        window.resolveLocalFileSystemURL(path, function(directoryEntry) {
            var options = {create: true, exclusive: false};

            directoryEntry.getFile(that.fileName, options, function(file) {
                file.createWriter(function(writer) {
                    writer.onwriteend = function(event) {
                        if(typeof ok === 'function') {
                            ok(event);
                        }
                    };

                    writer.write(that.fileData);
                }, fail);
            }, fail);

        }, fail);
    };

    // open InApp Browser to view file
    function viewFile(filename) {
        var path = localFilePath(filename);

        window.open(path, "_blank", "location=yes,hidden=no,closebuttoncaption=Close");
    }

    return {
        FileWritter: FileWritter,
        localFilePath: localFilePath,
        viewFile: viewFile
    }
})();

您的downloadFileOK应如下所示:

function downloadFileOK(response){
    var pdfData = response['invocationResult']['text'];

    var fileWritter = new AppUtils.FileWritter('YOUR-PDF-NAME.pdf');

    fileWritter.saveBase64ToBinary(pdfData, function(r){
        // file was saved
    }, function(e){
        // error file was not saved
    });
}

如果要打开文件,可以使用AppUtils.viewFile('YOUR-FILE-NAME.pdf')