通过restful下载带有Ionic的pdf文件

时间:2016-08-24 17:18:21

标签: angularjs rest ionic-framework ngcordova

我正在创建一个移动应用,我想下载一个非常好的pdf文件,我不知道它是否可能。

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

我可以将文件作为对象,但我不知道它是否正确?

1 个答案:

答案 0 :(得分:0)

以下是使用AngularJS从服务中保存PDF文件的代码片段,这些代码应该在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");
            });
        }

如果saveas函数本身不起作用,则可能需要在项目中添加FileSaver.js。 https://github.com/eligrey/FileSaver.js/