Angularjs open base64 pdf in new tab
A nice question!
To open a Base64-encoded PDF in a new tab using AngularJS, you can use the following approach:
-
First, create a function that takes the Base64-encoded PDF string as an argument and returns a URL that can be used to open the PDF in a new tab.
function openPdfInNewTab(pdfBase64) { return 'data:application/pdf;base64,' + pdfBase64; }
This function takes the Base64-encoded PDF string and returns a URL that starts with
data:application/pdf;base64,
, followed by the Base64-encoded PDF data. -
Next, use the
ng-click
directive to call theopenPdfInNewTab
function when a button or link is clicked.<a ng-click="openPdfInNewTab(pdfBase64)" target="_blank">Open PDF</a>
In this example,
pdfBase64
is the Base64-encoded PDF string that you want to open in a new tab. -
Finally, make sure to inject the
$window
service into your controller or directive, so that you can use theopen
method to open the new tab.angular.module('myApp').controller('MyCtrl', function($window) { //... function openPdfInNewTab(pdfBase64) { var url = openPdfInNewTab(pdfBase64); $window.open(url, '_blank'); } //... });
In this example, the
openPdfInNewTab
function is called when the button or link is clicked, and it uses the$window
service to open the new tab with the Base64-encoded PDF URL.
Here's the complete code:
<a ng-click="openPdfInNewTab(pdfBase64)" target="_blank">Open PDF</a>
angular.module('myApp').controller('MyCtrl', function($window) {
var pdfBase64 = 'your-base64-encoded-pdf-string';
function openPdfInNewTab(pdfBase64) {
var url = 'data:application/pdf;base64,' + pdfBase64;
$window.open(url, '_blank');
}
});
This should open the Base64-encoded PDF in a new tab when the button or link is clicked.