Printing html using the embedded web browser control
In this post I’ll try to answer some questions about the web browser control and provide some workarounds for known issues involved in the printing process.
I'm assuming that you have some experience with the web browser control and basic knowledge of COM and hosting APIs. So I’m not going to cover those topics.
At the bottom of this page I’ve added the links to download a small library I wrote that takes care of printing HTML and a demo app so you can try it out without having to write any code by yourself.
Using the code
The HtmlPrinter class will allow you to print html from an URL or just passing the html as string, you can also specify the title and the number of copies you want to print. The code may look something like this:
Now that we know how to use the API let get answer some questions.
Well, apparently when you send a lot of print commands to the web browser control, there is a lot of COM crap in between that leave the control into nonresponsive state and after a couple of calls, your app will hang and eventually it will die.
I ran into this issue a couple of days ago and I can solve it adding this code inside the print method:
While the COM API is busy, we just keep on pumping messages to the OS loop, avoiding app hungups, when the API es ready, we proceed with the printing. So far, always work ;)
Why my images don't print or how can I print them?
The only thing you should take care of when it comes to print images is specify the image URL in a way that is “reachable” by the web browser control. The code down below ain’t gonna work.
whereas this should work like a charm:
It’s possible to print without showing the print preview dialog?
Yes it is possible. Just download the sample app and run it. All the samples presented in this post print html without showing the print preview dialog.
How can I change the page orientation?
The answer is you cannot. It is possible to change the default page orientation modifying this key on the registry:
But I recommend not to that. (and sometimes it doesn't work either).
You can find more info at http://msdn.microsoft.com/en-us/library/ms905101.aspx
* I also tried adding this header to the html without any luck
So I think that’s all for those issues I've heard of. If you have any question about printing HTML, feel free to ping me, I'll try to answer it.