【问题标题】:Printing the contents of a WPF WebBrowser打印 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,但这真的会破坏它吗?

【问题讨论】:

    标签: wpf browser printing


    【解决方案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

        【讨论】:

        • 非常感谢。这很棒。这也可以用来保存页面吗?
        猜你喜欢
        • 2010-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 2014-05-25
        • 2017-06-11
        • 2011-08-29
        相关资源
        最近更新 更多