使用TWebBrowser组件保存网页为html和mht文件 收藏

一、保存为HTML文件

uses ActiveX;
...
procedure WB_SaveAs_HTML(WB : TWebBrowser; const FileName : string) ;
var
  PersistStream: IPersistStreamInit;
  Stream: IStream;
  FileStream: TFileStream;
begin
  if not Assigned(WB.Document) then
  begin
    ShowMessage('Document not loaded!') ;
    Exit;
  end;

PersistStream := WB.Document as IPersistStreamInit;
  FileStream := TFileStream.Create(FileName, fmCreate) ;
  try
    Stream := TStreamAdapter.Create(FileStream, soReference) as IStream;
    if Failed(PersistStream.Save(Stream, True)) then ShowMessage('SaveAs HTML fail!') ;
  finally
    FileStream.Free;
  end;
end; (* WB_SaveAs_HTML *)

使用方法:

WebBrowser1.Navigate('http://www.uufax.com') ;

//then save
WB_SaveAs_HTML(WebBrowser1,'c:/WebBrowser1.html') ;

二、另存为MHT单一文件

uses CDO_TLB, ADODB_TLB;
...
procedure WB_SaveAs_MHT(WB: TWebBrowser; FileName: TFileName) ;
var
  Msg: IMessage;
  Conf: IConfiguration;
  Stream: _Stream;
  URL : widestring;
begin
  if not Assigned(WB.Document) then Exit;

URL := WB.LocationURL;

Msg := CoMessage.Create;
  Conf := CoConfiguration.Create;
  try
    Msg.Configuration := Conf;
    Msg.CreateMHTMLBody(URL, cdoSuppressAll, '', '') ;
    Stream := Msg.GetStream;
    Stream.SaveToFile(FileName, adSaveCreateOverWrite) ;
  finally
    Msg := nil;
    Conf := nil;
    Stream := nil;
  end;
end; (* WB_SaveAs_MHT *)

使用方法:

//first navigate
WebBrowser1.Navigate('http://www.uufax.com') ;

//then save
WB_SaveAs_MHT(WebBrowser1,'c:/WebBrowser1.mht') ;

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sunstone/archive/2009/11/09/4788743.aspx

上一篇:详细解读Android中的搜索框(三)—— SearchView


下一篇:C#接口实现技巧之借助第三方