How to Print Pdf in Angular 2
我有pdf文件的网址,例如exa的网址是" test.example.com/incoice/1/download?auth_token="some_token",当我访问该网址时,该网址将在浏览器中显示PDF。
现在,我想用打印功能打开此pdf文件,这意味着用户不必按
我尝试过iframe,但它给了我跨源错误。
这是我使用的演示代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //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 onloadx="window.print()">dddd</body>'); newWin.document.close(); |
我在plunker中创建了一个用于打印pdf的演示。 http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/在此插件中,我在新窗口中打开pdf,但我想直接打印该pdf。 我怎样才能做到这一点 ?
任何建议将不胜感激,如果我错了,您可以纠正。
谢谢
所以在这里我找到了解决问题的方法
在我的情况下,我的API返回了
以下是它的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); }); |
干得好!!
我希望这可以帮助任何有此问题的人:)
看看https://github.com/devintyler/real-time-angular2/tree/master/plugin/print-pdf
简单而美观的实现。