How to print html in C#

MoShe picture MoShe · Oct 6, 2011 · Viewed 18.4k times · Source

I would like to print a file using PrintDocument in C#. The file is simple HTML (I need it because I need the text in the file to be located in specific places within the page.)

My question is, how do I print the file so it will not print the HTML itself (tags, etc.) but the HTML as it would show in a web browser?

Answer

JohnFx picture JohnFx · Oct 6, 2011

Use a web browser control and call the print method on it like so:

private void PrintHelpPage()
{
    // Create a WebBrowser instance. 
    WebBrowser webBrowserForPrinting = new WebBrowser();

    // Add an event handler that prints the document after it loads.
    webBrowserForPrinting.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(PrintDocument);

    // Set the Url property to load the document.
    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");
}

private void PrintDocument(object sender,
    WebBrowserDocumentCompletedEventArgs e)
{
    // Print the document now that it is fully loaded.
    ((WebBrowser)sender).Print();

    // Dispose the WebBrowser now that the task is complete. 
    ((WebBrowser)sender).Dispose();
}

MSDN Article on doing this