您现在的位置:首页 >> VCL >> VCL >> 内容

Delphi直接从流中读取HTML到WebBrower中

时间:2011/9/3 16:24:41 点击:

  核心提示:usesActiveX; procedureLoadStream(WebBrowser:TWebBrowser;Stream:TStream); var PersistStreamInit:IPers...
uses ActiveX;


procedure LoadStream(WebBrowser: TWebBrowser; Stream: TStream);
var
PersistStreamInit: IPersistStreamInit;
StreamAdapter: IStream;
MemoryStream: TMemoryStream;
begin
{Load empty HTML document into Webbrowser to make "Document" a valid HTML document}
WebBrowser.Navigate('about:blank');
{wait until finished loading}
repeat
Application.ProcessMessages;
Sleep(0);
until
WebBrowser.ReadyState = READYSTATE_COMPLETE;
{Get IPersistStreamInit - Interface}
if WebBrowser.Document.QueryInterface(IPersistStreamInit, PersistStreamInit) = S_OK then
begin
{Clear document}
if PersistStreamInit.InitNew = S_OK then
begin
{Make local copy of the contents of Stream if you want to use Stream directly, you have to
consider, that StreamAdapter will destroy it automatically}
MemoryStream:= TMemoryStream.Create;
try
MemoryStream.CopyFrom(Stream, 0);
MemoryStream.Position:= 0;
except
MemoryStream.Free;
raise;
end;
{Use Stream-Adapter to get IStream Interface to our stream}
StreamAdapter:= TStreamAdapter.Create(MemoryStream, soOwned);
{Load data from Stream into WebBrowser}
PersistStreamInit.Load(StreamAdapter);
end;
end;
end;



{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
var
S: TStringStream;
begin
S:= TStringStream.Create('<html><h1>Stream Test</h1><p>:This HTML content ' +
'is being loaded from a stream.</html>');
try
LoadStream(WebBrowser1, S);
finally
S.Free;
end;

End;

上面是把html字符串显示在WebBrowser里,下面是保存成Html文件:

function SaveHTMLCode(WebBrowser: TWebBrowser; const FileName: TFileName): Boolean;
var
ps: IPersistStreamInit;
fs: TFileStream;
sa: IStream;
begin
ps := WebBrowser.Document as IPersistStreamInit;
fs := TFileStream.Create(FileName, fmCreate);
try
sa := TStreamAdapter.Create(fs, soReference) as IStream;
Result := Succeeded(ps.Save(sa, True));
finally
fs.Free;
end;
end;

Call with:
SaveHTMLCode(WebBrowser1, 'C:\MyHTMLDoc.html');

//保存成流:
procedure SaveDocumentSourceToStream(Document: IDispatch; Stream: TStream);
var
PersistStreamInit: IPersistStreamInit;
StreamAdapter: IStream;
begin
Stream.Size := 0;
Stream.Position := 0;
if Document.QueryInterface(IPersistStreamInit, PersistStreamInit) = S_OK then
begin
StreamAdapter := TStreamAdapter.Create(Stream, soReference);
PersistStreamInit.Save(StreamAdapter, False);
StreamAdapter := nil;
end;
end;

Tags:直接 读取 
作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
本类推荐
  • 没有
本类固顶
  • 没有
  • 盒子文章(www.2ccc.com) © 2020 版权所有 All Rights Reserved.
  • 沪ICP备05001939号