Correcting THMLLabel Scrollable Height and Width
Sometimes you will load an THTMLLabel with content including images which do not have predefined width or height, and the scrollable region will not be correctly sized.
The problem occurs because at content load time, the image’s height and width are unknown, so the browser/library are unable to compute the correct dimensions.
The following quick and dirty solution is not perfect, but it helps, by increasing the width and height of the THTMLLabel to be at least large enough, if not possibly larger than necessary. Ideally it would be exactly sized, but this is certainly better than undersized.
It works by cycling through all the content, looking for images or other content with calculated positions and dimensions, and adding their known values to the height and width.
Sometime after the image is loaded, so at least a second or so later, called FixHTMLLabelHeight(). This is easily done inside a timer. Multiple calls to it are safe and will not grow it endlessly wide or high, so you can leave the timer activiated as long as the form is visible with only a bit of slowness added to your browser.
procedure FixHTMLLabelHeight( c : THTMLLabel );
var
divc : TDomElement;
d : TDomElement;
nodes : TNodeList;
i, y, h, x, w : integer;
s : string;
newerheight, newerwidth : integer;
already : string;
begin
newerheight := 0;
newerwidth :=0;
c.parent.BeginUpdate;
c.autosize.height := True;
c.autosize.width := True;
c.parent.endupdate;
if c.ClientID = ‘’ then
c.ClientId := 'AutoHeight'+IntToStr(random(1, 10000 ));
divc := window.document.GetElementById( c.clientid );
if divc = Nil then exit;
nodes := divc.childNodes;
for i := 0 to nodes.length -1 do begin
h := 0;
y := 0;
try
d := TDomElement(nodes[i]);
y := THTMLElement(d).scrollTop;
h := THTMLElement(d).scrollHeight; // getAttribute( 'scrollHeight' );
x := THTMLElement(d).scrollLeft;
w := THTMLElement(d).scrollWidth; // getAttribute( 'scrollHeight' );
already := THTMLElement(d).getAttribute('NiceAutoCalc');
if h > 0 and already <> '1' then begin
if y+h > c.Height then inc( newerheight, y+h);
if x+w > c.width then inc( newerwidth, x+w );
d.setAttribute('NiceAutoCalc','1' );
end;
except
end;
end;
c.parent.beginupdate;
c.autosize.height := False;
c.autosize.width := false;
c.parent.endupdate;
c.height := c.height + newerheight;
c.width := c.width + newerwidth;
end;
procedure TForm1.Timer1Tick(Sender: TObject);
begin
FixHTMLLabelHeight( htmllabel1 );
Timer1.Enabled := False;
end;