我有 pdf 文件的 URL,因为 exa url 是“test.example.com/incoice/1/download?auth_token="some_token”,当我访问这个 url 时,url 将在浏览器中显示 PDF。
现在我想用打印功能打开这个 pdf,我的意思是用户不必按 CTRL+P
我想在我这边做这件事。
我尝试了 iframe,但它给了我跨源错误。 这是我使用的演示代码
//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 中创建了一个用于打印 pdf 的演示。 http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/在这个 plunker 中,我在新窗口中打开 pdf,但我想直接打印该 pdf。我该怎么做?
如有任何建议,我将不胜感激,如有错误,请指正。 谢谢
最佳答案
所以在这里我得到了我的问题的解决方案
在我的情况下,我的 API 返回 pdf 的二进制数据
,而浏览器没有将该二进制数据打印到 window.print 中,因此首先我将 binary
数据转换为 blob
数据,然后创建 Iframe
用于打印
以下是它的代码。
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();
});
给你!! 我希望这可以帮助任何人遇到这个问题:)
关于javascript - 如何在 Angular 2 中打印 Pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44244148/