Angular download pdf - angularjs

I have angular function which get pdf data from server:
printDocument: function (bundleId, policyId) {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
$resource(baseUrlPrint, {
bundleId: bundleId,
policyId: policyId
}, {
get: {
method: 'GET'
},
responseType:'arraybuffer',
cache: true
}).get().$promise.then(function(result) {
console.log(result);
var file = new Blob([result], {type: 'application/pdf'});
var fileURL = (window.URL || window.webkitURL).createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
}
When I check a result variable I see there is byte array contains pdf file. But when I open this file in Notepad++ I see that there is no pdf byte data but only:
[object Object]. Is something wrong with my Blob object?

In case the API Rest retrieves an array of bytes you can simply use this js function
(function() {
'use strict';
angular
.module('fileUtils')
.service('DownloadService', DownloadService);
DownloadService.$inject = ['$window'];
function DownloadService($window) { // jshint ignore:line
this.download = function (fileBytes, name, type) {
var fileName = '';
if (name) {
fileName = name + '.' + type;
} else {
fileName = 'download.' + type;
}
var byteCharacters = atob(fileBytes);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/' + type });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName);
} else {
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = fileName;
document.body.appendChild(a);
a.click();
}
};
}
})();

Related

Only getting a few markers in the map

I am very new to angularJS and still exploring.I have created a map and showing around 1500 markers in it but when I load only 11 markers are visible.I am taking the Zip codes from a XML file and using geocoding I am converting them to LatLng and showing in map.Can any one suggest any solution.
Thanks in advance.
//Angular App Module and Controller
var mapApp = angular.module('mapApp', []);
// app.directive("importSheetJs", [SheetJSImportDirective]);
mapApp.factory('mySHaredService', function ($rootScope) {
var mySHaredService = {};
mySHaredService.message = '';
mySHaredService.prepForBroadcast = function (msg) {
this.message = msg;
this.broadcastItem();
};
return mySHaredService;
});
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
$timeout(function() {
console.log("Zip data from excel sheet" + $rootScope.zipArray)
var geocoder = new google.maps.Geocoder();
for (var i = 15; i <= $rootScope.zipArray.length; i++) {
var address = $rootScope.zipArray[i];
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$rootScope.LatLongList.push({
"latitudeValue": latitude,
"longitudeValue": longitude
});
}
});
}
// setTimeout(function () {
// $scope.$apply(function () {
// })
// }, 30000);
$timeout(function () {
console.log("Latitude value " + $rootScope.LatLongList[1].latitudeValue)
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(33.6496252, -117.9190418),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var circle = new google.maps.Circle({
center: new google.maps.LatLng(33.6496252, -117.9190418),
map: $scope.map,
radius: 10000, // IN METERS.
fillColor: '#FF6600',
fillOpacity: 0.3,
strokeColor: "#FFF",
strokeWeight: 0 // DON'T SHOW CIRCLE BORDER.
});
var bounds = circle.getBounds();
$scope.markers = [];
$rootScope.selectedAd = "";
var selectedLocation = [{ "lat": 0, "long": 0 }];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.latitudeValue, info.longitudeValue),
title: ""
});
marker.content = '<div class="infoWindowContent">' + '<br />' + info.latitudeValue + ' E,' + info.longitudeValue + ' N, </div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
selectedLocation[0].lat = marker.getPosition().lat();
selectedLocation[0].long = marker.getPosition().lng();
console.log("Latitude is " + selectedLocation[0].lat + "Longitude is " + selectedLocation[0].long);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: marker.getPosition()
}, $scope.selectedLoc = function (responses) {
if (responses && responses.length > 0) {
// alert(responses[0].formatted_address);
$rootScope.selectedAd = responses[0].formatted_address;
setTimeout(function () {
$scope.$apply(function () {
$rootScope.selectedAd = responses[0].formatted_address;
})
}, 1000);
$timeout(function () {
$rootScope.selectedAd = responses[0].formatted_address;
$scope.handleClick = function (msg) {
mySHaredService.prepForBroadcast($rootScope.selectedAd);
}
$scope.$on('handleBroadcast', function () {
$scope.message = $rootScope.selectedAd;
})
}, 2000);
} else {
}
});
});
$scope.markers.push(marker);
}
setTimeout(function () {
}, 3000);
$timeout(function () {
for (i = 1; i < $rootScope.LatLongList.length; i++) {
console.log(bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue)));
// if (bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue))) {
createMarker($rootScope.LatLongList[i]);
console.log("The value of i is " + i);
// }
}
}, 4000);
$scope.openInfoWindow = function (e, selectedMarker) {
var data = $rootScope.selectedAd
this.broadcastItem();
window.location = "valuePage.html";
}
}, 4000);
}, 2000);
oReq.send();
});
mapApp.controller("viewApp", function ($scope, $rootScope, mySHaredService, $timeout) {
// $scope.selectedAd = Products.FirstName;
// $scope.selectedAd = Products.FirstName;
setTimeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 3000);
$timeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 4000);
});
This is because you are sending too many requests through per second.
In addition to daily quota limits, the geocoding service is rate limited to 50 QPS (queries per second), calculated as the sum of client-side and server-side queries.
The Optimizing Quota Usage When Geocoding has a lot of strategies on how to account for that.
In your case I suggest doing a randomized interval for each request you make that way they are spread out you avoid going over the 50 request per second limit.
I've modified the part of your code sample where you are making the request.
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var randomTime = Math.round(Math.random()*(3000-500))+500;
var geocodeRequest = setTimeout(function() {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
}, randomTime);

Posting to Node.js post function from AngularJS

I am having problem posting to a function in my back-end (Node.js) from my front-end (AngularJS).
I keep getting a 404 error. Could someone see if there is something wrong with my code as I can't see what may be causing this.
Front end
MockUpMaker_v1/js/controller.js
// All photos've been pushed now sending it to back end
$timeout(function () {
$http.post('/MockUpMaker_v1/savePhotos', $scope.photosToPhp).then(function (success) {
$scope.generating = false;
$scope.generateBtn = 'Generate';
//creating mock up gallery
for (var x = 0; x < success.data.photos; x++) {
var file = '/MockUpMaker_v1/tmp/' + success.data.folder + "/out" + x + ".png";
$scope.gallery.push(file);
}
$scope.photosToPhp = [];
}, function (error) {
});
},
Back end
MockUpMaker_v1/server.js
app.post('/MockUpMaker_v1/savePhotos', function(req, res){
var folder = Math.random().toString(36).substr(2, 20);
var photos = req.body;
var counts = 0;
var callback = function(counts){
if(counts < photos.length){
saveBase64(photos[counts], folder, counts, callback);
}else{
// var counts = 0;
var response = {"folder": folder, "photos": photos.length};
res.send(response)
}
};
saveBase64(photos[counts], folder, counts, callback);
});
Full back-end
As requested
"use strict";
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var mkdirp = require('mkdirp');
var archiver = require('archiver');
var app = express();
var server = require('http').Server(app);
app.use(bodyParser.json({limit: '50mb'}));
app.use(express.static('/public'));
app.use(express.static('/js'));
app.use(express.static('/tmp'));
app.use(express.static('/img'));
app.use(express.static('/css'));
app.get('/', function(req, res){
res.sendFile(__dirname + 'views/form-mockup.html')
});
app.post('/MockUpMaker_v1/savePhotos', function(req, res){
var folder = Math.random().toString(36).substr(2, 20);
var photos = req.body;
var counts = 0;
var callback = function(counts){
if(counts < photos.length){
saveBase64(photos[counts], folder, counts, callback);
}else{
// var counts = 0;
var response = {"folder": folder, "photos": photos.length};
res.send(response)
}
};
saveBase64(photos[counts], folder, counts, callback);
});
app.post('MockUpMaker_v1/downloadZip', function(req, res){
var photos = req.body;
var out = photos[0];
var test = out.split('/');
var loc = test.pop();
var end = test.join('/');
console.log(end);
var outName = '/' + end + '/MockUp.zip';
var output = fs.createWriteStream(outName);
var archive = archiver('zip', {store: true });
var zip = function(photos, f){
for(var t = 0; t < photos.length; t++){
var file = 'mockUp' + t + '.jpg';
var from = '/' + photos[t];
archive.file( from, { name: file });
}
f();
};
output.on('close', function() {
var photos = req.body;
var out = photos[0];
var test = out.split('/');
var loc = test.pop();
var end = test.join('/');
res.send(end + '/MockUp.zip');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
zip(photos, f);
function f(){
archive.finalize();
}
});
server.listen(3000, function(){
console.log('sm2.0 server running');
});
function saveBase64(photo, folder, counts, callback){
var result = photo.split(',')[1];
var path = 'tmp/' + folder;
var filename = path + "/out" + counts + ".png";
mkdirp( path, function() {
fs.writeFile(filename, result, 'base64', function(error){
if (error) {
console.log('error saving photo');
}else{
console.log('photo saved');
counts++;
callback(counts);
}
});
});
}
And console printout
[nodemon] restarting due to changes... [nodemon] restarting due to
changes... [nodemon] starting node server.js sm2.0 server running
Inspect error
POST http://localhost:63342/MockUpMaker_v1/savePhotos 404 (Not Found)
In your Angular App, write the whole URL as the first argument of the $http.post function.
E.g. http://localhost:3000/MockUpMaker_v1/savePhotos

Unable to get $scope variables inside the fileReader.onload function

I am using something like this in angular
app.controller('techiesClub', function($scope, $http) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.asdf = "ankur";
$scope.uploadImage = function () {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = document.getElementById("upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent, ss) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
$scope.asdf = srcData; //////////////////NOT WORKING
}
debugger;
fileReader.readAsDataURL(fileToLoad, $scope);
}
}
});
Using uploadImage method on onchange of a input like this
<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage()">
I am unable to get the srcData i.e. the base64 data into a variable that i can use else where.
Ankur,
We can rewrite html in this way.
<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage(this);">
JS snippet here.. i'm trying with Blob version.
$scope.uploadImage = function ($event) {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = $event.files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var _ULR = window.URL || window.webkitURL;
var img = new Image();
img.onload = function() {
var srcData = this.src; // <--- data: blob
$scope.asdf = srcData; //////////////////NOT WORKING
};debugger;
img.src =_ULR.createObjectURL(fileToLoad);
}
}
I think you are missing the key point in your solution. I just change the way you are accessing the base64 contents. It should work.
$scope.uploadImage = function () {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = document.getElementById("upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileReader.result; // <--- data: base64
$scope.asdf = srcData; //////////////////NOT WORKING
}
debugger;
fileReader.readAsDataURL(fileToLoad);
}
}

Can't get rid of `$scope` in favor of `this` inside `$http.get` request

EDIT2:
var LanguageCtrl;
LanguageCtrl = function($scope, $http, $window) {
var vm;
vm = this;
if ($window.navigator.language.indexOf('it') !== -1) {
this.lang = 'it';
this.setLanguage = 'it';
} else {
this.lang = 'en';
this.setLanguage = 'us';
}
this.message = [];
this.pizze = [];
this.getPizze = function(lang) {
$http.get('localization/pizze-' + lang + '.json').success(function(pizze) {
vm.pizze = pizze;
});
};
this.setLanguage = function(lang) {
$http.get('localization/' + lang + '.json').success(function(data) {
vm.lang = lang;
vm.message = data;
vm.getPizze(vm.lang);
$window.location.href = '#!/order';
});
};
this.setLanguage(this.lang);
};
angular.module('myApp').controller('LanguageCtrl', LanguageCtrl);
EDIT: what I said doesn't work, doesn't work when I use this rather than $scope!
I'm moving to the controller as syntax and everything's fine when I do this for variables, but when I try the same thing for arrays populated by an $http.get, the code breaks.
Don't care about that horrible <button onclick>, just wanted to test code postponing the style for links.
controller
var LanguageCtrl;
LanguageCtrl = function($scope, $http, $window) {
if ($window.navigator.language.indexOf('it') !== -1) {
this.lang = 'it';
this.setLanguage = 'it';
} else {
this.lang = 'en';
this.setLanguage = 'us';
}
this.message = [];
this.pizze = [];
$scope.getPizze = function(lang) {
$http.get('localization/pizze-' + lang + '.json').success(function(pizze) {
$scope.pizze = pizze;
});
};
$scope.setLanguage = function(lang) {
$http.get('localization/' + lang + '.json').success(function(data) {
this.lang = lang;
$scope.message = data;
$scope.getPizze(this.lang);
$window.location.href = '#!/order';
});
};
$scope.setLanguage(this.lang);
};
angular.module('myApp').controller('LanguageCtrl', LanguageCtrl);
index.html works
<html ng-app="myApp" ng-controller="LanguageCtrl as langctrl" lang="{{langctrl.lang}}">
order.html doesn't
<button onclick="location.href='#!/cart'" ng-disabled="howManyPizze === 0">{{langctrl.message.cart}} {{howManyPizze === 0 ? langctrl.message.empty : '(' + howManyPizze + ')'}}</button>
<button onclick="location.href='#!/'">{{langctrl.message.change}}</button>
The problem is that the self-referencing this is not available when your $http.get() resolves. That is why you'll often see var vm = this; or something similar as the very first line in a controller when using the 'Controller as' syntax. By assigning this to a local variable in the controller it gives you access when your promise resolves. In short, add...
var vm = this;
...to your controller and then change your $http.get() to this...
vm.setLanguage = function(lang) {
$http.get('localization/' + lang + '.json').success(function(data) {
vm.lang = lang;
vm.message = data;
vm.getPizze(vm.lang);
$window.location.href = '#!/order';
});
};
UPDATE
I missed this on my original answer:
$scope.getPizze = function(lang) {
$http.get('localization/pizze-' + lang + '.json').success(function(pizze) {
$scope.pizze = pizze;
});
};
That needs to be changed to eliminate the use of $scope.
vm.getPizze = function(lang) {
$http.get('localization/pizze-' + lang + '.json').success(function(pizze) {
vm.pizze = pizze;
});
};
var LanguageCtrl;
LanguageCtrl = function( $http, $window) {
var parent = this;
if ($window.navigator.language.indexOf('it') !== -1) {
parent.lang = 'it';
parent.setLanguage = 'it';
} else {
parent.lang = 'en';
parent.setLanguage = 'us';
}
this.message = [];
this.pizze = [];
parent.getPizze = function(lang) {
$http.get('localization/pizze-' + lang + '.json').success(function(pizze) {
console.log("Your language is:"+lang)
parent.pizze = pizze;
});
};
parent.setLanguage = function(lang) {
$http.get("example.json").success(function(data) {
// $scope.$apply(function(){
console.log("Your language is:"+lang)
parent.lang = lang;
parent.message = data;
parent.getPizze(parent.lang);
$window.location.href = '#!/order';
//})
});
};
parent.setLanguage(parent.lang);
};
angular.module('myApp',[]).controller('LanguageCtrl', LanguageCtrl);
Use above code to work your angular code.
Created Plukar here https://plnkr.co/edit/psOaylBtnCsLDIJydT9N?p=preview

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

My my requirement is to either display(new tab)/download/embed a PDF in my angular js app on form submit/post.
I do not want the server to return a unique identifier of the generated PDF and than use $window service to open a new window with it's url pointing to a server-side endpoint which returns PDf based on unique identifier. Because I need to generate the pdf on the fly (no storing in file system).
Similar question to this one AngularJS: Display blob (.pdf) in an angular app But it is not working for me.
My controller
angular.module('EvaluationResultsModule').controller('CA_EvaluationResultsCtrl',
[ '$scope', 'EvaluationResultsService', '$sce', function($scope, EvaluationResultsService, $sce) {
$scope.showPDF = function() {
$scope.result = CA_EvaluationResultsService.getEvalutaionResultPDF($scope.evaluationResults);
$scope.result.$promise.then(function(data) {
var file = new Blob([data], {
type : 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
$scope.pdfContent = $sce.trustAsResourceUrl(fileURL);
});
}
} ]);
My Service
angular.module('EvaluationResultsModule').factory('EvaluationResultsService', function($resource) {
return $resource('./api/ca/evaluationResults/:dest', {}, {
getEvalutaionResultPDF : {
method : 'GET',
params : {
dest : "getPDF"
},
responseType : 'arraybuffer',
}
});
});
Rest Controller Method
#RequestMapping(value = "/getPDF", method = RequestMethod.GET)
public byte[] getEvalutaionResultPDF() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Generate PDF using Jasper
Map<String, Object> model = new HashMap<String, Object>();
List<User> usersList = null; //populated from Service layer;
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(usersList);
JasperPrint jasperPrint = jasperPrint = JasperFillManager.fillReport(this.getClass().getClassLoader().getResourceAsStream("A4.jasper"), model, beanColDataSource);
JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
return baos.toByteArray();
}
My response logged in console
response: Object {data: ArrayBuffer, status: 200, headers: function, config: Object, statusText: "OK"}config: Objectdata: ArrayBufferbyteLength: (...)__proto__: ArrayBufferbyteLength: [Exception: TypeError: Method ArrayBuffer.prototype.byteLength called on incompatible receiver #<ArrayBuffer>]get byteLength: function byteLength() { [native code] }constructor: function ArrayBuffer() { [native code] }slice: function slice() { [native code] }__proto__: Objectheaders: function (name) {resource: Resourcestatus: 200statusText: "OK"__proto__: Object
I use this code and it works for me:
REST Controller:
#RequestMapping(value = "/api/reports/pdf", method = RequestMethod.GET)
#Timed
public #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.

Resources