Creating Simple PDF Files With iTextSharp - Working with paragraphs (
Page 3 of 4 )
However, Chunk is a bit low-level. More often, you'll be using Paragraph, which represents a paragraph of text. A paragraph has space before it, and it can be indented. Unlike a Chunk, a paragraph's text does not have to be consistent. That is, portions of the text can be underlined, struck through, etc. Here's a basic Paragraph:
Paragraph hello = new Paragraph("Hello. This is a paragraph.");
A Paragraph can be styled just like a Chunk:
hello.Font.sestyle(Font.ITALIC);
However, applying styles to specific sections of text within a Paragraph is a bit trickier. To do this, we must break the Paragraph into Chunk objects and then style each Chunk object. Here, we create a paragraph with multiple styled sections of text:
Paragraph fancy = new Paragraph();
Chunk bold = new Chunk("This ");
bold.Font.SetStyle(Font.BOLD);
fancy.Add(bold);
Chunk italics = new Chunk("is a");
italics.Font.SetStyle(Font.ITALIC);
fancy.Add(italics);
Chunk big = new Chunk("fancy");
big.Font.Size = 20;
big.Font.SetStyle(Font.BOLD);
fancy.Add(big);
Chunk struck = new Chunk("paragraph.");
struck.Font.SetStyle(Font.STRIKETHRU);
fancy.Add(struck);
A paragraph will automatically have some spacing, but it's possible to add more:
Paragraph spaced =
new Paragraph("This has a lot of space around it.");
spaced.SpacingBefore = 72;
spaced.SpacingAfter = 72;
spaced.IndentationLeft = 72;
spaced.IndentationRight = 72;
Indenting the paragraph by setting the IndentationLeft property indents the entire paragraph, though. Often, you'll want to indent only the first line of a paragraph. This can be done by setting the FirstLineIndent property:
Paragraph p = new Paragraph();
p.FirstLineIndent = 36;
While paragraphs are left-aligned by default, the alignment can be changed using the Alignment property:
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_LEFT;
p.Alignment = Element.ALIGN_CENTER;
p.Alignment = Element.ALIGN_RIGHT;
p.Alignment = Element.ALIGN_JUSTIFIED;
The lines in a paragraph will naturally need some space between them, called a leading. The default leading will often do fine, but sometimes the leading must be modified. This can be done by setting the Leading property:
Paragraph spacy = new Paragraph();
spacy.Leading = 72;
The leading can also be specified in the constructor:
Paragraph spacy2 = new Paragraph(72);
Paragraph spacy3 = new Paragraph(72,
"The leading is an inch.");
The leading can also be calculated by multiplying the font size by a number. This feature can be used, for example, to double space a paragraph:
Paragraph doubleSpaced = new Paragraph();
doubleSpaced.MultipliedLeading = 2;