Problem with angular-pdf and pdfmake


#1

Hi guys,
I’ve a trouble with download of a PDF file created with pdfmake. I have created and viewed the pdf made from charts.js, but now I would like to download the file.

I tried to use ngCordova:

var blob = new Blob([pdf], {type: ‘application/pdf’});

$scope.pdfUrl = URL.createObjectURL(blob);

$cordovaFile.writeFile(cordova.file.dataDirectory,‘fileName.pdf’,$scope.pdfUrl, true).then(function(result){
alert(‘Success! Survey created!’);
}, function(err) {
console.log(“ERROR”);
})

But I got an error 1: NOT_FOUND_ERR

What’s wrong? Please help me…I’m going crazy!! Thank you all guys


#2

Solved by myself. The problem was with the directory path.


#3

Helo

Can you tell me your solution?

cordova.file.dataDirectory is undefined for me

I want sabe the file in sdcard from android de ice

Thnx


#4

I need more information.
What r u trying to do? Send me some snippets of code if u can.

You should log your path and all the information you need so we can figure out what’s the problem


#5

Sorry here my code:

//Controller
.controller(‘BillCtrl’, function($scope,$rootScope,APIService,$state,$sce,$window,$cordovaFileOpener2, $ionicPlatform,$cordovaFile) {
$scope.openPDF= function() {
APIService.GetPDFBill()
.then(function(result) {

        var blob = new Blob([result.data], {type: 'application/pdf'});
        $scope.pdfUrl = window.URL.createObjectURL(blob);
      })
      .catch(function(result) {
      })
      .finally(function () {

        //Debemos guardar el file en el device
        $cordovaFile.writeFile(**cordova.file.externalRootDirectory**,'fileName.pdf',$scope.pdfUrl, true).then(function(result){
          alert('Success! Survey created!');
        }, function(err) {
          alert("ERROR: " + Cordova.file.externalRootDirectory);    **// UNDEFINED** 
        });

        $cordovaFileOpener2.open(
            '/sdcard/fileName.pdf',
            'application/pdf'
        ).then(function() {
            alert('Success');
        }, function(err) {
            alert('An error occurred: ' + JSON.stringify(err));
        });
      });
};

Thnx


#6

Sorry the aler is:
alert("ERROR: " + cordova.file.externalRootDirectory);


#7

If this is undefined maybe you don’t have added the file plugin?

cordova plugin add cordova-plugin-file

here the url: http://ngcordova.com/docs/plugins/file/


#8

Hello

I’ve installed in plugins cordova-plugin-file and cordova-plugin-file-opener2

there may be conflict?

Is very strange because this sentence: alert(cordova.file.dataDirectory); Nothing happens
I then than cordova.file.dataDirectory throws an error

Thnx


#9

My code is:

    $scope.pdfPath = {};
    if(isIOS) {
              $scope.pdfPath = cordova.file.documentsDirectory;
    } else if (isAndroid) {
              $scope.pdfPath = cordova.file.externalApplicationStorageDirectory;
    }
   ...
   var pathName = $scope.pdfPath+'pdf-chart-reports/';
   .....
   
   $scope.downloadReportPDF = function() {
        // WRITE
        $scope.creatingPDF=true;
        var pathName = $scope.pdfPath+'pdf-chart-reports/';
        if($scope.blob) {
            var date = new Date();
            var postFix = ""+date.getHours()+"."+date.getMinutes()+"."+date.getDate()+"."+(date.getMonth() + 1)+"."+date.getFullYear();
            
            UserService.get().then(function (result) {
                  $scope.user = result.data.user;
                  $cordovaFile.checkDir($scope.pdfPath, 'pdf-chart-reports/').then(function (success) {
                    console.log('the directory exists');
                    $cordovaFile.writeFile(pathName, "chart-"+$scope.user.username+"-"+postFix+".pdf", $scope.blob, true)
                      .then(function (success) {
                        // success
                        $scope.creatingPDF=false;
                      }, function (error) {
                        // error
                        $scope.creatingPDF=false;
                        console.log('Error on PDF download');
                    });
                  }, function (error) {
                      // If directory doesn't exist, i will create it
                      $cordovaFile.createDir($scope.pdfPath, 'pdf-chart-reports/', false)
                        .then(function (success) {
                          console.log('directory '+$scope.pdfPath+'pdf-chart-reports/'+' created');
                          $cordovaFile.writeFile(pathName, "chart-"+$scope.user.username+"-"+postFix+".pdf", $scope.blob, true)
                            .then(function (success) {
                              ToastService.showToast('Report '+'chart-'+$scope.user.username+'-'+postFix+'.pdf'+' scaricato con successo','short','center');
                              $scope.creatingPDF=false;
                            }, function (error) {
                              // error
                              $scope.creatingPDF=false;
                              ToastService.showToast('Error on PDF download');
                          });
                        }, function (error) {
                          $scope.creatingPDF=false;
                          ToastService.showToast('Error on PDF download');
                    });
                  });
            });
          
        }
      }


// Where $scope.blob is:

$scope.blob = new Blob([pdf], {type: 'application/pdf'});

Hope it helps you.


#10

Hello
Thnx for your code it’s very interesant.
I resolved de problem uninstall de plugins.

The next problem is with new Blob.

My code:
apiRoutes.post(’/getPDFBill’, passport.authenticate(‘jwt’, { session: false}), function(req, res) {

  exec('curl -X POST --insecure -d "Param" URL > /home//tmp/facturaOut.pdf', function(err,out,code){
  
  var filePath = "/home/tmp/facturaOut.pdf";
  fs.readFile(filePath , function (err,data){
     res.contentType("arraybuffer");
     res.send(data);
  });
});

});

In my controller:
APIService.GetPDFBill()
.then(function(result) {
var blob = new Blob(result.data, {type: ‘application/pdf’}); --> Error The code stop

Can you tell me the mistake? thnx


#11

Are you sure that result is well formatted?

Your result.data must be the base64 result of pdfMake library output.
I mean :

PDFService.createPdf(myData).then(function(pdf) {
        var blob = new Blob([pdf], {type:'application/pdf'});
        ...

Where:

function PDFService($q,ReportSrv,GRAPHTYPE) {  
    function createPdf(myData) {
        return $q(function(resolve, reject) {
            var dd = createDocumentDefinition(myData); // JSON version of our PDF
            var pdf = pdfMake.createPdf(dd);
            pdf.getBase64(function (output) {
                resolve(base64ToUint8Array(output));
            });
            
        });
    }

    return {
        createPdf: createPdf
    };    
}

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;
}

I’ve used this one to accomplish my task: http://gonehybrid.com/how-to-create-and-display-a-pdf-file-in-your-ionic-app/

Good luck


How to write data to a file using ngCordova?
#12

After viewing your code I want to ask that where are you storing the .pdf file when you are generating it through pdfmaker.

Can we get the location of the file while generating a pdf through pdfmaker ?
@ddelfio