如何打印动态生成的pdf dataUrl? [英] How to print dynamically generated pdf dataUrl?

查看:345
本文介绍了如何打印动态生成的pdf dataUrl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从网页上打印动态生成的PDF。

I'm trying to print a dynamically generated PDF from a web page.

var $iframe = $('<iframe>');
$iframe.appendTo('body');
$iframe.load(function() {
    var iframe = $iframe[0];
    var result = iframe.contentWindow.document.execCommand("print", false, null);
    if (!result) iframe.contentWindow.print();
    $.remove($iframe);
});
$iframe.attr('src', dataUrl);

execCommand()给出错误信息:

execCommand() gives the error message:

Uncaught SecurityError:阻止了一个包含来源
的框架 http:// localhost:2520 从访问具有原点的帧null。
请求访问的帧具有http协议,访问
的帧具有数据协议。协议必须匹配。

Uncaught SecurityError: Blocked a frame with origin "http://localhost:2520" 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.

此外,设置src attr会发出警告:

Also, setting the src attr gives the warning:

资源被解释为Document但是使用MIME类型application / pdf传输:

Resource interpreted as Document but transferred with MIME type application/pdf:

dataUrl看起来像这样:

The dataUrl looks like this:

data:application/pdf;base64,JVBERi0xLjQKJdP...

编辑:@Mike C

@Mike C

我可以创建iframe并显示pdf,但是当我打印时,它是空白的。

I can create the iframe and display the pdf, but when I print, it's blank.

<style type="text/css" media="print">
    body * { display:none }
    iframe#theframe { display:block }
</style>

var $iframe = $('<iframe id="theframe" src="'+dataUrl+'"></iframe>');
$iframe.appendTo('body');
$iframe.load(function() {
    setTimeout(function() {
        window.print();
    }, 1000);
});


推荐答案

尝试使用 window.open () document.write() setTimeout()

var popup = window.open("", "w");

var html = '<!doctype html><html><head></head>'
           + '<body marginwidth="0" marginheight="0" style="background-color: rgb(38,38,38)">'
           + '<embed width="100%" height="100%" name="plugin" src="data:application/pdf;base64,JVBERi0xLjQKJdP..." type="application/pdf">'
           + '<script>setTimeout("print()", 1000)</script></body></html>';

popup.document.write(html);

这篇关于如何打印动态生成的pdf dataUrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆