8

Hello everyone I am really new to developing with AngularJS and I am trying to figure out how to use BLOB to download a PDF locally to a machine. I already got it to work with a JSON and now I need a PDF. I have written some code but it doesn't seem to be working.

html

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .center {
            position: absolute;
            left: 50%;
            bottom: 50%;
        }

        .btn-purple {
            background-color: rgb(97, 34, 115);
            width: 100px;
        }

    </style>
    <meta charset="UTF-8">
    <title></title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>


<body>
<div class="center" ng-controller="jsonController" ng-app="app">
    <a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
        <button type="button" class="btn btn-purple">{{fileName}}</button>
    </a>
</div>

<div class="center" ng-controller="pdfController" ng-app="app">
    <a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
        <button type="button" class="btn btn-purple">{{fileName}}</button>
    </a>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>

controller.js

var app = angular.module('app', []);

app.config(['$compileProvider', function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);

app.controller('jsonController', function ($scope, $window, $http, $log) {
    $http.get('data.json')
        .success(function (info) {
            var data = angular.toJson(info, true);
            data = data.replace(/\n/g, "\r\n")
            console.log(data)
            var blob = new Blob([data], {type: "octet/stream"}),
                url = $window.URL || $window.webkitURL;
            $scope.fileUrl = url.createObjectURL(blob);
            $scope.schemaName = "test"
            $scope.fileName = $scope.schemaName + ".json"
        })
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
    $http.get('data.json' + $stateParams.id,
        {responseType: 'arraybuffer'})
        .success(function (response) {
            var file = new Blob([(response)], {type: 'application/pdf'});
            var fileURL = URL.createObjectURL(file);
            $scope.content = $sce.trustAsResourceUrl(fileURL);
        });
});
user2402107
  • 913
  • 5
  • 22
  • 43

5 Answers5

18

Possible Try-

HTML:

<button ng-click="downloadPdf()" >Download PDF</button>

JS controller:

'use strict';
var app = angular.module('app')
    .controller('ctrl', function ($scope, MathServicePDF) {
        $scope.downloadPdf = function () {
            var fileName = "file_name.pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            ServicePDF.downloadPdf().then(function (result) {
                var file = new Blob([result.data], {type: 'application/pdf'});
                var fileURL = window.URL.createObjectURL(file);
                a.href = fileURL;
                a.download = fileName;
                a.click();
            });
        };
});

JS services:

app.factory('ServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});

Happy Helping!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
  • 1
    Hi! Is it necessary to delete that dummy "a" tag afterwords? If yes, how important is it? – Arttu Apr 10 '19 at 10:10
9

Tested with large files (> 1.5 GB) on

  • Firefox 56.0
  • Safari 11.0

Use the following in your angular controller:

$scope.download = function() {
 $http({
   method: 'GET',
   url: fileResourceUrl,
   responseType: 'blob'
 }).then(function(response) {
   var blob = response.data;
   startBlobDownload(blob, "largedoc.pdf")
 });

};

function startBlobDownload(dataBlob, suggestedFileName) {
   if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      // for IE
      window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
   } else {
      // for Non-IE (chrome, firefox etc.)
      var urlObject = URL.createObjectURL(dataBlob);

      var downloadLink = angular.element('<a>Download</a>');
      downloadLink.css('display','none');
      downloadLink.attr('href', urlObject);
      downloadLink.attr('download', suggestedFileName);
      angular.element(document.body).append(downloadLink);
      downloadLink[0].click();

      // cleanup
      downloadLink.remove();
      URL.revokeObjectURL(urlObject);
  }
}
vzipp
  • 350
  • 3
  • 8
Steve Oh
  • 1,149
  • 10
  • 18
0

Change your responseType from responseType: 'arraybuffer' to responseType: 'blob'

Ricardo Alfaro
  • 110
  • 1
  • 10
0

In you controller PHP

   return $pdf->stream();

In you controller AngularJS

$http.post('generate', {
    dateStart:  $scope.ds,
    dateEnd:    $scope.de
}, 
{
  responseType: 'arraybuffer'
}).then(function success(response) {

  var blob = new Blob([response.data], { type: "application/pdf"});
  saveAs(blob, "filename.pdf");

}, function error(error) {
    $scope.recordErrors(error);
});
Vega
  • 27,856
  • 27
  • 95
  • 103
0

This code worked for me in angular 9, Yii2, while using mpdf

this._gService.download_post(`controller/action`, postData).pipe(takeUntil(this._unsubscribeAll)).subscribe(result => {

  const fileURL = URL.createObjectURL(result);

  // Direct print preview

  // const iframe = document.createElement('iframe');
  // iframe.style.display = 'none';
  // iframe.src = fileURL;
  // document.body.appendChild(iframe);
  // iframe.contentWindow.print();

  // Direct Download

  const fileName = 'Patient Report';
  const a = document.createElement('a');
  document.body.appendChild(a);
  a.href = fileURL;
  a.download = fileName;
  a.click();


}, error => {
   // show error message
});
danish ali
  • 132
  • 1
  • 5