user1931386
user1931386

Reputation: 11

AngularJS Opening PDF in New tab

I am very new to AngularJS. I need help to get out of the below situation mentioned. I am trying to open an PDF file in new tab on button click. The code i am working around is below. The new tab does not open up. Any guidance will be highly appreciated.

$http.get('/api/services/downloadpdf/' + scope.invoice.id, { responseType: 'arraybuffer' }).then(function (response) {
    var file = new Blob([response.data], { type: 'application/pdf' });
    file.name = 'invoice.pdf';
    var fileUrl = URL.createObjectURL(file);
    $window.open(fileUrl);
});

Upvotes: 1

Views: 2926

Answers (2)

byteC0de
byteC0de

Reputation: 5273

If you have file link just give like this, In html

<a target="_target" href="invoice.pdf" role="button">View</a>

In controller use this

$http.get('/api/services/downloadpdf/' + scope.invoice.id, { responseType: 'arraybuffer' }).then(function (response) {
    var file = new Blob([response.data], { type: 'application/pdf' });
    file.name = 'invoice.pdf';
    var fileUrl = URL.createObjectURL(file);
    $window.open(fileUrl, '_blank');
});

Upvotes: 2

Kartik Patel
Kartik Patel

Reputation: 310

You can try with following code

var fileName = response.headers('content-name');
var blob = new Blob([response.data], {type: 'application/pdf'});
var url = window.URL.createObjectURL(blob);

linkElement.setAttribute('href', url);
linkElement.setAttribute("download", fileName);

var clickEvent = new MouseEvent("click", {
      "view": window,
      "bubbles": true,
      "cancelable": false
});
linkElement.dispatchEvent(clickEvent);

Upvotes: 0

Related Questions