print a pdf via iframe (cross domain)

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.


There is a workaround for this.

  1. Create an endpoint in your server to return the HTML content of the external url. (because you can't get external content from the browser - same-origin policy)

  2. Use $.get to fetch the external content from your URL and append it to an iframe.

Something similar to this:

HTML:

<div id="main">
    <iframe id="my-iframe" style="display:none"></iframe>
</div>

JS:

$.get('https://secure.domain.com/get-cdndomaincom-url-content', function(response) {
    var iframe = $('#my-iframe')[0],
        iframedoc = iframe.contentDocument || iframe.contentWindow.document;

    iframedoc.body.innerHTML = response;
    iframe.contentWindow.print();
});

C# implementation for get-cdndomaincom-url-content:

Easiest way to read from a URL into a string in .NET

Tags:

Javascript