AngularJS Display PDF (byte[]) received from Spring @RestController AngularJS Display PDF (byte[]) received from Spring @RestController angularjs angularjs

AngularJS Display PDF (byte[]) received from Spring @RestController


I use this code and it works for me:

REST Controller:

@RequestMapping(value = "/api/reports/pdf", method = RequestMethod.GET)@Timedpublic @ResponseBody byte[] getOpenedEventsInPdf(HttpServletResponse response) {    response.setHeader("Content-Disposition", "inline; filename=file.pdf");    response.setContentType("application/pdf");// get file in bytearray from my custom service in backend    byte[] file = jasperReportsService.getOpenedEventsReport(ReportFormat.PDF);    return file;}

JS/Angular Controller;

$scope.getPdf = function(){  $http.get('/api/reports/pdf', {responseType: 'arraybuffer'})  .success(function (data) {    var file = new Blob([data], {type: 'application/pdf'});    var fileURL = URL.createObjectURL(file);    window.open(fileURL);  });}

HTML fragment:

<a ng-click="getPdf()">Show PDF</a>


For "Browser Compatibility" given code is working properly :

Get the byte array data from beck-end controller side and generate file on js controller side :

Beck-end controller

@RequestMapping(value = "/getPDF", method = RequestMethod.GET)public byte[] getEvalutaionResultPDF()  {                byte[] data = //get byte Array from back-end service        return data;}

JS Service

var getPdfFile = function(){        return $http.get("getPDF", {responseType: 'arraybuffer'});};

JS controller

$scope.pdfFile = function() {        service.getPdfFile().then(function (data) {            //for browser compatibility              var ieEDGE = navigator.userAgent.match(/Edge/g);            var ie = navigator.userAgent.match(/.NET/g); // IE 11+            var oldIE = navigator.userAgent.match(/MSIE/g);             var name = "file";            var blob = new window.Blob([data.data], { type: 'application/pdf' });            if (ie || oldIE || ieEDGE) {                var fileName = name+'.pdf';                window.navigator.msSaveBlob(blob, fileName);            }            else {                var file = new Blob([ data.data ], {                    type : 'application/pdf'                });                var fileURL = URL.createObjectURL(file);                var a         = document.createElement('a');                a.href        = fileURL;                 a.target      = '_blank';                a.download    = name+'.pdf';                document.body.appendChild(a);                a.click();            }        },        function(error) {            //error        });    };


In the following link, you should find the answer :

AngularJS Display PDF (byte[]) received from Spring(@RestController) + jasper report

In this link you find how display pdf in a iframe using angularjs.The pdf is received from a API rest using spring and jasper report.