Wpf – Printing the contents of a WPF WebBrowser

browserprintingwpf

I'm trying to print the contents of a WPF WebBrowser control so that no print dialog is shown, but am having no luck.

I have tried the following and am sure it did work:

PrintDialog printDialog = new PrintDialog();
printDialog.PrintDocument(((IDocumentPaginatorSource)browser.Document).DocumentPaginator, "My App");

but for some reason, I'm now getting the following exception:

Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to interface type 'System.Windows.Documents.IDocumentPaginatorSource'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{2C0C27DF-282F-3225-ADCD-CEC68F890EEB}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

The only thing I can think has changed on my PC is that I have installed IE8 since I last tried this, but would that really break it?

Best Answer

// Send the Print command to WebBrowser. For this code to work: add the Microsoft.mshtml .NET reference
mshtml.IHTMLDocument2 doc = WebBrowser1.Document as mshtml.IHTMLDocument2;
doc.execCommand("Print", true, null);

Source: http://social.msdn.microsoft.com/Forums/en/wpf/thread/63ae5345-b2ca-45a9-9113-0ddc43e9925b

Related Topic