How do I underline text element in PDF?

Q: How do I underline text?

I know that PDF does not support underline style for text, but I would
like to achieve the same effect by drawing a line (i.e. path) under
the text.


A: You could add a line under text element using its bounding box. For
example:


text_element.GetBBox(bbox);

builder.PathBegin();
builder.MoveTo(bbox.x1, bbox.y1);
builder.LineTo(bbox.x2, bbox.y2);
Element line = builder.PathEnd();

// Set color attributes for the line…
line.SetPathFill(false);
line.SetPathStroke(true);

GState gs = line.GetGState();
gs.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB());
gs.SetStrokeColor(new ColorPt(1, 0, 0)); // red

// Set line thickness to be some fraction of text height
gs.SetLineWidth(bbox.Height()/100.0);

writer.WriteElement(line); // Add line to PDF page

Please note that the above pseudocode uses ElementBuilder and
ElementWriter to add new content to exisitng page. For an example of
how to use these classes please take a look at ElementBuilder sample
project (or http://www.pdftron.com/pdfnet/faq.html#how_watermark).

Q: Using this approach the line thickness, doesn’t increase
proportionately when I make the text bold. When you print bold text,
the increase in the thickness of the character should be higher than
the increase in the size of the bounding rectangle.
-----
A: If you would like to put a stronger underline for bold fonts you
would also need to add some weight to take into account whether the
font is bold of not

Probably the best way it to obtain font weight using GDI+. If you
can't figure how to obtain font weight using GDI+, you could obtain
this value from PDF font as follows:

double GetFontWeight(pdftron.PDF.Font font)
{
double v = 400;
Obj font_desc = font.GetDescriptor();
if (font_desc != null) {
  Obj a = font_desc.FindObj("FontWeight");
  if (a != null) {
    v = a.GetNumber();
  }
}
return v;
}

Font 'weight' is a number in the range 300-900 where each number
indicates a weight that is at least as dark as its predecessor. A
value of 400 indicates a normal weight; 700 indicates bold.