Can I add underlined text to a PDF page?

Q: I have text that I need to add to a page, underlined. However I don’t have an underlined font. How can I make the text underlined?
A: The approach at https://groups.google.com/d/msg/pdfnet-sdk/YcqIHkyNL4Y/Mlwk8F8yTCoJ is recommended. Here is complete VB.NET sample code showing how to do so:

Imports System

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF
Imports pdftron.PDF.Annots
Imports System.Collections

Module StamperTestVB
Dim pdfNetLoader As PDFNetLoader
Sub New()
pdfNetLoader = pdftron.PDFNetLoader.Instance()
End Sub

Sub GatherTextRects(ByRef reader As ElementReader, ByRef annot_rect As Rect, ByRef text_rects As ArrayList)
Dim element As Element = reader.Next()
While (Not IsNothing(element)) ’ Read page contents
Dim type As Element.Type = element.GetType()
If type = Element.Type.e_text Then
Dim text_rect As Rect = New Rect
element.GetBBox(text_rect)
If (text_rect.IntersectRect(text_rect, annot_rect)) Then
text_rects.Add(text_rect)
End If
ElseIf type = Element.Type.e_text_new_line Then
ElseIf type = Element.Type.e_form Then
reader.FormBegin() ’ Process form XObjects
GatherTextRects(reader, annot_rect, text_rects)
reader.End()
End If
element = reader.Next()
End While
End Sub

Function UnderlineTextInAnnotRect(ByRef doc As PDFDoc, ByRef page As Page, ByRef annot_rect As Rect)
Dim text_rects As ArrayList = New ArrayList

Using reader As ElementReader = New ElementReader
reader.Begin(page)
GatherTextRects(reader, annot_rect, text_rects)
reader.End()
End Using

Dim underline As Underline = underline.Create(doc, annot_rect)
underline.SetColor(new pdftron.PDF.ColorPt(1, 0, 0), 3)
Dim num_quads As Integer = 0
For Each r As Rect In text_rects
underline.SetQuadPoint(num_quads, New QuadPoint(New Point(r.x1, r.y1), New Point(r.x2, r.y1), New Point(r.x2, r.y2), New Point(r.x1, r.y2)))
num_quads = num_quads + 1
Next
underline.RefreshAppearance()
page.AnnotPushBack(underline)
underline.RefreshAppearance()
underline.Flatten(page)
End Function

Sub Main()

PDFNet.Initialize()

Dim input_path As String = “…/…/…/…/TestFiles/”
Dim output_path As String = “…/…/…/…/TestFiles/Output/”
Dim input_filename As String = “blank”

Try
Dim annot_rect As Rect = New Rect(10, 400, 160, 570)
Using doc As PDFDoc = New PDFDoc(input_path + input_filename + “.pdf”)
doc.InitSecurityHandler()

Dim first_page As Page = doc.GetPage(1)

Dim txt_annot As FreeText = FreeText.Create(doc, annot_rect)
txt_annot.SetContents((“The quick red fox jumps over the lazy brown dog.”))
first_page.AnnotPushBack(txt_annot)
txt_annot.RefreshAppearance()
txt_annot.Flatten(first_page)

UnderlineTextInAnnotRect(doc, first_page, annot_rect)

doc.Save(output_path + input_filename + “.modified.pdf”, SDFDoc.SaveOptions.e_linearized)
End Using
Catch ex As PDFNetException
Console.WriteLine(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Module