通过iframe打印pdf(跨域)

cla*_*rkk 9 javascript

我需要打印PDF ...但是我收到错误

有解决方法吗?我只需要点击一下即可打印PDF文件

错误:

Uncaught SecurityError: Blocked a frame with origin "https://secure.domain.com" from accessing a frame with origin "https://cdn.domain.com". Protocols, domains, and ports must match.
Run Code Online (Sandbox Code Playgroud)

码:

var iframe = $('<iframe src="'+url+'" style="display:none"></iframe>').appendTo($('#main')).load(function(){
    iframe.get(0).contentWindow.print();
});
Run Code Online (Sandbox Code Playgroud)

HiD*_*Deo 6

您正在处理的错误与跨域保护和同源策略有关.

在您的情况下,如果您将此iframe嵌套在我们可以调用代理iframe的另一个本地iframe中,则可以打印跨域iframe.

由于代理iframe是本地的并且具有相同的来源,因此您可以毫无问题地打印它,并且还会打印跨域iframe.

请参阅下面的示例:

index.html(容器)

$(function() {
  var url = 'proxy.html'; // We're not loading the PDF but a proxy which will load the PDF in another iframe.

  var iframe = $('<iframe src="' + url + '"></iframe>').appendTo($('#main'));

  iframe.on('load', function(){
    iframe.get(0).contentWindow.print();
  });
});
Run Code Online (Sandbox Code Playgroud)

proxy.html(代理)

<body>
  <iframe src="http://ANOTHER_DOMAIN/PDF_NAME.pdf"></iframe>
</body>
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,您不再有跨域问题,您可以使用print()函数.您需要处理的唯一事情是将PDF URL从容器传递到代理,以及检测何时实际加载带有PDF的iframe的方法,但这取决于您正在使用的解决方案/语言.

  • 这个答案不起作用(至少在Chrome中).是的,你可以在包装器iframe上调用`print()`,但是打印预览是空白的,即使pdf内容是在内部iframe中加载的. (5认同)