1,372 articles and 9,185 comments as of Tuesday, February 9th, 2010

Tuesday, December 9, 2008

JQuery for Everyone: Print (Any) Web Part

Back in August, I worked on a script to print web parts to answer a question from Stump the Panel.  However, my script was not dynamic enough to adjust to the web parts on the page and create the “print this” links on the fly–I had no good ideas to tackle that problem.

The more I explore jQuery, the more ideas I get about solving old problems.  So when someone else asked for a printing solution, I decided to tackle it in jQuery.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  // Load jQuery
  google.load("jquery", "1.2.6");
</script>
<script type="text/javascript">
$(function(){
    //find all web parts by their TD
    var tags = $("td[id^='MSOZoneCell_WebPart']");
    //loop through web parts
    tags.each(function(){
        //get id for print function
        var tagid = $(this).attr("id");
        //append an image with onClick event
        $(this).find("h3 nobr").append(
            "<span style='padding-left:20px;'>"+
            "  <a href='#' onClick='printWebPart("+'"'+tagid+'"'+"); return false;'>"+
            "      <img src='/_layouts/images/nws16.gif' border='0' alt='printer friendly' />"+
            "  </a>"+
            "</span>"
        );
    });
});
function printWebPart(tagid){
    if (tagid) {
        //build html for print page
        var html = "<HTML>\n<HEAD>\n"+
            $("head").html()+
            "\n</HEAD>\n<BODY>\n"+
            $("#"+tagid).html()+
            "\n</BODY>\n</HTML>";
        //open new window
        var printWP = window.open("","printWebPart");
        printWP.document.open();
        //insert content
        printWP.document.write(html);
        printWP.document.close();
        //open print dialog
        printWP.print();
    }
}
</script>

 

Update 12/11/2008:
Dave T requested a version of this script that works with the List View Web Part (no title displays). Great idea Dave! Replace the main function with this one, notice there is a second “append” process that looks for the toolbar space instead of the title area.

$(function(){
    //find all web parts by their TD
    var tags = $("td[id^='MSOZoneCell_WebPart']");
    //loop through web parts
    tags.each(function(){
        //get id for print function
        var tagid = $(this).attr("id");
        //append an image with onClick event
        $(this).find("h3 nobr").append(
            "<span style='padding-left:20px;'>"+
            "  <a href='#' onClick='printWebPart("+'"'+tagid+'"'+"); return false;'>"+
            "      <img src='/_layouts/images/nws16.gif' border='0' alt='printer friendly' />"+
            "  </a>"+
            "</span>");
        $(this).find("td.ms-toolbar[width='99%']").append(
            "<span style='padding-left:20px;'>"+
            "  <a href='#' onClick='printWebPart("+'"'+tagid+'"'+"); return false;'>"+
            "      <img src='/_layouts/images/printerfriendly.gif' border='0' alt='printer friendly' />"+
            "  </a>"+
            "</span>");
    });
});

Paul Grenier

View all entries in this series: PaulGrenier-JQuery for Everyone»
Entries in this series:
  1. JQuery for Everyone: Accordion Left Nav
  2. JQuery for Everyone: Print (Any) Web Part
  3. JQuery for Everyone: HTML Calculated Column
  4. JQuery for Everyone: Dressing-up Links Pt1
  5. JQuery for Everyone: Dressing-up Links Pt2
  6. JQuery for Everyone: Dressing-up Links Pt3
  7. JQuery for Everyone: Cleaning Windows Pt1
  8. JQuery for Everyone: Cleaning Windows Pt2
  9. JQuery for Everyone: Fixing the Gantt View
  10. JQuery for Everyone: Dynamically Sizing Excel Web Parts
  11. JQuery for Everyone: Manually Resizing Web Parts
  12. JQuery for Everyone: Total Calculated Columns
  13. JQuery for Everyone: Total of Time Differences
  14. JQuery for Everyone: Fixing Configured Web Part Height
  15. JQuery for Everyone: Expand/Collapse All Groups
  16. JQuery for Everyone: Preview Pane for Multiple Lists
  17. JQuery for Everyone: Preview Pane for Calendar View
  18. JQuery for Everyone: Degrading Dynamic Script Loader
  19. JQuery for Everyone: Force Checkout
  20. JQuery for Everyone: Replacing [Today]
  21. JQuery for Everyone: Whether They Want It Or Not
  22. JQuery for Everyone: Linking the Attachment Icon
  23. JQuery for Everyone: Aspect-Oriented Programming with jQuery
  24. JQuery for Everyone: AOP in Action - loadTip Gone Wild
  25. JQuery for Everyone: Wiki Outbound Links
  26. JQuery for Everyone: Collapse Text in List View
  27. JQuery for Everyone: AOP in Action - Clone List Header
  28. JQuery for Everyone: $.grep and calcHTML Revisited
  29. JQuery for Everyone: Evolution of the Preview
  30. JQuery for Everyone: Create a Client-Side Object Model
  31. JQuery for Everyone: Print (Any) Web Part(s) Plugin
  32. JQuery for Everyone: Minimal AOP and Elegant Modularity
  33. JQuery for Everyone: Cookies and Plugins
  34. JQuery for Everyone: Live Events vs. AOP
  35. JQuery for Everyone: Live Preview Pane
  36. JQuery for Everyone: Pre-populate Form Fields
  37. JQuery for Everyone: Get XML List Data with OWSSVR.DLL (RPC)
  38. Use Firebug in IE
  39. JQuery for Everyone: Extending OWS API for Calculated Columns
  40. JQuery for Everyone: Accordion Left-nav with Cookies Speed Test
  41. JQuery for Everyone: Email a List of People with OWS
  42. JQuery for Everyone: Faster than Document.Ready
  43. jQuery for Everyone: Collapse or Prepopulate Form Fields
  44. jQuery for Everyone: Hourly Summary Web Part
  45. jQuery for Everyone: "Read More..." On a Blog Site
  46. jQuery for Everyone: Slick Speed Test
  47. jQuery for Everyone: The SharePoint Game Changer
  48. JQuery For Everyone: Live LoadTip
 

Please Join the Discussion

52 Responses to “JQuery for Everyone: Print (Any) Web Part”
  1. Ari says:

    In your example screenshot you have the “jQuery add images to external links”. Can you share the code, it is something I have been looking for.

  2. AutoSponge says:

    @Ari,

    Thanks for following along.

    I can show the “dress-up external links” code in my next JQuery for Everyone article. I’m finishing up a script that will also grab some file data with AJAX and/or JSON. Look for it next Tuesday.

  3. I can’t get this to work.

    I’m guessing that I’m supposed to add a content editor web part and then put the script in there but unless I stay in edit page mode only the content editor web part get’s the printer icon.

    What did I miss?

  4. AutoSponge says:

    @Martin,

    I also used a CEWP. Do you have any templates, themes, or custom code that can change the way your web parts are rendering? Open up the page source and check the web part’s ID.

    In my script with the default page, the IDs all start with MSOZoneCell_WebPart. If yours is different, that could cause the images to not appear.

  5. No custom code or themes.

    I’m using it on WSS but I fail to see why that should change anything.

    All the IDs start with MSOZoneCell_WebPart.

    I’ll tinker with it to see if there’s anything I’m missing.

  6. Mark says:

    Just to add my comments, I’m seeing this issue as well. Running vanilla MOSS/SP1

  7. This is a wonderfully helpful little script.

    Would you mind if I packaged it for use as a customisation within ShUIE?

    ShUIE is here: http://www.codeplex.com/ShUIE/ and enables fragments of JavaScript to be deployed and lit-up across your SharePoint farm from a central location.

    If you could let me know, it would be much-appreciated.

  8. AutoSponge says:

    @David,

    I’d be honored. I deployed it as an icon (near “?”) in the .master instead of firing on document.ready. Maybe that would work for ShUIE too.

    Thanks,
    ~Paul

  9. Dave T says:

    Martin,
    I am experiencing the same issue. I have tried this on a couple of sites. One with a CEWP with java and one w/o. The icon appears on other CEWP’s but not on lists or libs.

    All the ID’s start with MSOZoneCell_WebPart.

    Let me know if you get it working. I’ll do the same.

    Dave

  10. AutoSponge says:

    The problem is line 15, it should be find(”h3 nobr”). I’ll fix it above. Thanks for pointing that out.

  11. Dave T says:

    That did it! Thanks Paul!!

    Dave

  12. This is now include in ShUIE:
    http://www.codeplex.com/ShUIE/

    I’ve made a couple of very small changes.

    1) I check for jQuery as it may not have loaded in the print window and ShUIE would attempt to run again (I may well add this to ShUIE).

    2) I hide the print icon before copying the HTML into the print window, and show it again straight after copying. This means the print window doesn’t get the print icon.

    I’ve credited by putting a link straight back here, but if you have a specific license you’d like to apply you should let me know.

    Thanks,

    David

  13. Dave T says:

    Paul,
    I have found that this sweet little app works well on the homepage of site. But not on a .aspx page for a list. I thought it would be nice to create a list view called ‘Print’ and use the view to print the list. The icon appears in the Edit Page view but then disappears.

    Is there anything that can be done to make this work in the list view? Even if it means two different versions?

    Thanks for the help!!
    Dave

  14. AutoSponge says:

    @Dave T,

    Thanks for the idea. I’ve added an update to the post above with a new “main” function that I tested in FF and IE on a List View.

  15. Dave T says:

    Paul,
    It worked like a champ!! Thanks for the quick turnaround. This little app will help a LOT of my clients.

    Dave

  16. I’ve updated the ShUIE version with this functionality.

    One thing I added to the ShUIE version was to hide the print icon before copying the html, and then showing it afterwards.

    All that does is make the print out itself not have the print icon.

    Oh, and on list views I take the table and not the blue menu bar.

    This can be seen here:
    http://www.codeplex.com/ShUIE/SourceControl/changeset/view/22903

    Under: trunk > Customisations > Print (Any) Web Part

  17. Chris Quick says:

    This works great in my environment with one small exception. After I call up the page, I get the error message ‘ctx1 is not defined’ about 10 times after the web part has been printed. It may be something about how our IE is handled via group policy as we get other javascript errors on other web sites that I don’t have any problems with on my home computer.

    It also works fine under FireFox. Thx for any ideas!

  18. Chris Quick says:

    Okay… figured it out. I had multiple instances of the loading the JQuery Library. Put this into it’s own CEWP at the top of the left most column.

    <script type=”text/javascript” src=”http://www.google.com/jsapi”></script>
    <script type=”text/javascript”>
    // Load jQuery
    google.load(”jquery”, “1.2.6″);
    </script>

  19. AutoSponge says:

    You can try to supress errors in IE, I used this trick in my example for calendar preview pane:
    http://www.endusersharepoint.com/?p=1223

  20. Atish says:

    Hi ,

    I am totally new in WSS , Can you please step by step where to copy this script as i have a lot of lists in my portal .

  21. Peter Allen says:

    Has anyones else had problems with using this JQuery script to print a Excel Web Access webpart? I posted a response on another site about the is JQuery solution and they indicated that it did not work for them with the Excel Web Access webpart.

    thanks,

    Peter

  22. Kerrie Thomas says:

    Hi,
    I was wondering if you have a way to take it a step further for the following situations.
    1. I would like to use the Internet ‘Send Page as Email’ using the page that pops-up when clicking the printer icon. However, the page turns out to be a garbled mess rather than the page like it is shown visually & prints out.
    2. I would like to be able to print an entire page showing all multiple web-parts rather than printing one at a time. This would also be something I would want to send that page as an email. Currently when the Internet option is used it includes all of the top navigation, breadcrumbs, etc in the email. Not pretty at all.

    Thanks for your help. You’ve made my life easier already.

  23. AutoSponge says:

    @Peter,

    It’s on my list of things to look at to see if it can work with EWA.

    @Kerrie
    ‘Send Page as Email’ is an IE feature so I can’t change it. However, we could work from a “cleaner” CSS. I’ll put it on the list.

  24. Jerome says:

    Thanks Paul for this great article.

    However it does not seems to be working with the Excel Web Access Web Part.

    whenever the popup window shows up, it’s empty.

    Any advice ?

    Thanks,

    Jerome

  25. Kerrie Thomas says:

    I was trying to use this for a web part that has coloring on the items which is dynamically built based on the data coming into the web part. The problem I’m running into is that when I print the page, none of the coloring is printing. Any thoughts?

  26. Peter Allen says:

    Does the color show up in the print view? If yes then it may have to do with the CSS being applied. Color is funny thing with CSS. What are you coloring in your web part?

  27. AutoSponge says:

    @Kerrie

    The problem is probably caused by a script that the web part needs render the colors (CSS, JavaScript or both) and it is not being copied to the new page because it does not live the HEAD of the original page.

    After you identify the code needed for render you’ll either need to target it for copy or hard-code it into this script. By making it part of the html variable, it will make its way to the new page.

  28. Paul says:

    Hi Paul,

    Is there a way to strip off the Toolbar from the print page? I’m trying to remove as much real estate as possible so the main content (calendar month view) can print on one page. I need the full tool bar on the actual page, just want it removed from the print page.

    thanks in advance

  29. Peter says:

    Paul,

    I will let Paul answer the question about his code. I have a found another way to print pages by hiding aspects of the page with CSS styles.

    If you go to this example: http://www.bitsofsharepoint.com/ExamplePoint/Site/PrintCleanPage.aspx

    It will show you code for printing a clean page by stripping the site of CSS styles. So you would only need to add the .ms-globalTitleArea, .ms-toolbar, and .ms-menutoolbar in the section of the code where it lists CSS styles to hide. This could work.

    Here is an example that I setup: http://www.bitsofsharepoint.com/ExamplePoint/Site/CalendarPrint.aspx

  30. AutoSponge says:

    @Paul

    With this script, the easiest way to do that is probably to alter the html variable. Add a CSS style tag with .ms-toolbar {display:none} inside. That way, when you write the html to the new page, the new CSS will apply only there.

  31. Paul says:

    Thanks Peter & Paul (where’s Mary?). That worked.

  32. Paul says:

    Back with one more question: is there any css tag for the exclusion of the days from the previous and next months? For example, if you look at a month view for the current month of March 2009, you get row at the top that has all business days in February since Sunday was March 1st, despite having set my first day of week to Monday on regional settings.

    thanks again,
    Paul

  33. AutoSponge says:

    You can use some jQuery to hide the items not in the current month but not the grid boxes themselves.

    $(”td.ms-cal-nodataMid>table”).hide()

    That will hide an event appearing in a “shaded” box.

  34. Paul says:

    Thanks again Paul – I’m not seeing the desired result – the events in the shaded boxes still appear. Is this correct?

    // Load jQuery
    google.load(”jquery”, “1.2.6″);

    // Hide events from previous and next month – the shaded boxes
    $(”td.ms-cal-nodataMid>table”).hide()

    Or do I need to wrap it in a function?

  35. Paul says:

    for some reason is truncated – here is the full code from the WP

    // Load jQuery
    google.load(”jquery”, “1.2.6″);

    // Hide events from previous and next month – the gray boxes
    $(”td.ms-cal-nodataMid>table”).hide()

  36. Paul says:

    disregard previous – I’m all set now. thanks

  37. Amanda says:

    Hi there. I have two comments/questions.

    1. I am using hex codes to color code my calendar list. Is there any way to print the calendar in color? When I click the page icon, the pop up is in color, but going to Print Preview, the calendar is back to black/white.

    2. Since I am color coding my calendar, I also have a CEWB with a color key. I want both that and the calendar to print on the same page. When I used the clean print page code, I did not get all my calendar entries on my print screen – although did get both my color key and the calendar. I tried to EXPAND ALL prior to clicking printer icon, but the calendar collapsed itself again. When using the print any webpart code, I was able to expand all and have all items on my printout, but no color key.

    Is there a way to have a clean print page that will show all calendar entries (the expand option ’sticks’) OR is there a way to use the print any webpart code and get both the CEWB and the calendar to print on the same page?

    Any help would be wonderful!
    Amanda

  38. Petr says:

    Error in IE8

    //open new window
    var printWP = window.open(”",”printWebPart”);
    printWP.document.open();
    //insert content
    printWP.document.write(html);
    printWP.document.close();
    //open print dialog
    printWP.print();

  39. dan says:

    Is there away to make this work with Excel Web Access?

  40. Mindbenda says:

    I do not use a masterpage only an aspx, so the webparts don’t have the MSOZoneCell_WebPart ID.
    Is there a workaround?

  41. Josi Montero says:

    Paul,

    I love everything you do!!!! The printing feature was a much needed feature!!!

    I have a question, I apologize if it’s a dumb one…, in my defense, I’m one of the common normal people, most of the time just trying to catch up with what you’re all taking about!

    I have Christophe’s Easy Tabs on my page, and I see the printer frindly icon on edit mode when I add your code to a content editor wp but when I get out of edit mode it’s gone!

    Is there anything I can do? or these two just won’t go together?

    They are absolutely fantastic together! they keep a page functional, neat, and simple!

    Thanks so much!

    Josi

  42. TrackVino says:

    Is there a way of using this in a basic page? A basic page doesnt have any webparts, just a built in text editor. I can add a CEWP thru SharePoint Designer and add the script, or embed it into the page itself, but the script is looking for a web part to print.

    Do you think this is possible?

    Thanks

  43. AutoSponge says:

    @TrackVino,

    The PrintWebPart function will print any container by ID. Just create a link with an href=’printWebPart()’ on the page.

  44. Nate says:

    This just results in a “Error on Page” message in the IE status bar for me. I used the revised code from 12/08 and am attempting to print a custom list in a group by view.

    Any help appreciated!

  45. AutoSponge says:

    @Nate,

    The second block of code is not a straight copy/paste, it replaces the “body” of the previous version. Do you still have the SCRIPT tags in place?

  46. Nathan says:

    I’d like to echo Josi’s comment… Great feature, but I would also love to incorporate it into Christophe’s EasyTabs. Many thanks for sharing your work.

  47. Rob van der Geer says:

    Just found this wonderful script and know we will benefit a lot from your work!
    Thank you for that!

    Do you think there is a way to print all webparts in a single webpart zone?
    For meetings we create a page with an agenda, tasklist, etc. If attendees want to print this, they can only print the entire page (with navigation, etc.) or, thanks to you, the seperate webparts.

    We would like a way to print all webparts in a specific webpart zone with only 1 click.
    Can such thing be done?

  48. Yin says:

    Hi Paul,

    Thank you for the script!
    Could you teach me how to upgrade it to Jquery 1.3.1.
    I want to put in with another Jquery script(1.3.1) into one page.

  49. AutoSponge says:

    @Yin,

    There’s nothing in there that would prevent a newer jQuery version from working. I suggest replacing the original first 5 lines with:

    <script type="text/javascript">
    if(typeof jQuery=="undefined"){
    	var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/";
    	document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
    }
    </script>
    

Trackbacks

Check out what others are saying about this post...
  1. [...] had a request from Ari in our last installment of JQuery for Everyone!  Ari wants to know how to add fancy “this is an external link” icons to his page.  [...]

  2. SharePoint Kaffeetasse #98…

    Tools und Addons Custom Content Editor Web Part for SharePoint jQuery http://jquery.com/ jQuery is a…

  3. [...] improved the Print Any Web Part code and, once again, made it “plugin-style.” Now you can write your own links by using a [...]




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!