Reputation: 199
I have a email client which allows the user to change font, font size, bold, italics etc.
The issue l am having is when l try to change the font size of the selection either up or down i get a "EVariantTypeCastError" with a message of "Could not convert variant of type Null into type OleStr". This exception gets thrown on TextRange.queryCommandValue('FONTSIZE').
procedure TForm1.act_FontIncreaseExecute(Sender: TObject);
var
Selection: IHTMLSelectionObject;
HtmlPage: IHTMLDocument2;
TextRange: IHTMLTxtRange;
Parent: IHTMLElement2;
s: string;
i, mode: Integer;
begin
HtmlPage := self.HtmlEditor.Document as IHTMLDocument2;
Selection := HtmlPage.Selection;
TextRange := Selection.createRange as IHTMLTxtRange;
if (TextRange <> nil) then
begin
s := TextRange.queryCommandValue('FONTSIZE');
val(s, i, mode);
if mode = 0 then
HtmlPage.execCommand('FONTSIZE', False, inttostr(i + 1))
end;
end;
Is this the correct approach to increase the size of the font for the selection?
Edit 1:
Sample HTML:
<HTML><HEAD></HEAD>
<BODY>
<P>
<SPAN style='FONT-SIZE: 7pt;'>
Test Text
</SPAN>
</P>
</BODY></HTML>
It looks like the issue lies with the FONT-SIZE Style. When this is taken out then no exception is thrown. My end goal is to be able to copy and paste from outlook and this is a stripped down example of that. When l use other styles such as color:red then no exceptions are thrown. So it looks like its just FONT-SIZE that is has the issue with.
Edit 2
Exception Stack Trace
Upvotes: 1
Views: 970
Reputation: 21242
Is this the correct approach to increase the size of the font for the selection?
.queryCommandValue('FONTSIZE')
refers to the FONT
tag surrounding the text range (font sizes 1-7): e.g.
<FONT size=1>Test Text</FONT>
In your HTML example there is no FONT
tag. You need to handle the FONT-SIZE
Style attribute (CSS) of the surrounding SPAN
.
e.g. (no error checking to simplify the example):
if (TextRange <> nil) then
begin
...
ShowMessage(TextRange.parentElement.style.fontSize);
end;
This will show 7pt
.
Your specific exception cause is explained by @whosrdaddy answer (queryCommandValue
returns null for the reason I explained)
Upvotes: 3
Reputation: 11860
As you found out, in some cases the query will return NULL
and then the Val()
command will fail.
The solution is simple, assume standard font size when you get null:
procedure TForm1.FontIncreaseExecute;
var
Selection: IHTMLSelectionObject;
HtmlPage: IHTMLDocument2;
TextRange: IHTMLTxtRange;
s: OleVariant;
i, mode: Integer;
begin
HtmlPage := WebBrowser1.Document as IHTMLDocument2;
Selection := HtmlPage.Selection;
TextRange := Selection.createRange as IHTMLTxtRange;
if (TextRange <> nil) then
begin
s := TextRange.queryCommandValue('FONTSIZE');
if VarisNull(s) then
s := 0; // fall back to standard font size
Val(s, i, mode);
if mode = 0 then
HtmlPage.execCommand('FONTSIZE', False, inttostr(i + 1))
end;
end;
Upvotes: 1