How to Display blob (.pdf) in an AngularJS app

后端 未结 8 1299
逝去的感伤
逝去的感伤 2020-11-22 11:01

I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using

8条回答
  •  醉酒成梦
    2020-11-22 11:44

    I use AngularJS v1.3.4

    HTML:

    
    

    JS controller:

    'use strict';
    angular.module('xxxxxxxxApp')
        .controller('xxxxController', function ($scope, xxxxServicePDF) {
            $scope.downloadPdf = function () {
                var fileName = "test.pdf";
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                xxxxServicePDF.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:

    angular.module('xxxxxxxxApp')
        .factory('xxxxServicePDF', function ($http) {
            return {
                downloadPdf: function () {
                return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                    return response;
                });
            }
        };
    });
    

    Java REST Web Services - Spring MVC:

    @RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
        public ResponseEntity getPDF() {
            FileInputStream fileStream;
            try {
                fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
                byte[] contents = IOUtils.toByteArray(fileStream);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/pdf"));
                String filename = "test.pdf";
                headers.setContentDispositionFormData(filename, filename);
                ResponseEntity response = new ResponseEntity(contents, headers, HttpStatus.OK);
                return response;
            } catch (FileNotFoundException e) {
               System.err.println(e);
            } catch (IOException e) {
                System.err.println(e);
            }
            return null;
        }
    

提交回复
热议问题