问题描述
我有一些unicode .html文件,我想显示在一个THtmlViewer组件,在Delphi。
I have some unicode .html files that I want to display inside a THtmlViewer component, in Delphi.
我似乎无法说服代码工作,只是做'.LoadFromFile' - 我首先需要将unicode文件加载到流中,然后以某种方式转换?
I can't seem to persuade the code to work just doing '.LoadFromFile' - do I firstly need to load the unicode file into a stream and then somehow convert it?
Delphi 2007,THtmlViewer v9.45
Delphi 2007, THtmlViewer v9.45
我没有对unicode文件做任何事情,或者THHTMLViewer,
I've not done anything with unicode files, or THtmlViewer, before.
推荐答案
好的,这里是我出现的胆量。建设性批评和观察感谢!
Okay, well here's the guts of what I came up. Constructive criticism and observations appreciated!
// load either an ansi or unicode-type html doc into the browser component.
// the filename has already been confirmed as an existing file
procedure TfrmBrowser.LoadDocument(FFileName:string);
var
FWideText : Widestring;
FAnsiText : AnsiString;
FRequiredLen : Integer;
FFileStream : TFileStream;
FMemStream : TMemoryStream;
FBuffer : Byte;
begin
FFileStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyNone);
// anything less than half a dozen bytes would be pointless, but...
if FFileStream.Size>1 then
begin
// checking the first byte of the file to give us a clue about file-type
FFileStream.Read(FBuffer,1);
FFileStream.Position:=0; // rewind position
if (FBuffer=$FF) or (FBuffer=$EF) then
begin
// probably Unicode
FRequiredLen := FFileStream.Size div 2; // 2 bytes per char
SetLength(FWideText, FRequiredLen);
FFileStream.Read(FWideText[1], FFileStream.Size);
// cast it into an Ansistring
FAnsiText := FWideText;
FMemStream := TMemoryStream.Create;
FMemStream.Write(FAnsiText[1], FRequiredLen);
FMemStream.Position := 0; // rewind the position
// load the stream into the THtmlViewer
vwBrowse.LoadFromStream(FMemStream);
FMemStream.Free;
end
else
begin
// probably Ansi, just load original filestream in
vwBrowse.LoadFromStream(FFileStream);
end;
FFileStream.Free;
end;
显然缺少一些错误捕获,但这是基本思想。
Obviously missing some error-trapping, but that's the basic idea.
这篇关于如何使PBear的THHTMLViewer加载&显示一个unicode HTML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!