views:

1088

answers:

3

All,

I have a html string held in memory after transforming to my desired template with XSLT. What is the best mechanism to the send this to the client printer?

In previous projects I have shamelessly cheated and created a print preview scree which was essentially an ASPX page stipped to a white background that I then printed using Window.print().

Cheers

+1  A: 

Look at CSS media selectors. You can use them to create a single page the looks how you want on the screen and also prints nicely when the user chooses print in the browser.

Joel Coehoorn
+4  A: 

I don't think a 'print preview' is cheating at all. Since your string is most likely on the server (ie created in ASP.NET code-behind), you must output it to the client somehow and call window.print() to print. There's no way for a webserver to access a client's printers. However you may be able to streamline things using a few tips:

-use @media tags in CSS to provide a printable style for your page. In many cases, you can use this to hide any navigation, etc. and not have a need for a 'print preview'. I usually add something like the following to my .css file:

.showwhenprinting {position:absolute; display:none;}
@media print
{
  .hidewhenprinting {position:absolute; display:none;}
  .showwhenprinting {position:relative; display:block;}
}

This will let you hide blocks when printing in most browsers. For example:

<div class="someclass hidewhenprinting">Navigation Menu</div>
<div class="someclass showwhenprinting">Printed Page Title</div>

The other benefit of this approach is that it allows users to simply click 'print' as they normally would in the browser. The drawbacks are that some older browsers do not support it, and in some cases it does not give you enough control over the layout (for example if you want page headers/footers).

-if the above doesn't give you the output you need (for example, you don't want the page URL, etc. on the printed result), the other option would be to use a printer-friendly format such as PDF. To do this, use Reporting Services or a similar tool for generating your PDF.

-A final option I wouldn't really recommend is to add a hidden iframe to the page, populate it with your "printable" HTML, and call print() in it. This may work, but would require some javascript to pull off, so you would need to take care to make it cross-browser. This would have the same drawbacks of option #1, but be more difficult to get right.

I name my classes "PrintOnly" and "ScreenOnly" (or "PrintNever" if I'm thinking about mobile as well). "showwhenprinting" is such a mouthful.
Joel Coehoorn
you could do "ForPrint" and "ForScreen" and they would make more sense, and you save a character! :)
Jason
A: 

Related if not duplicate topic.

How do I do advanced printing from a web application?

Greg Ogle