2009-08-19 128 views
2

我試圖打印WPF WebBrowser控件的內容,以便不顯示任何打印對話框,但我沒有運氣。打印WPF WebBrowser的內容

我曾嘗試以下,並相信它的工作:

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

但由於某些原因,我現在收到以下異常:

無法投類型的COM對象「 mshtml.HTMLDocumentClass'到接口類型'System.Windows.Documents.IDocumentPaginatorSource'。此操作失敗,因爲具有IID'{2C0C27DF-282F-3225-ADCD-CEC68F890EEB}'的接口的COM組件上的QueryInterface調用失敗,原因是出現以下錯誤:沒有支持此接口(異常來自HRESULT:0x80004002(E_NOINTERFACE)) 。

我能想到的唯一事情就是在我的電腦上改變了,自從我上次試過這個以來,我已經安裝了IE8,但是真的會打破它嗎?

回答

2

對於無聲打印而不對話框,使用以下代碼:

private void PrintCurrentPage() 
{ 
    // document must be loaded for this to work 
    IOleServiceProvider sp = WebBrowser1.Document as IOleServiceProvider; 
    if (sp != null) 
    { 
     Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); 
     Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E"); 
     const int OLECMDID_PRINT = 6; 
     const int OLECMDEXECOPT_DONTPROMPTUSER = 2; 

     dynamic wb; // should be of IWebBrowser2 type 
     sp.QueryService(IID_IWebBrowserApp, IID_IWebBrowser2, out wb); 
     if (wb != null) 
     { 
      // this will send to the default printer 
      wb.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, null, null); 
     } 
    } 
} 
[ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 
private interface IOleServiceProvider 
{ 
    [PreserveSig] 
    int QueryService([MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject); 
} 

WebBrowser silent printing