How to print an HTML document from inside of your application

By: Corbin Dunn

Abstract: Printing HTML documents by automating Internet Explorer with TWebBrowser

Developing Internet Applications
By Corbin Dunn
Delphi Developer Support

Question: How do I print an HTML document from inside an application? Or, how do I print from a TWebBrowser control?

Answer: Using Internet Explorer 5 makes this very simple to do, but involves a little work to get it done. Let's say that you want to allow your program to print HTML documents - either from the web directly, or from a file. The main problem programmers encounter is that TWebBrowser does not have a Print method. If you have ever looked inside of MSHTML.pas you will notice that IHTMLWindow3 has a print method that we can call - the only trick is in acquiring an IHTMLWindow3 interface from a TWebBrowser. This can be down by using TWebBrowser component (it doesn't have to be visible), calling WebBrowser.Navigate to go the location you want to print, and then in the NavigateComplete event doing the print:

procedure TForm1.WebBrowser_V1NavigateComplete(Sender: TObject;
  const pDisp: IDispatch; var URL: OleVariant);
var
  HTMLDoc: IHTMLDocument2;
  HTMLWnd: IHTMLWindow2;
  HTMLWindow3: IHTMLWindow3;
begin
  HTMLDoc := (Sender as TWebBrowser).Document as IHTMLDocument2;
  if HTMLDoc = nil then
    raise Exception.Create('Couldn''t convert the WebBrowser to an IHTMLDocument2');
  HTMLWnd := HTMLDoc.parentWindow;
  HTMLWindow3 := HTMLWnd as IHTMLWindow3;
  // Finally, we get to the print method
  HTMLWindow3.print;
end;
Download the sample source for this project from Borland Code Central


Server Response from: ETNASC03