3

I'm tring to download a pdf file inside a android web-view page. The problem is that the Web-view don't support the blob-link.

So I made a JavaScript interface, suggest by this answer

@JavascriptInterface
public void getBase64FromBlobData(String base64Data) throws IOException {
    convertBase64StringToPdfAndStoreIt(base64Data);
}
public static String getBase64StringFromBlobUrl(String blobUrl){
    if(blobUrl.startsWith("blob")){
        return "javascript: var xhr = new XMLHttpRequest();" +
                "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);" +
                "xhr.setRequestHeader('Content-type','application/pdf');" +
                "xhr.responseType = 'blob';" +
                "xhr.onload = function(e) {" +
                "    if (this.status == 200) {" +
                "        var blobPdf = this.response;" +
                "        var reader = new FileReader();" +
                "        reader.readAsDataURL(blobPdf);" +
                "        reader.onloadend = function() {" +
                "            base64data = reader.result;" +
                "            Android.getBase64FromBlobData(base64data);" +
                "        }" +
                "    }" +
                "};" +
                "xhr.send();";
    }
    return "javascript: console.log('It is not a Blob URL');";
}
private void convertBase64StringToPdfAndStoreIt(String base64PDf) throws IOException {
    String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
    final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/report_" + currentDateTime + ".pdf");
    byte[] pdfAsBytes = Base64.decode(base64PDf.replaceFirst("^data:application/pdf;base64,", ""), 0);
    FileOutputStream os;
    os = new FileOutputStream(dwldsPath, false);
    os.write(pdfAsBytes);
    os.flush();

    if(dwldsPath.exists())
        Toast.makeText(context, context.getApplicationContext().getString(R.string.download_success), Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context, context.getApplicationContext().getString(R.string.download_failed), Toast.LENGTH_LONG).show();

}

But this don't work correctly, because when I load the url like:

String newUrl = JavaScriptInterface.getBase64StringFromBlobUrl(url);
webView.loadUrl(newUrl);

nothing happining. So I suppose that is the blob url parse inside the interface, becouse when I change this: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);" to this "xhr.open('GET', ' ', true);"

code works, but, obviusly, don't download the right pdf but a empty file.pdf.

Any advice?

thanks

Matteo Sausto
  • 53
  • 1
  • 1
  • 9

1 Answers1

0

I had the same issue. In my case not all permissions were granted.

Please check:

  • WRITE_EXTERNAL_STORAGE,
  • READ_EXTERNAL_STORAGE and
  • ACCESS_NOTIFICATION_POLICY.
William Prigol Lopes
  • 1,803
  • 14
  • 31
Alona
  • 1