iTextSharp draw line under text (heading) at a random location on a page

Rob picture Rob · Jun 16, 2011 · Viewed 13.8k times · Source

does anyone know how I can draw a line under a heading (a short line of bold text) that may be located in a random location on a page.

e.g.

My Heading 1
---------------------------------------------- 

Some random paragraph


My Heading 2
----------------------------------------------

I can do it as I have done above using a line of Underscores _ but in order to get the line anywhere near the heading I have to set the font size at 2 which results in a spotty ugly line.

I can also add two chunks over the top of each other (one with the heading and one with _) similar to the first example in this article http://www.mikesdotnetting.com/Article/82/iTextSharp-Adding-Text-with-Chunks-Phrases-and-Paragraphs using the same font size but it seems that this only works at the top of the page, once I add other paragraphs and try to do it mid-way down the page the two chunks separate with a clear line-break at the end of the first chunk.

It seems you can draw lines in iTextSharp but I have no idea how to calculate the coordinates, as all the examples I have seen use this method to place a line at the top or bottom of the page in a fixed location.

Any help greatly appreciated.

Cheers Rob

Answer

Justin Ploof picture Justin Ploof · Jun 23, 2011

The LineSeperator object might be what you're looking for. Wrap it with a chunk and put it where you need it.

Here's a sample line seperator:

Chunk linebreak = new Chunk(new LineSeparator(4f, 100f, colorGrey, Element.ALIGN_CENTER, -1));
doc.Add(linebreak);