Thursday, June 9, 2011

Print another webpage or image from this page javascript

Pretty simple solution for this I found with slight modifcation.

Place this code with 'otherpage.jpg' as the one you want to print, whether an image or webpage (could even be pdf) and it will prompt for printing when clicked on the button below the code

<script type="text/javascript" >
function printExternal() {
printWindow = window.open(  "otherpage.jpg","mywindow");
setTimeout('printWindow.print()', 2000);
setTimeout('printWindow.close()', 2000);
}
</script>

As you see the first step is to open the page (can be html,  pdf, jpg or other image, etc).
Second step (after short wait of 2 seconds) start the print built-in javascript function.
Third and final is to close that window after print or canceled.

Now here's how to trigger the external print:
<input type='button' value='print' onclick="printExternal()">


The code can also be modified to have much more customized pages (this is how I use it):
<script type="text/javascript" >
function printExternal(str) {
printWindow = window.open(  str,"mywindow");
setTimeout('printWindow.print()', 2000);
setTimeout('printWindow.close()', 2000);
}
</script>

As you see there is now str instead of direct image or file, this allows the function to take it dynamically from page code, now using your favourite server side language you can generate the files from a database (which is what I do in my case with php):

<?php
//this function to get the files
$files = files();

//loop through them
foreach($files as $file){ ?>
<input type='button' value='print' onclick="printExternal(<?php  echo $file ?>)">
<?php } ?>

anyway hope this php didn't confuse you but should help in basic scenarios too.

Comment and let me know if you have questions, comments etc.

5 comments:

Laura said...

Hi, I just tried this code on my website and it works beautifully! Thank you!

I was looking for an easy way to print a coupon from my page.

Thanks again,
Laura

Hemal said...

Hi, I tried this code but this doesnt work on IE 9 or the latest version of Chrome. But yep, it did work on Firefox. Do you have any clue why that happened? Or a solution if that helps this work in both IE 9 and latest versions of Chrome?

Anonymous said...

How will you modify it if you are working from a template page(working in dreamweaver? My coupons are going to change with different businesses, so how would you go around that? thanks, so far yours is the easiest print to apply:)

Unknown said...

This works great! Do you know how to alter it so it works on the Ipad? It just simply opens the new page on an Ipad... you would be helping so much if you could point me in the right direction!

Unknown said...

Hi,

This really works, thank you...!