How can I print the contents of a WebBrowser control?

B. Clay Shannon picture B. Clay Shannon · Oct 5, 2014 · Viewed 8.9k times · Source

I found code here that I used like so:

printDialog1.PrintDocument
(((IDocumentPaginatorSource)webBrowserMap.Document).DocumentPaginator, "Alchemy Map");

...but with that I get two err msgs, namely:

0)'System.Windows.Forms.PrintDialog' does not contain a definition for 'PrintDocument' and no extension method 'PrintDocument' accepting a first argument of type 'System.Windows.Forms.PrintDialog' could be found (are you missing a using directive or an assembly reference?)

1) The type or namespace name 'IDocumentPaginatorSource' could not be found (are you missing a using directive or an assembly reference?)

I then tried to adapt the code from here this way:

private void buttonPrint_Click(object sender, EventArgs e)
{
    WebBrowser wb = getCurrentBrowser();
    wb.ShowPrintDialog();
}

private WebBrowser getCurrentBrowser()
{
    return (WebBrowser)tabControlAlchemyMaps.SelectedTab.Controls[0];
}

...but got, "System.InvalidCastException was unhandled HResult=-2147467262 Message=Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.WebBrowser'.

I then tried to derive from what I found here, with this code:

private void buttonPrint_Click(object sender, EventArgs e)
{
    WebBrowser web = getCurrentBrowser();
    web.ShowPrintDialog();
}

private WebBrowser getCurrentBrowser()
{
    // I know there's a better way, because there is only one WebBrowser control on the tab
    foreach (var wb in tabControlAlchemyMaps.SelectedTab.Controls.OfType<WebBrowser>())
    {
        return wb;
    }
    return null;
}

...and, although I can step through it, and it seems to work (I get to the "web.ShowPrintDialog()" line with no err msg), I see no print dialog. So how can I go about printing the contents of a WebBrowser control?

Answer

Pavel Krymets picture Pavel Krymets · Oct 5, 2014

MSDN page about printing windows forms web browser control: http://msdn.microsoft.com/en-us/library/b0wes9a3(v=vs.90).aspx

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();
}