How to print Pdf in Angular 2
I have a pdf file url for exa url: "test.example.com/incoice/1/download?auth_token=" some_token "when I find this url the url will show me the PDF in the browser.
Now I want to open this pdf with print function, I mean the user doesn’t need to click CTRL+P
I want to do it from my side.
I tried iframe but it gives me a cross origin error. This is the demo code I used
//first try
let _printIframe;
var iframe = _printIframe;
if (!_printIframe) {
iframe = _printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.id = "printf";
iframe.name = "printf";
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
// second try
// SRC of pdf
iframe.src = "Some API URl " + "/download?access_token=" +
this.authenticationService.currentTokenDetails.access_token;
let url = iframe.src + "&output=embed";
window.frames["printf"].focus();
window.frames["printf"].print();
var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();
I created a demo in plunker for pdf printing. http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/ In this plunker, I open a pdf in a new window, but I want to directly print this pdf. How can i do this?
Any suggestion would be appreciated and you can correct if I am wrong. Thanks to
So I got a solution for my problem In my situation, my API was returning binary data of pdf
and the browser was not printing this binary data to window.print, so for that I first convert the data binary
to data blob
and then create Iframe
to print Below is the code for it.
const url = request URL // e.g localhost:3000 + "/download?access_token=" + "sample access token";
this.http.get(url, {
responseType: ResponseContentType.Blob
}).subscribe(
(response) => { // download file
var blob = new Blob([response.blob()], {type: 'application/pdf'});
const blobUrl = URL.createObjectURL(blob);
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = blobUrl;
document.body.appendChild(iframe);
iframe.contentWindow.print();
});
Here you go! Hope this can help any problem :)
Have a look at https://github.com/devintyler/real-time-angular2/tree/master/plugin/print-pdf
simple and pleasant implementation.