Printing web pages & a new jQuery print plugin

by Cedric Dugas on January 3, 2011

Printing is becoming more and more obsolete these days, however most websites still do offer a print stylesheet . Print stylesheets are rarely perfect, when you start disabling some parts of your website you’re bound to forget to disable a div and your layout will probably give you an headache.

Making a site print friendly

There is generally 2 way used for making a website print friendly. Your first option is to use the technique I’ve talked before and make a print stylesheet directly in your website, and you disable everything that is not relevant content.

Generally it becomes rapidly a mess, unfortunately disabling every parts of your website can be tedious, and you are at the mercy of odd IE behaviors because of divs multiplication, css float properties, website updates and others small thing that make the life of a front-end developer miserable for print.

Your second option, and the one I find best suited in most cases, is to create a template with only the page content that you want to print. You add a button on your page and your open in a popup your special print page and call window.print() on page load.

Now call me an idiot, but I never really thought about the fact that window.print could be used to render an iframe instead of a popup. After a quick look on the internet, I found out that I could in fact render iframes from any page (if they are on the same domain of course..).

Introducing a jQuery printing plugin

Download the source code View demo

Now I know there are already plugins to prints parts of your page. That being said the idea behind this plugin is that instead of opening a popup, the plugin creates an iframe and print it directly! This way you save yourself (and your users) the hassle of dealing with a new window.

Also, because you still link to your popup, if some of your users have javascript disabled, they could still open the special template and print it.

Using it

$(".btnPrint").printPage()

Optional

There are some options available:
url: Overwrite the automatic url fetching in the href attribute
attr: change the default href attribute that is used to retrieve the print page URL.
message: The text message displayed before the print page is loaded

That’s it

I realize that you don’t always want a print button on your pages, but generally if you don’t need a button it is probably not that important too, and you can still have a print style sheet on your website that get you 90% there. One good example would be a recipe page, where you need a perfect print template and where this technique could be really useful.

Have a look at the demo, it is pretty self-explanatory, hope you guys like it.

Tested on:
Firefox 3.6
IE 7&8
Chrome latest

** I use a data url background image and some CSS3 properties for the little warning box, you might want to have a look if you care about IE



26 comments

nice job sir. Thank you. I really needed this plugin.

by Bogdan on February 5, 2011 at 4:52 am. #

Good work mate. Keep them coming!

by Rahul on February 17, 2011 at 4:49 am. #

Clever, smart & simple.
Exactly the kind of script that I was looking for our invoice online app.
Thanks for the good work!
F.

by Kidd on March 26, 2011 at 5:10 am. #

very nice jquery.
only two remarques.
I use this to print out div’s on a page that have max width of the page.
if I hide the page to print it, then I see the div’s are scalled.

and is there any way to use this in a submit button like :

thanks
didier

by Didier on April 29, 2011 at 7:39 am. #

I agree with another comenters

by finanse on May 9, 2011 at 1:26 pm. #

nice script! but found error through js console: overfow…

by nicmare on June 23, 2011 at 7:47 am. #

Hi, this plugin is a success. Just wondering if there are any callback function after the user click the ‘ok’ button in print dialog box?

by Jose Carlo Quilala on July 4, 2011 at 9:54 pm. #

@Jose Unfortunately I don’t think you have access to that kind of data, tryied a search on google, but found nothing

by Cedric Dugas on July 5, 2011 at 6:27 am. #

Cedric,

My need for printing is to print a defined element. In my case that element contains dynamically rendered info so printing a full page on the server won’t help.

Can I accomplish this here ? Can I just grab a ‘div’ id and print it using this plugin.

It looks great. Love the way it works.

Jay
Owner
CompuMatter

by Jay Lepore on July 13, 2011 at 4:43 pm. #

Hi, I’m taking this error:

Unsafe JavaScript attempt to access frame with URL http://www.mydomain.com/iframe.html from frame with URL http://www.mydomain.com/page.php. Domains, protocols and ports must match.

Uncaught TypeError: Object [object DOMWindow] has no method ‘print’

What it could be the problem?

by Panos on July 11, 2011 at 10:27 am. #

Thank for the consice code. One question: in the demo the web iframe.html can be printed. If I just want to the page index.html itself. How to modify the code?
I tried:
Print!
It seemed to be not working.

by ardmore on July 21, 2011 at 3:35 pm. #

Hi, great plugin
thanks a lot. you reduced my work to 80%

by graphicmist on December 1, 2011 at 4:40 am. #

hi, nice work! How about extending it with abilities to generate dynamic page to print. eg using a ‘print_template.php’ and passing content to it ?

by phil on December 20, 2011 at 11:42 am. #

Is there a way to print without clicking the btnPrint link? ie: PrintPage (‘url here’).

Ex:
$.ajax({
type: “POST”,
url: “bd/insert.php”,
data: formdata,
success: function(msg){
resetForm(“form1″)
document.getElementById(‘done’).focus();
PrintPage (‘url here’)
}
});

txs.

by henriques on December 22, 2011 at 10:55 pm. #

Great script.
Is there a way to print directly for a Form without clicking the btnPrint link?
Thank you,
Regards.

by Joaquim on December 27, 2011 at 1:01 pm. #

Hi Cedric,

This is a great plugin…
But, is there a way to execute this using a button?
I tried using window.location and window.location.href
in the onclick event of the button but it didn’t work for me.

Thank you.

by Aldrin Butcon on January 11, 2012 at 10:33 pm. #

This is very a very cool script, Thank You! love jQuery…

It’s printing two pages when there is only one to print though. I can’t seem to see any reason for it in the script, am I missing sometihng?

by Stewart on February 13, 2012 at 3:20 pm. #

CSS I had linked to was causing it. Prints fine now.

by Stewart on February 13, 2012 at 6:41 pm. #

Hi, I am using this, seems great. but in my case the print message box won’t go away after printing

by Craig on February 16, 2012 at 9:39 am. #

hi i like the example.. but i have to do like break a page into pages and the print the all break pages….at the same time on different page number at the time print.

by Rahul Kumar on March 15, 2012 at 3:03 am. #

en: nice plugin, good work whith any brousers, but not work in Opera. I try fix problem whith opera, but can’t find what cand the problem.
ru: Плагин хороший, удобный, но с Оперой большие проблемы. Фокус созданному фрейму не передаётся из-за чего на печать выводит текущую страницу. Пытался пофиксить сам, но так и не понял в чём беда. В результате решил проверять что за браузер и перенаправлять оперианцев на нужную страницу, с которой они ручками сами печатают. Вот такая бяка.

by Александр on March 23, 2012 at 12:27 pm. #

I like samples

by Alex Grafik on March 29, 2012 at 11:56 am. #

Hey ,

Its great but i am facing a problem in IE8. The problem is that on clicking the button ajax loader comes but the Print Preview doesn’t comes and on refreshing the page the Print Preview comes don’t know what’s the actual problem is .
Please tell me ASAP.

Thanks
Amir Khan

by Amir Khan on May 10, 2012 at 2:10 am. #

Great Plugin!

I need to print about 20 links as one print job.
This is probably not too efficient, But I want all 20 links opened up as hidden iframes then all printed to one print dialogue with page breaks between each iframe.

Has anyone done this? and want to share? I will attempt it. Ill let you know.

by Martin on May 24, 2012 at 3:45 am. #

Your plugin has a very big bug.

http://stackoverflow.com/questions/10997481/jquery-print-plugin-load-everytime-when-i-made-click/

due to ajax call

by Shahid on June 12, 2012 at 12:57 pm. #

I responded on the thread

by admin on June 13, 2012 at 6:33 am. #