Πέμπτη 23 Αυγούστου 2012

Print a div with javascript which opens in a new window using Javascript

Today I had to put a print button into a web application, which when clicked, should open a new window and print the contents of a certain div.

I found this very useful link http://sarwarhossain.com/2010/10/05/print-a-div-open-new-window-print-and-close-using-javascirpt/. I used the code and everything worked great in Firefox, but I noticed that it doesn’t work well with Chrome, launches straight to blank Print screen and doesn’t load content in new window first. Same in Safary (I didn't try IE, I was sure that it wouldn't work as well).

Here is the code I found from the above link and right after I will post 2 solutions for this problem.


Javascript Function

HTML


1st solution 

The first thing I thought was to remove following lines
in order to let Chrome and Safari open the new window with print button in the contents, but this relies on user to manually push print. I found this thought in the comments area too.

Everything worked great, but I wanted to open the new window and after that automatically invoke the print dialog window. So I did the following.


2nd solution

I just put onLoad=”self.print()” inside body element and everything worked like a charm:-) See the new code of the printContent function below. Hope it helps!

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου