In a Delphi 10.4.2 Win32 VCL Application, I need to insert an SVG document manually into a TWebBrowser
(wb1.SelectedEngine := IEOnly;
) at run-time:
procedure TForm1.btnLoadSVGDocClick(Sender: TObject);
var
Doc: Variant;
slSVG: TStringList;
begin
slSVG := TStringList.Create;
try
slSVG.LoadFromFile('C:\DELPHI\_test\BrowserSVGViewer\steamreactor.svg');
// Todo: Make corrections to the SVG document text
if NOT Assigned(wb1.Document) then
wb1.Navigate('about:blank');
Doc := wb1.Document;
Doc.Clear;
Doc.Write(slSVG.Text);
Doc.Close;
//wb1.Refresh;
finally
slSVG.Free;
end;
end;
Unfortunately, the SVG is not shown in the TWebBrowser
! What am I doing wrong? I even tried wb1.Refresh;
, but it does not help.
The Internet Explorer control is not quite designed to be given content on the fly. Therefore, my standard approach is to save my content to a temporary file:
type
TForm1 = class(TForm)
WebBrowser1: TWebBrowser;
btnLoadSvg: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnLoadSvgClick(Sender: TObject);
private
FTempFiles: TList<TFileName>;
public
end;
implementation
uses
IOUtils;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FTempFiles := TList<TFileName>.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if Assigned(FTempFiles) then
for var TempFile in FTempFiles do
Winapi.Windows.DeleteFile(PChar(TempFile));
end;
procedure TForm1.btnLoadSvgClick(Sender: TObject);
begin
var SvgText := TFile.ReadAllText('K:\flower.svg', TEncoding.UTF8);
var TempFileName := ChangeFileExt(TPath.GetTempFileName, '.svg');
FTempFiles.Add(TempFileName);
TFile.WriteAllText(TempFileName, SvgText, TEncoding.UTF8);
WebBrowser1.Navigate(TempFileName);
end;
This is robust. For instance, even if the user presses F5 while the control has focus, the document will still be there.