Search code examples
c#htmlprintingprintdocument

How to print html in C#


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?


Solution

  • 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