Arturo
Arturo

Reputation: 11

Download pdf file with Ionic via restful

I am creating a mobile app and I want to download a pdf file with restful, I don't know if it's possible.

$headers = array('Content-type: application/json','Authorization: ',);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');

$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));
curl_setopt($curl, CURLOPT_USERPWD, $api_key);
$file = curl_exec($curl);
if ($file === false){
   $info = curl_getinfo($curl);
   curl_close($curl);
   die('error occured during curl exec. Additioanl info: ' . var_export($info));
}

curl_close($curl);
header('Content-type: ' . 'application/octet-stream');
header('Content-Disposition: ' . 'attachment; filename=report.pdf');
echo $file;

angular.module('getPdf.Pdf', []).factory('Pdf', function ($http) {
    var folUrl = urlRest + '/getPdf.php';
    return {
        getPdf: function (pdfName) {
            return $http.post(folUrl, pdfName).then(function (response) {
                   return response;
            });
        }
    };
});

I can get the file as an object but i do not know if it's the right way?

Upvotes: 1

Views: 1742

Answers (1)

Dinesh Devkota
Dinesh Devkota

Reputation: 1417

Here is the snipped of code I used some time back to save PDF file from services using AngularJS which should work in Ionic.

 getPdf: function (pdfName) {
            return $http.post(folUrl, pdfName).then(function (result) {
              var file = new Blob([result.data], {type: 'application/pdf'});
                var timestamp = new Date().toUTCString();
                 saveAs(file, pdfName +timestamp+ ".pdf");
            });
        }

If saveas function didn't work by itself you might need to add FileSaver.js in your project. https://github.com/eligrey/FileSaver.js/

Upvotes: 0

Related Questions