如何从 Web 服务打印 HTML 文档? [英] How do I print an HTML document from a web service?
问题描述
我想从 C# 网络服务打印 HTML.Web 浏览器控件是过大的,在服务环境中不能很好地运行,在安全约束非常严格的系统中也不能很好地运行.是否有任何类型的免费 .NET
库支持打印基本的 HTML 页面?这是我到目前为止的代码,它运行不正常.
I want to print HTML from a C# web service. The web browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free .NET
library that will support the printing of a basic HTML page? Here is the code I have so far, which does not run properly.
public void PrintThing(string document)
{
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
Thread thread =
new Thread((ThreadStart) delegate { PrintDocument(document); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
else
{
PrintDocument(document);
}
}
protected void PrintDocument(string document)
{
WebBrowser browser = new WebBrowser();
browser.DocumentText = document;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Print();
}
这在从 UI 类型线程调用时工作正常,但从服务类型线程调用时没有任何反应.将 Print()
更改为 ShowPrintPreviewDialog()
会产生以下 IE 脚本错误:
This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing Print()
to ShowPrintPreviewDialog()
yields the following IE script error:
错误: dialogArguments.___IE_PrintType
为空或不是对象.
网址:res://ieframe.dll/preview.dlg
出现一个小的空打印预览对话框.
And a small empty print preview dialog appears.
推荐答案
您可以使用以下命令从命令行打印:
You can print from the command line using the following:
rundll32.exe%WINDIR%System32mshtml.dll,PrintHTML%1"
rundll32.exe %WINDIR%System32mshtml.dll,PrintHTML "%1"
其中 %1 是要打印的 HTML 文件的文件路径.
Where %1 is the file path of the HTML file to be printed.
如果您不需要从内存中打印(或者可以在临时文件中写入磁盘),您可以使用:
If you don't need to print from memory (or can afford to write to the disk in a temp file) you can use:
using (Process printProcess = new Process())
{
string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
printProcess.StartInfo.FileName = systemPath + @"
undll32.exe";
printProcess.StartInfo.Arguments = systemPath + @"mshtml.dll,PrintHTML """ + fileToPrint + @"""";
printProcess.Start();
}
注意我认为这仅适用于 Windows 2000 及更高版本.
N.B. This only works on Windows 2000 and above I think.
这篇关于如何从 Web 服务打印 HTML 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!