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.
First, open the HTML file or load the web site page in your browser window. Then select 'Print...' from the web browser's File menu. You will then be able to convert the HTML web page to a PDF copy of the page on your computer.
Open the web page. 2. Press Ctrl + A 3. Right click on the page and left click on “Print” 4.
You can print from the command line using the following:
rundll32.exe %WINDIR%\System32\mshtml.dll,PrintHTML "%1"
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 + @"\rundll32.exe"; printProcess.StartInfo.Arguments = systemPath + @"\mshtml.dll,PrintHTML """ + fileToPrint + @""""; printProcess.Start(); }
N.B. This only works on Windows 2000 and above I think.
I know that Visual Studio itself (at least in 2003 version) references the IE dll directly to render the "Design View".
It may be worth looking into that.
Otherwise, I can't think of anything beyond the Web Browser control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With