Creating Simple PDF Files With iTextSharp - Working with fonts and text (
Page 2 of 4 )
Adding text to the document is quite easy. The most basic unit of text is the Chunk, which is simply a “chunk” of text that must have a consistent appearance. Here, we create a simple Chunk:
Chunk boo = new Chunk("Boo!");
Content must be manually added to the page:
doc.Add(boo);
We can stylize the text if we need to. Below, we make the text bold and big:
boo.Font.SetStyle(Font.BOLD);
boo.Font.Size = 72;
As you can see, the Font property, which is of the Font type, represents the text's font. Above, we make it bold and give it a size of 72 points. To set the style, we can either pass an appropriate integer value (these values can be found in Font, like Font.Bold), or we can pass a string to achieve the same effect:
boo.Font.SetStyle("bold");
Fonts can also be created and passed into the constructor when creating a Chunk:
Font small = new Font(Font.TIMES_ROMAN, 5);
Chunk smallText = new Chunk("This is small.", small);
Above, we create a font by specifying the font family (Times Roman) and a size (five points). However, we can specify several more properties in the constructor, such as the font style and the color. Below, we create a red, italicized font:
Font redItalic = new Font(Font.HELVETICA, Font.DEFAULTSIZE,
Font.ITALIC, Color.RED);
Fonts can also be quickly and easily created using the GetFont method of the FontFactory class:
Chunk hey = new Chunk("Hey.", FontFactory.GetFont("Courier", 12, Font.ITALIC));
There's also a Phrase class, which is a bit higher level than the Chunk class, but is created similarly:
Phrase p = new Phrase("This is a phrase.");