通过iframe打印pdf(跨域) [英] print a pdf via iframe (cross domain)

查看:1497
本文介绍了通过iframe打印pdf(跨域)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



有解决方法吗?我只需要一键打印PDF文件



错误:



  Uncaught SecurityError:阻止具有原点https://secure.domain.com的框架访问具有原始https://cdn.domain.com的框架。协议,域和端口必须匹配。 



代码:



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


解决方案

您正在处理的错误与交叉错误有关域保护和同源策略。



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



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



请参阅下面的示例:



index.html(容器)

  $(function(){
var url ='proxy.html'; //我们没有加载PDF,而是一个加载PDF的代理另一个iframe中的PDF。

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

iframe.on('load',function(){
iframe.get(0).contentWindow.print();
});
});

proxy.html(代理)

 <身体GT; 
< iframe src =http://ANOTHER_DOMAIN/PDF_NAME.pdf>< / iframe>
< / body>

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

I need to print a PDF... But I get an error

Is there a workaround? I just need to print a PDF file with one click

error:

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.

code:

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

解决方案

The error you are dealing with is related to cross-domain protection and the same-origin policy.

In your case, you can print an cross-domain iframe if you nest this iframe in another local iframe that we can call a proxy iframe.

Since the proxy iframe is local and have the same origin, you can print it without any issue and it'll also print the cross-domain iframe.

See below for an example:

index.html (container)

$(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();
  });
});

proxy.html (proxy)

<body>
  <iframe src="http://ANOTHER_DOMAIN/PDF_NAME.pdf"></iframe>
</body>

With this solution, you no longer have cross-domain issues and you can use the print() function. The only things you need to deal with are a way to pass the PDF url from the container to the proxy and a way to detect when the iframe with the PDF is actually loaded but these depends on the solution / languages you're using.

这篇关于通过iframe打印pdf(跨域)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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