我正在尝试打印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)) 的
在我的电脑上,我唯一能想到的就是我自上次尝试过以来已经安装了IE8,但这真的会破坏它吗?
答案 0 :(得分:7)
// 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
答案 1 :(得分:3)
对于没有对话框的静默打印,请使用以下代码:
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);
}
答案 2 :(得分:0)
要避免依赖MSHTML,您只需执行以下操作:
browser.InvokeScript("execScript", new object[] { "window.print();", "JavaScript" });
当我遇到一个WPF项目的麻烦时,我设计了上述解决方案,该项目已迁移到.Net Core 3,并且使用了涉及MSHTML参考的Tony的答案。在.Net Core中引用MSHTML并不是很简单(请参见this github issue)