如何打印动态生成的pdf dataUrl

How to print dynamically generated pdf dataUrl?

本文关键字:pdf dataUrl 动态 何打印 打印      更新时间:2023-09-26

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

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()给出错误信息:

Uncaught SecurityError: Blocked a frame with origin"http://localhost:2520"访问原点为"null"的帧。请求访问的帧具有"http"协议,该帧为access有一个"data"协议。协议必须匹配。

同样,设置src attr会给出警告:

资源被解释为文档,但使用MIME类型application/pdf:

dataUrl看起来像这样:

data:application/pdf;base64,JVBERi0xLjQKJdP...
编辑:@Mike C

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

<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);