从WPF Web浏览器静默打印HTML

本文关键字:打印 HTML 静默 浏览器 WPF Web | 更新日期: 2023-09-27 17:57:57

我必须在WPF中从WebBrowser静默打印HTML文档。我已经做了它不是无声的代码:

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

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

从WPF Web浏览器静默打印HTML

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

注:答案的灵感来自于这个SOq&