2

I have to silently print HTML document from WebBrowser in WPF. I have done it NOT silently by that code:

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

Now I want to skip the print dialog. Please help.

v.chjen
  • 615
  • 1
  • 8
  • 20

1 Answers1

2

For silent printing with WPF WebBrowser, below code worked for me:

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

Note: answer was inspired by this SO q & a

Community
  • 1
  • 1
PostureOfLearning
  • 3,481
  • 3
  • 27
  • 44
  • 4
    How does WebBrowser1.Document gets converted in to IOleServiceProvider. As WebBrowser1.Document is an HTMLDocument – Malcolm Jan 18 '16 at 11:17
  • 2
    Is there a way to send it to a non-default printer? – Slate May 16 '17 at 09:00
  • 1
    @Malcolm If anyone else comes across this (and several have judging by the upvotes on your comment), please note that this answer uses the WPF WebBrowser NOT the WinForms one. – Jonathan Willcock Jun 08 '21 at 06:21