Print preview from multiple iframes?

2019-02-18 17:56发布

问题:

I have several iframes in a page. I want to show in a print preview all the iframe contents as snapshots of iframes. I used window.print() for individual iframes, and it's working fine, but how do I do it for multiple frames?

回答1:

You need to focus all frames one-by-one and merge in print report.

You can achieve it, with this code:

HTML:

<button id="printButton" onclick="javascript:printPage()" >Print this page</button>

<h1 id='header'><b>Awesome Print Report</b></h1>
<iframe id="ifr1" src="http://amazon.com"></iframe>
<iframe id="ifr2" src="http://amazon.com"></iframe>
<iframe id="ifr3" src="http://amazon.com"></iframe>
<iframe id="ifr4" src="http://amazon.com"></iframe>
<iframe id="ifr5" src="http://amazon.com"></iframe>
<iframe id="ifr6" src="http://amazon.com"></iframe>

JavaScript:

function printPage() {

    window.print();

    for (var k = 0; k < window.frames.length; k++) {
        window.frames[k].focus();
        window.frames[k].print();
    }

}

CSS:

#header {
    margin - top: 20px;
}

@media print {
    #printButton {
        display: none;
    }
}

This CSS will hide print button on printed report.

Here is JsFiddle for you: http://jsfiddle.net/zur4ik/r7pvF/



回答2:

May this code helpful for you..

HTML:

<input type="submit" value="Print All"
  onclick="javascript:printall()"
/>
<p>Hi! I'm a report!</p>
<iframe id="frame1" src="http://indiabix.com"></iframe>
<iframe id="frame2" src="http://indiabix.com"></iframe>
<iframe id="frame3" src="http://indiabix.com"></iframe>
<iframe id="frame4" src="http://indiabix.com"></iframe>

Script

function printall() {
  window.print();
  for (var i=0; i<window.frames.length; i++) {

    window.frames[i].focus();
    window.frames[i].print();
  }
}

Fiddle : http://jsfiddle.net/ackMC/5/



回答3:

If iframe previews may be just static images, you can do the following:

  • provide hidden image (with preview) next to each iframe
  • provide separate CSS file for printer using media queries
  • in this file, hide the iframes and show the images

If you do it like this, you will have images with previews instead of iframes in print view.



回答4:

I think the biggest problem here is getting content from different frames into one view, which can be printed. Wether you want this in a .pdf or with window.print(). Is it possible for you to get the content of all frames which need to be printed into one document (frame)? For instance With AJAX, cURL, or PHP-methods? I think that's the only way to make one printable document of it.

Good luck!