Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get AngularJS BLOB to Download PDF?

Tags:

angularjs

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);
        });
});
like image 229
user2402107 Avatar asked Feb 04 '16 15:02

user2402107


People also ask

What is AngularJS PDF?

AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world.


2 Answers

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!

like image 72
Zeeshan Hassan Memon Avatar answered Oct 05 '22 02:10

Zeeshan Hassan Memon


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);
  }
}
like image 29
Steve Oh Avatar answered Oct 05 '22 02:10

Steve Oh