Save this pdf in the cache/local storage on ionic

2019-02-21 04:22发布

问题:

Ho to everyone. I followed this tutorial to create a modal view with a pdf generated with pdfmake.

http://gonehybrid.com/how-to-create-and-display-a-pdf-file-in-your-ionic-app/

My simply question is how can i save the pdf in my local storage on in cache? I need that to send the pdf by email or open it with openfile2. I'm using Ionic and cordova.

回答1:

I don't know how you code it, but I know what plugin you should use:

https://github.com/apache/cordova-plugin-file

The git contains a complete documentation of the plugin so everything you could need should be there.



回答2:

Sample code to write pdf file in device using cordova file and file transfer plugin:

var fileTransfer = new FileTransfer();

    if (sessionStorage.platform.toLowerCase() == "android") {
        window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
    } else {
        // for iOS
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
    }

    function onError(e) {
        navigator.notification.alert("Error : Downloading Failed");
    };

    function onFileSystemSuccess(fileSystem) {
        var entry = "";
        if (sessionStorage.platform.toLowerCase() == "android") {
            entry = fileSystem;
        } else {
            entry = fileSystem.root;
        }
        entry.getDirectory("Cordova", {
            create: true,
            exclusive: false
        }, onGetDirectorySuccess, onGetDirectoryFail);
    };

    function onGetDirectorySuccess(dir) {
        cdr = dir;
        dir.getFile(filename, {
            create: true,
            exclusive: false
        }, gotFileEntry, errorHandler);
    };

    function gotFileEntry(fileEntry) {
        // URL in which the pdf is available
        var documentUrl = "http://localhost:8080/testapp/test.pdf";
        var uri = encodeURI(documentUrl);
        fileTransfer.download(uri, cdr.nativeURL + "test.pdf",
            function(entry) {
                // Logic to open file using file opener plugin
            },
            function(error) {
                navigator.notification.alert(ajaxErrorMsg);
            },
            false
        );
    };