我开发了一个Windows服务,每x次检查一个目录,如果有html文件,它们会被发送到打印机。
在我的电脑上一切正常,但当应用程序部署在服务器PC上时,它不会打印
对于实现,我使用此链接作为参考:https://limbioliong.wordpress.com/2014/07/21/using-the-webbrowser-control-to-print-documents/
通过日志记录,我知道事件ie.PrintTemplateInstantiation被调用。之后,不再记录任何内容,没有错误。可能有什么不对?
所有相关代码:
Thread thread = new Thread(PrintDocument);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
private void PrintDocument()
{
try
{
var printJob = _printJobs.First(x => !x.Printed);
new Print.Print().StartDocumentPrint(_printerName, printJob, PrintFinished);
}
catch (Exception ex)
{
// Some logging
}
}
public void StartDocumentPrint(string pname, PrintJob file, Action<PrintJob> finished)
{
_file = file;
_finishedAction = finished;
try
{
// Create a WebBrowser instance.
var webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(file.File);
Application.Run();
}
catch (Exception ex)
{
// Logging
}
}
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var logService = DependencyResolver.Container.Resolve<ILogService>();
WebBrowser wb = sender as WebBrowser;
try {
SHDocVw.InternetExplorer ie = (SHDocVw.InternetExplorer)(wb.ActiveXInstance);
ie.PrintTemplateInstantiation +=
new SHDocVw.DWebBrowserEvents2_PrintTemplateInstantiationEventHandler(IE_OnPrintTemplateInstantiation);
ie.PrintTemplateTeardown +=
new SHDocVw.DWebBrowserEvents2_PrintTemplateTeardownEventHandler(IE_OnPrintTemplateTeardown);
ie.PutProperty("WebBrowserControl", (object)wb);
wb.Print();
}
catch (Exception ex)
{
// Logging
}
}
private static void IE_OnPrintTemplateInstantiation(object pDisp)
{
// Logging
}
private static void IE_OnPrintTemplateTeardown(object pDisp)
{
// Logging
_finishedAction.Invoke(_file);
SHDocVw.IWebBrowser2 iwb2 = pDisp as SHDocVw.IWebBrowser2;
WebBrowser wb = (WebBrowser)(iwb2.GetProperty("WebBrowserControl"));
wb.Dispose();
Application.ExitThread();
}