How to get AngularJS BLOB to Download PDF?

后端 未结 5 2036
甜味超标
甜味超标 2021-01-12 08:54

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 wi

5条回答
  •  爱一瞬间的悲伤
    2021-01-12 09:57

    Possible Try-

    HTML:

    
    

    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!

提交回复
热议问题