Setting a Paragraph’s Absolute Position with iTextSharp

Man, you’d think this would have been easier. The Paragraph object in iTextSharp doesn’t have a position property so you can’t absolutely position it. If you search online they’ll tell you to use a PdfContentByte instead which does not work if you want to handle multiple lines automatically. Also, and more important for my case, PdfContentByte only allows you to specify a BaseFont which means unless your actual file is BOLD/ITALIC you can’t specify those options. The trick is to embed a Paragraph in a ColumnText object which can be absolutely positioned.

        'Create a PdfDocument
        Dim document As New Document(PageSize.LETTER)
        'Create a file on the desktop called "Test.pdf"
        Using outputStream As New FileStream(Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read)
            'Associate the pdf with the output stream, get access to the PdfWriter object
            Dim w = PdfWriter.GetInstance(document, outputStream)

            'Get access to the raw PdfContentBytes
            Dim cb = w.DirectContent

            'ColumnText can contain paraphraphs as well as be abolsutely positioned
            Dim Col As New ColumnText(cb)

            'Set the x,y,width,height
            Col.SetSimpleColumn(20, 20, 500, 100)

            'Create our paragraph
            Dim P As New Paragraph()
            'Create our base font, assumes you have arial installed in the normal location and that CP1252 works with it
            Dim BF = BaseFont.CreateFont(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows), "Fontsarial.ttf"), BaseFont.CP1252, False)
            'Add two chunks that will be placed side-by-side but with different font weights
            P.Add(New Chunk("BOLD TEXT: ", New Font(BF, 10.0, iTextSharp.text.Font.BOLD)))
            P.Add(New Chunk("NORMAL TEXT", New Font(BF, 10.0, iTextSharp.text.Font.NORMAL)))
            'Add the paragraph to the ColumnText
            'Call to stupid Go() method which actually writes the content to the stream.
        End Using

7 thoughts on “Setting a Paragraph’s Absolute Position with iTextSharp

  1. Thanks for this awesome post. It’s just what I needed. A clarification on ColumnText.SetSimpleColumn though. It’s not x,y,width,height. It’s (lower-left x, lower-left y, upper-right x, upper-right y).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.