如何在Angular 2中打印Pdf [英] How to Print Pdf in Angular 2
问题描述
我有exf url的pdf文件的网址是test.example.com/incoice/1/download?auth_token=\"some_token,当我访问此网址时,网址会在浏览器中显示PDF格式。
I have URL of pdf file for exa url is "test.example.com/incoice/1/download?auth_token="some_token", when I visit this url, url will show me PDF in browser.
现在我想用打印功能打开这个pdf,我的意思是用户不必按 CTRL + P
我想做这个来自我。
Now I want to open this pdf with print function, I mean user do not have to press CTRL+P
I want to do this from my side.
我试过iframe但是它给了我错误的交叉来源。
这是我使用的演示代码
I tried iframe but it gives me error of cross origin. This is demo code which 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();
我在plunker中为print pdf创建了一个demo。 http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/ 在这个plunker中,我在新窗口中打开pdf但是我想直接打印该pdf。我怎么能这样做?
I created a demo in plunker for print pdf. http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/ In this plunker i open pdf in new window but i want to directly print that pdf. how can i do that ?
任何建议都会有所体现,如果我错了你可以纠正。
谢谢
Any suggestion will be appreciate, and you can correct if I am wrong. Thanks
推荐答案
所以我在这里得到了我的问题的解决方案
在我的情况下,我的API正在返回 pdf
的二进制数据,浏览器没有将那个二进制数据打印到window.print中,所以首先我转换二进制文件
blob
数据中的数据然后创建 iframe
打印
以下是代码。
So here I got the solution for my problem
In my situation my API was returning binary data of pdf
, and browser did not print that binary data into window.print, so for this first I convert binary
data in blob
data and then create Iframe
for print
Following is 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!! I hope this can help anyone have this problem :)
这篇关于如何在Angular 2中打印Pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!