Hypersapien
Hypersapien

Reputation: 623

How to format HTML links in iTextSharp?

I am using iTextSharp to generate PDFs from data contained in a database. There is one text field that uses HTML formatting. I found the following code to take HTML blocks and insert them into a Paragraph.

Dim p As New Paragraph()
Dim htmlarraylist As List(Of IElement) = HTMLWorker.ParseToList(New StringReader(HtmlString), Nothing)

For k As Int32 = 0 To htmlarraylist(0).Chunks().Count() - 1
    Dim c As Chunk = htmlarraylist(0).Chunks(k)
    p.Add(c)
Next

The problem is that when a link is passed through this code, it isn't formatted like a link. I can click on it, but it's the same color as the rest of the text and isn't underlined.

Is there any way of globally formatting html links in iTextSharp like this?

Alternatively, is there any way of identifying which Chunks that are passed through the For statement above are, in fact, links, so I can format them individually inside the loop? I have stepped through the loop and looked at the object properties and can't find anything in the Chunk that might identify it as a link. The "Content" property merely contains the link text.

Upvotes: 0

Views: 293

Answers (1)

Chris Haas
Chris Haas

Reputation: 55447

The simplest way is to probably just use a stylesheet:

Dim SS As New StyleSheet()
SS.LoadTagStyle(HtmlTags.A, HtmlTags.COLOR, "blue")

And then pass that into the HTMLWorker object:

Dim htmlarraylist = HTMLWorker.ParseToList(New StringReader(HtmlString), SS)

If for some reason you don't want to do that you could also just address it in your For loop:

Dim htmlarraylist = HTMLWorker.ParseToList(New StringReader(HtmlString), Nothing)
For Each el In htmlarraylist
    For Each C In el.Chunks
        If C.Role.Equals(PdfName.LINK) Then
            C.Font.Color = BaseColor.BLUE
        End If
    p.Add(C)
    Next
Next

Upvotes: 1

Related Questions