How do I print an HTML document from a web service?

Posted by Chris Marasti-Georg on Stack Overflow See other posts from Stack Overflow or by Chris Marasti-Georg
Published on 2008-08-01T18:33:48Z Indexed on 2010/04/12 18:03 UTC
Read the original article Hit count: 344

Filed under:
|
|
|

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, that is not running 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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about html