标签云

微信群

扫码加入我们

WeChat QR Code

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();
}

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:

Error: 'dialogArguments.___IE_PrintType' is null or not an object
URL: res://ieframe.dll/preview.dlg

And a small empty print preview dialog appears.


Please select best answer, thanks.

2018年07月19日49分54秒

mruanova None of the answers worked last I tried them. If you have something that works let us know.

2018年07月19日49分54秒

Great answer - was going to mark it accepted, and ran my test. Seems that dll still pops up the Print dialog, and as this is to run as an unattended Windows Service, we need to bypass that somehow. I've pretty much exhausted Google, and I'm at my wits end.

2018年07月19日49分54秒

Unfortunately printer dialog appears. I tested on Windows 7 x64.

2018年07月19日49分54秒

Last I checked, part 2 (printing via command line with Adobe) does not work in a service - it requires user interaction.

2018年07月19日49分54秒

Try Sumatra PDF it's much faster blog.kowalczyk.info/software/sumatrapdf/…

2018年07月18日49分54秒

ColonelPanic Wow. Great hint. Took me ages to find one that works even from a service, and it seems SumatraPdf is actually usable in commercial packages.

2018年07月19日49分54秒