Cry about...
Delphi Programming with TWebBrowser


How to save the page displayed in a TWebBrowser to a single page .mht web archive file


If all you want to do is to save a page from the internet as a web archive file then there is no need to create an instance of TWebBrowser to load and hold the page.

The web archive files (.mht) are only supported by Internet Explorer but provide a convenient means of capturing the HTML, images etc of a webpage in a single file.

To capture a page from the web and save it to a file use:

procedure SaveURLasMHT(const url: String; const fileName: String);
var
  imsg: IMessage;
  iconf: IConfiguration;
  stream: _Stream;
begin
  imsg := CoMessage.Create;
  iconf := CoConfiguration.Create;

  try
    imsg.Configuration := iconf;
    imsg.CreateMHTMLBody(url,cdoSuppressAll,'','');
    stream := imsg.GetStream;
    stream.SaveToFile(fileName, adSaveCreateOverWrite);
  finally
    imsg := nil;
    iconf := nil;
    stream := nil;
  end;
end;

To save the page currently visible in the browser use:

procedure SaveAsMHT(const webBrowser: TWebBrowser; const fileName: String);
begin
  SaveURLasMHT(webBrowser.LocationURL,fileName);
end;

Note:

  • Unfortunately this does not save the HTML currently in the browser but instead the HTML for the URL that the browser has been opened on. So if you were to inject HTML into the browser then this would not be reflected in the .MHT file you then saved. I have looked for ways to retrieve the currently viewed page as a web archive but have not been successful - and an open to suggestions.
  • If all you need is to obtain and save the HTML of the current page then the function GetBrowserHtml may be all that you require.

These notes are believed to be correct for Delphi 6 and 7, and may apply to other versions as well.



About the author: is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.