2014-10-05 112 views
0

我发现代码here,我用像这样:如何打印WebBrowser控件的内容?

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 消息=无法将类型为“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()“行没有错误味精),我看不到打印对话框。那么如何可以我去打印一个WebBrowser控件的内容?有关打印窗口

+0

这对WPF。 – SLaks 2014-10-05 19:30:54

+0

全部是?如果是这样,Winforms的方式是什么? – 2014-10-05 19:32:23

回答

1

MSDN页面构成web浏览器控制: 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(); 
} 
+1

因为我不需要动态地创建一个WebBrowser,并且当用户对Print按钮进行抠图时该文档已经被加载,所以我可以通过简单的webBrowser.Print()来获取它。 – 2014-10-06 04:56:50