ComponentOne PDF for .NET
Drawing Text
Using ComponentOne PDF for .NET > Adding Text > Drawing Text

Adding text to PDF for .NET documents is easy – all the work is done by the DrawString method.

DrawString draws a given string at a specified location using a given font and brush. For example:

To write code in Visual Basic

Visual Basic
Copy Code
pdf.DrawString("Hello World!", font, Brushes.Black, rect)

To write code in C#

C#
Copy Code
pdf.DrawString("Hello World!", font, Brushes.Black, rect);

By default, DrawString will align the text to the left and to the top of the given rectangle, will wrap the string within the rectangle, and will not clip the output to the rectangle. You can change all these options by specifying a StringFormat parameter in the call to DrawString. The StringFormat has members that allow you to specify the horizontal alignment (Alignment), vertical alignment (LineAligmnent), and flags that control wrapping and clipping (FormatFlags).

For example, the code below creates a StringFormat object and uses it to align the text to the center of the rectangle, both vertically and horizontally:

To write code in Visual Basic

Visual Basic
Copy Code
Dim font As New Font("Arial", 12)
Dim rect As New RectangleF(72, 72, 100, 50)
Dim text As String = "Some long string to be rendered into a small rectangle. "
text = text & text & text & text & text & text
 ' Center align string.
Dim sf As New StringFormat()
sf.Alignment = StringAlignment.Center
sf.LineAlignment = StringAlignment.Center
pdf.DrawString(text, font, Brushes.Black, rect, sf)
pdf.DrawRectangle(Pens.Gray, rect)

To write code in C#

C#
Copy Code
Font font = new Font("Arial", 12);
RectangleF rect = new RectangleF(72, 72, 100, 50);
string text = "Some long string to be rendered into a small rectangle. ";
text = text + text + text + text + text + text;
 // Center align string.
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
pdf.DrawString(text, font, Brushes.Black, rect, sf);
pdf.DrawRectangle(Pens.Gray, rect);

Here is the resulting PDF document: