javascript 如何打印base64 pdf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33900689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a base64 pdf?
提问by user2796982
I receive a base64 pdf from the server which I want to print.
我从要打印的服务器收到一个 base64 pdf。
I have been trying the following:
我一直在尝试以下方法:
$.ajax({
type: "POST",
url: url,
data: blahblahblah,
success: function(data) {
var printWindow = window.open( "data:application/pdf;base64, " + data );
printWindow.print();
}
});
Sadly, this does not work in Chrome. I am receiving the following error:
遗憾的是,这在 Chrome 中不起作用。我收到以下错误:
SecurityError: Blocked a frame with origin "xxx" from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.
SecurityError:阻止了来源为“xxx”的框架访问来源为“null”的框架。请求访问的帧具有“http”协议,被访问的帧具有“数据”协议。协议必须匹配。
Suggestions on how to work around this?
关于如何解决这个问题的建议?
回答by Ricardo Pontual
You can try to open your window and try to insert the pdf data as embed.
您可以尝试打开窗口并尝试插入 pdf 数据作为嵌入。
Here is an piece of code I've found and used fine (I changed to fit on your code, but not tested):
这是我找到并使用得很好的一段代码(我已更改以适合您的代码,但未经过测试):
$.ajax({
type: "POST",
url: url,
data: blahblahblah,
success: function(data) {
var winparams = 'dependent=yes,locationbar=no,scrollbars=yes,menubar=yes,'+
'resizable,screenX=50,screenY=50,width=850,height=1050';
var htmlPop = '<embed width=100% height=100%'
+ ' type="application/pdf"'
+ ' src="data:application/pdf;base64,'
+ escape(data)
+ '"></embed>';
var printWindow = window.open ("", "PDF", winparams);
printWindow.document.write (htmlPop);
printWindow.print();
}
});
Hope it helps.
希望能帮助到你。
回答by Muhammad Fahad
you can use jspdf to do this like
你可以使用 jspdf 来做到这一点
var p=new jspdf();
p.addImage(imgData, 'JPEG', 0, 0); // where imageDate contains base64 string