Y. Leonce Eyog
Y. Leonce Eyog

Reputation: 903

DIsplay pdf in ioinic app from base64url

Hello World, I am receiving a base64url "JVBERi0xLjMKMSAwIG9iago8...mVmCjM3MjgxCiUlRU9GCg=="
from a web server and I am able to convert this string into a blob and display it in the browser using the code below.

.controller("formB", function() {
$scope.formb.year = ["2015"+"\/"+"2016", "2016"+"\/"+"2017"];
$scope.formb.semester = [1,2,3];
$scope.formb.pdf ="";

setDefaultsForPdfViewer($scope);
// Initialize the modal view.
$ionicModal.fromTemplateUrl('src/app/components/form_b/pdf-viewer.html', {
    scope: $scope,
    animation: 'slide-in-up'
}).then(function (modal) {
    $scope.modal = modal;
});
$scope.openModal = function() { 
    $scope.modal.show();
    };
$scope.$watchGroup([
'formb.year.selected',
'formb.semester.selected'
],function(newVals, oldVals){

    if(newVals[0]&&newVals[1]&&newVals!==oldVals){
            $ionicLoading.show({
             template:'Loading...'
                 }).then(function(){
             });

    DataFactory.getFormB(newVals[0],newVals[1]).then(function(resp){
           $scope.formb.pdf = resp.data.data; 
    var str  =  resp.data.data;
    currentBlob = myB64ToBlob(str,"application/pdf");

    $ionicLoading.hide().then(function(){
    console.log("No more loading");
        });

     $scope.pdfUrl = window.URL.createObjectURL(currentBlob);

            // Display the modal view

            });
    }

    });

    // Clean up the modal view.
    $scope.$on('$destroy', function () {
    $scope.modal.remove();
    });
    function base64ToUint8Array(base64) {  
    var raw = atob(base64);
    var uint8Array = new Uint8Array(raw.length);
    for (var i = 0; i < raw.length; i++) {
    uint8Array[i] = raw.charCodeAt(i);
    }
    return uint8Array.buffer;
    }  
    function myB64ToBlob( base64,contentType ){
    var arr =  base64ToUint8Array(base64);

    var blob = new Blob([arr], {type: contentType});
    return blob;
    }
    ...
       }

What is important here is this line here:

$scope.pdfUrl = window.URL.createObjectURL(currentBlob);

It works in the browser but it fails in the phone. I am really confused and I can't seem to figure out what is going on. Can anyone help?

Upvotes: 0

Views: 413

Answers (1)

Dinesh Devkota
Dinesh Devkota

Reputation: 1417

Try JS native function to create URL and pass it to scope. windows won't be available to phone.

  objectURL = URL.createObjectURL(blob);

Read this. https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

For mobile one needs to use ng-cordova file plugin. See here https://github.com/apache/cordova-plugin-file

Upvotes: 1

Related Questions