I recently built a SharePoint (SP) Visual Web Part (VWP) with two calendar controls and a literal control. The calendar controls are used to filter the content of a specific list and the results are displayed in the literal control.
The literal control only has the “text” property for its content and no formatting attributes. You can build your content in the literal control with html tags and, in that way, get the display results you want.
So - how do I get my nicely formatted content printed? More specifically, how do I get the literal control content printed easily without 1) cutting and pasting into a document; 2) selecting the desired text and chooding “Selection” from the print dialog; or 3) printing the page without the calendar controls on the printed page?
I tried a few less complicated approaches before hitting on the one that works well for me.
Approach 1. Assign print attribute to an existing button.
In this approach you create a button in your visual web part. On PageLoad you add an attribute to the button that adds the “onclick” method with the “window.print” action.
When you click ‘btnPrint’ then the print dialog is generated and you can print the page.
I think this is a very common approach because it is all over the web and is very easy to implement.
The problem with this approach is that it prints the entire page. So if you have other controls or text on the page you don’t want printed (like my calendar controls) this approach will not work.
The above code will not compile unless it is properly concatenated or on one line. It is displayed like this for readability.
So what is the problem with this code? Well, unfortunately what gets inserted as literalcontrol.text is not dynamic. This button attribute is set on page load and whatever is in the literal control at that point is what will be writtent into the html document and printed.
Approach 3. Write the print action into the literal control text.
In the above code I define string “rpt” so that I can put in a report header text with a different format from that which is put in the literal control. Also, the rpt variable is really “bookended” with ‘html’ and ‘body’ tags, but unfortunately those tags do not displayed in this post.
To minimize confusion with all of the single and double quotes, I build up my link one component at a time (rpt, then href, then link).
The end result is that the “Print…” link creates a temporary html page with the content I want with the format I want and generating the print dialog box as well. Once printed, the temporary html document disappears and you are back to the page where you started.