简体   繁体   中英

Printing only the contents of an iframe when a user selects file->print

Problem:

I have an application which loads content from other servers into an <iframe> . Users want to be able to print the content in the iframe, which can sometimes be quite long and cause the iframe to scroll. When the print, only the area shown in the iframe's viewport is printed. The rest is cut off.

What I've tried:

Using @media print styles, I can hide all the other elements on the page and expand the iframe to 100% width and height. What I can't do AFAICT is resize it to the w/h of the actual content (using CSS alone), so if 100% isn't enough the content is truncated.

I know this is solvable via javascript, but browsers do not consistently offer an event hook for file->print, so I can't run the javascript when it's needed.

I could make a custom "print" button, so that the JS could run and the iframe would be correctly printed, but it doesn't allow for "Print Preview", because browsers don't offere a JS method for this.

I'm stumped here, is there an answer?

If you want to print the contents of your iframe you can use

document.getElementById('ifr1').contentWindow.print()

This will call the print() on the contents of the iframe (and not the container window).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM