从WPF WebBrowser中静默打印HTML

时间:2014-04-11 11:30:35

标签: c# wpf

我必须在WPF中静默地从WebBrowser打印HTML文档。我没有通过该代码默默地完成它:

mshtml.IHTMLDocument2 doc = WebBrowser1.Document as mshtml.IHTMLDocument2;
doc.execCommand("Print", true, null);

现在我想跳过打印对话框。 请帮忙。

1 个答案:

答案 0 :(得分:2)

对于使用WPF WebBrowser的静默打印,下面的代码对我有用:

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

注意:答案的灵感来自this SO q & a