我有 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/ http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/在此plunker中,我在新窗口中打开pdf,但我想直接打印该pdf。我怎样才能做到这一点 ?
任何建议将不胜感激,如果我错了,您可以纠正。
谢谢
所以在这里我得到了我的问题的解决方案
在我的情况下,我的 API 正在返回binary data of 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();
});
干得好!!
我希望这可以帮助任何遇到这个问题的人:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)