Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Dec 9, 2002

Printing formatted text and other data with the WebBrowser control

Printing con be quite difficult in VB.NET (or any other .NET language), especially if you not only have to print plain text, but also tables, images, bulleted lists, text with different fonts, styles, colors and any other type of formatted data. Here's a tip that can make your life much easier, in many cases.

The trick is to save your data in HTML format, and then use the Microsoft Web Browser control to print it. Creating tables, lists and formatted text in HTML is very easy, as it is just plain text. Once you have the HTML string with the content to print, save it to a temporary .htm file, by using the {{C491 SaveTextFile}} routine, and by getting a temporary file name, as follows:


Imports System.IO
…
Dim tempFile As String = Path.ChangeExtension(Path.GetTempFileName(), "htm")
SaveTextFile(tempFile, htmlData)
Now you need a Web Browser control on your form. This is a COM component, and you have to create a .NET wrapper assembly for it before being able to use it. This is done by adding a reference to the ShDocVw.dll file (located under the System32 directory) from the Customize Toolbox dialog. Once the control is available from the toolbox, drag&drop it on your form, and make it as small as possible (1x1 pixels), or put it out-of-sight, so that it is not visible at runtime. (Note: you can't just set its Visible property to False, this won't allow you to print its content).

At this point you can load the HTML file into the Web Browser control:


AxWebBrowser.Navigate(tempFile)
And finally you can print your formatted data by executing a JavaScript piece of code that opens the Print dialog, from which you can choose the printer to use, the number of copies, and other options:

AxWebBrowser.Document.parentWindow.execScript("window.print();", "JScript")
Quick and dirty!
Marco Bellinaso
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap