简体   繁体   中英

How do I open and display a base64 pdf from inside my Cordova App?

I am creating an App for Android using Cordova, and I would like to open and display a file (PDF or image) that is served from the server as Base64-encoded binary data. Of course I have read the multiple other posts on the subject that already exist on this website, but none of the proposed solutions have worked for me, more details below.

To be more precise, the server sends a JSON-file to the app, which among many other things contains a string consisting of the base64-encoded contents of a PDF file. I want to convert this data back into the represented PDF and display it to the user.

If this were a pure browser page, I would simply package my base64 data into a data-URL, attach this as the href of some anchor, and add a download-attribute. Optionally I could wrap all of my data into a blob and create an object url for that first.

In Cordova, this does not work. Clicking the <a> does nothing. Here is what I have attempted so far:

  • Using the file plugin, I can write the binary data to a file on the device. This works, and using a terminal I can see that the file was downloaded correctly, but into an app-private directory which I cannot access normally (eg through the file explorer).
  • Accessing the user's "downloads" folder is blocked by the file system
  • Using window.open with the file path as the first argument and "_system" as the target does nothing. There is no error but also nothing happens. Setting the target to "_blank" instead, I get an error saying ACCESS_DENIED.
  • Using cordova.InAppBrowser behaves the same was as window.open
  • With the plugin file-opener2 installed, the app will not compile, because the plugin is looking for an android4 toolchain, and I am building for android 9 and up
  • The plugin document-viewer (restricting to PDFs for the time being) suffers the same problem and does not compile.
  • Passing the data-URI to window.open (or cordova.InAppBrowser) directly loads for a very long time and eventually tells me that the desired page could not be loaded.

The PDF file I am using for testing is roughly 17kb after converting to base64. I know this is technically above the spec for how long data-URIs can be, but Chrome in the browser has no trouble with it whatsoever, and using a much shorter URI (only a few dozen bytes) produces the same behavior.

Ideally, what I would like to do, is download the file and then trigger the user's standard browser to open the file itself. That was, I would not have to deal with MIME types and also it would look exactly how the user expected from their own device. Alternatively, if that doesn't work, I would be ok with downloading the file into a system-wide directory and prompting the user to open it themselves. This is not optimal, but I would be able to swallow that pill. And lastly, if there is a plugin or some other solution that solves the problem amazingly, but for PDFs only, then I can also work out something else for images (eg embedding a new into my app and assigning the URI to that).

I would be thankful for any suggestion you might have on how to solve this problem. The code I use to download the file currently is shown below.

Thank you for your time.

var filePath = cordova.file.externalDataDirectory;  // Note: documentsDirectory is set to "" by Cordova, so I cannot use that
var fileName = "someFileName.pdf";
var mime = "application/pdf";
var dataBlob = /* some blob containing the binary data for a PDF */

function writeFile(fileEntry, dataBlob) {
    // Create a FileWriter object for our FileEntry.
    // This code is taken directly from the cordova-plugin-file documentation
    fileEntry.createWriter(function (fileWriter) {

        fileWriter.onwriteend = function() {
            console.log("Successful file write...");
            readFile(fileEntry);
        };

        fileWriter.onerror = function (e) {
            console.log("Failed file write: " + e.toString());
        };

        fileWriter.write(dataBlob);
    });
}


window.resolveLocalFileSystemURL(
    filePath,
    function onResolveSuccess (dirEntry) {
        dirEntry.getFile(
            fileName,
            { create: true },
            function onGetFileSuccess (file) (
                writeFile(file, dataBlob);
                // At this point, the file has been downloaded successfully
                window.open(file.toURL(), "_system"); // This line does nothing, and I don't understand why.
            }
        );
    }
);

I managed to solve the problem.

As per the documentation of the file-opener2 plugin, you need to also add the androidx-adapter plugin to correct for the outdated (android 4) packages. With the plugins file, file-opener2 and androidx-adapter installed, the complete code is the following:

var filePath = cordova.file.externalDataDirectory;  // Note: documentsDirectory is set to "" by Cordova, so I cannot use that
var fileName = "someFileName.pdf";
var mime = "application/pdf";
var dataBlob = /* some blob containing the binary data for a PDF */

function writeFile(fileEntry, dataBlob) {
    // Create a FileWriter object for our FileEntry.
    // This code is taken directly from the cordova-plugin-file documentation
    fileEntry.createWriter(function (fileWriter) {

        fileWriter.onwriteend = function() {
            console.log("Successful file write...");
            readFile(fileEntry);
        };

        fileWriter.onerror = function (e) {
            console.log("Failed file write: " + e.toString());
        };

        fileWriter.write(dataBlob);
    });
}


window.resolveLocalFileSystemURL(
    filePath,
    function onResolveSuccess (dirEntry) {
        dirEntry.getFile(
            fileName,
            { create: true },
            function onGetFileSuccess (file) (
                writeFile(file, dataBlob);
                // At this point, the file has been downloaded successfully
                cordova.plugins.fileOpener2.open(
                    filepath + filename,
                    mime,
                    {
                        error : function(){ },
                        success : function(){ }
                    }
                );
            }
        );
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM