procedure html2stream(const URL: WideString; Stream: TStream);
var
Msg: IMessage;
Conf: IConfiguration;
I_Stream: _Stream;
Str: string;
begin
Msg:= CoMessage.Create;
Conf:= CoConfiguration.Create;
try
Msg.Configuration:= Conf;
Msg.CreateMHTMLBody(URL, CdoSuppressNone, '', '');
I_Stream:= Msg.GetStream;
I_Stream.Position:= 0;
I_Stream.Charset:= 'gb2312';
Str:= I_Stream.ReadText( I_Stream.Size );
Stream.Write(Pointer(Str)^, Length(Str));
finally
Msg:= nil;
Conf:= nil;
end;
end; (* html2stream *)
这是我转换html为mht的函数,但这个函数必须要输入URL地址。
另外如果将 Msg.CreateMHTMLBody(URL, CdoSuppressNone, '', '');改为 Msg.HTMLBody:= '';// 这里直接赋上html文件的内容也可以实现转换功能,但这种转换,只能转换不含图片的网页,效果等同 Msg.CreateMHTMLBody(URL, CdoSuppressAll, '', '');因为不想每做一次转换都需要生成一个临时的html文件,所以不知道是否有方法可以设置 CdoMHTMLFlags 属性
HRESULT CreateMHTMLBody(
BSTR URL,
CdoMHTMLFlagsFlags=cdoSuppressNone,
BSTR UserName,
BSTR Password
);
CdoMHTMLFlags Enum 申明
Name Value Description
CdoSuppressNone 0 Download all resources referred to in elements within the resource at the specified Uniform Resource Identifier (URI) (not recursive).CdoSuppressImages 1 Do not download resources referred to in IMG elements.
CdoSuppressBGSounds 2 Do not download resources referred to in BGSOUND elements.
CdoSuppressFrames 4 Do not download resources referred to in FRAME elements.
CdoSuppressObjects 8 Do not download resources referred to in OBJECT elements.
CdoSuppressStyleSheets 16 Do not download resources referred to in LINK elements.
CdoSuppressAll 31 Do not download any resources referred to from within the page.
现在就讨论下这个问题吧,散分散分。上面的问题关键是在如果用IMessage封装的 CreateMHTMLBody 接口,那么因为这个接口中允许设置保存网页的属性(如保存同时也保存图片,还是保存纯文字)但如果通过设置HTMLBody,好像默认是只能保存网页文字,而不会保存图片内容。
IMessage在CDO_TLB单元函数需要 CDO_TIB 和 ADODB_TLB 单元。
创建单元方法:
1、Project-->Import Type Library
2、在列表中查找: Microsoft CDO for Windows 2000 Library (Version 1.0)
3、如果没有,则点击 Add,添加 "C:\WINDOWS\system32\cdosys.dll"
4、选中该项,点击 Create Unit
郁闷
//把HTML文档保存为MHT格式
function TDownHTML.HtmlSaveAsMHT(URL:string;FilePath:string;FileName:string):Integer;
var
msg:IMessage;
conf:IConfiguration;
stream:_Stream;
TempFileName,Ext: string;
TempFilePath: string;
begin
msg := CoMessage.Create;
conf := CoConfiguration.Create;
try
try
msg.Configuration :=conf;
//msg.CreateMHTMLBody(URL, cdoSuppressAll, 'domain\username','password');
msg.CreateMHTMLBody(URL,cdoSuppressNone,'',''); //cdoSuppressNone 则表示不限制任何内容,即保存所有内容
//stream.Charset :='gb2312';
stream := msg.GetStream;
stream.SaveToFile(NormFileName(FilePath,FileName),adSaveCreateOverWrite);
Result:=1;
except
try //第一次出错,再尝试第二次保存
msg.CreateMHTMLBody(URL,cdoSuppressAll, '', ''); //cdoSuppressAll, 则图片,声音,样式等内容就不被保存到mht文件中.
msg.GetStream.SaveToFile(NormFileName(FilePath,FileName),adSaveCreateOverWrite);
Result:=1;
except
SendErrToMemo('下载文件失败! URL:' + URL);
WriteLog('下载文件失败!' + TempFileName + '(' + URL + ')', LogFile);
Result:=0;
end;
end;
finally
msg := nil;
conf := nil;
stream := nil;
//web := nil;
end;
end;