如何打印WebBrowser控件的内容?

时间:2014-10-05 19:29:14

标签: c# winforms browser printdialog

我找到了我用过的代码here

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

...但是我得到了两个错误的信息,即:

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?)

然后我尝试以这种方式调整here的代码:

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

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

...但得到了,“ System.InvalidCastException未处理   的HResult = -2147467262   Message =无法将'System.Windows.Forms.Button'类型的对象强制转换为'System.Windows.Forms.WebBrowser'。

然后我试图从我发现的here中得到这个代码:

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

...而且,虽然我可以单步执行它,但似乎工作(我进入“web.ShowPrintDialog()”行没有错误的msg),我看不到打印对话框。那么可以如何打印WebBrowser控件的内容?

1 个答案:

答案 0 :(得分:2)

关于打印Windows窗体Web浏览器控件的MSDN页面: 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();
}