devxlogo

Printing formatted text and other data with the WebBrowser control

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 (1×1 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!

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist