打印 WPF WebBrowser 的内容

Posted

技术标签:

【中文标题】打印 WPF WebBrowser 的内容【英文标题】:Printing the contents of a WPF WebBrowser 【发布时间】:2010-11-20 21:39:10 【问题描述】:

我正在尝试打印 WPF WebBrowser 控件的内容,以便不显示打印对话框,但我没有运气。

我已经尝试了以下方法,并且确信它确实有效:

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

但由于某种原因,我现在遇到以下异常:

无法将“mshtml.HTMLDocumentClass”类型的 COM 对象转换为接口类型“System.Windows.Documents.IDocumentPaginatorSource”。此操作失败,因为 IID 为“2C0C27DF-282F-3225-ADCD-CEC68F890EEB”的接口的 COM 组件上的 QueryInterface 调用因以下错误而失败:不支持此类接口(来自 HRESULT 的异常:0x80004002 (E_NOINTERFACE)) .

我认为我的 PC 上唯一发生的变化是,自从我上次尝试后我安装了 IE8,但这真的会破坏它吗?

【问题讨论】:

【参考方案1】:
// 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);

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

【讨论】:

【参考方案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

【讨论】:

【参考方案3】:

为了避免对 MSHTML 的依赖,您可以这样做:

browser.InvokeScript("execScript", new object[]  "window.print();", "javascript" );

当我遇到迁移到 .Net Core 3 的 WPF 项目并使用涉及 MSHTML 参考的 Tony 的答案时,我设计了上述解决方案。在 .Net Core 中引用 MSHTML 不是很简单(参见 this github issue)

【讨论】:

非常感谢。这很棒。这也可以用来保存页面吗?

以上是关于打印 WPF WebBrowser 的内容的主要内容,如果未能解决你的问题,请参考以下文章

WPF中WebBrowser 如何在页面加载的时候注入js脚本

如何禁用 WPF WebBrowser 控件的点击噪音?

StackPanel中的WebBrowser不会在WPF中扩展到其内容大小

WPF c# webbrowser 在顶部菜单上滚动

数据绑定 WPF 中 WebBrowser 的 Source 属性

wpf webbrowser