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) document.Open() '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 Col.AddText(P) 'Call to stupid Go() method which actually writes the content to the stream. Col.Go() document.Close() End Using
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).
Nice Post. It helped me.
Thank you so much.
—
Raaghav
How do i get to use the DIM?
Dim is VB.Net which is what the post was written in but is essentially the same as C#’s var
HI..It really help me,thanks u very muc.
perfect post !! thank you
Tiny typo, you have the font as fontsarial.ttf, but I think it should be fonts\arial.ttf ?
Great post though!