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

In many cases, you will need to check whether the string will fit on the page before you render it. You can use the MeasureString method for that. MeasureString returns a SizeF structure that contains the width and height of the string (in points) when rendered with a given font.

For example, the code below checks to see if a paragraph will fit on the current page and creates a page break if it has to. This will keep paragraphs together on a page:

To write code in Visual Basic

Visual Basic
Copy Code
Private Function RenderParagraph(text As String, font As Font, rect As RectangleF, rectPage As RectangleF) As RectangleF
      ' Calculate the necessary height.
    Dim sz As SizeF = _c1pdf.MeasureString(text, font, rect.Width)
    rect.Height = sz.Height
      ' If it won't fit this page, do a page break.
    If rect.Bottom > rectPage.Bottom Then
        _c1pdf.NewPage()
        rect.Y = rectPage.Top
    End If
      ' Draw the string.
    _c1pdf.DrawString(text, font, Brushes.Black, rect)
      ' Update rectangle for next time.
    Rect.Offset(0, rect.Height)
    Return rect
End Function
  ' Use the RenderParagraph method.
Dim font As New Font("Arial", 10)
Dim rectPage As RectangleF = _c1pdf.PageRectangle
rectPage.Inflate(-72, -72)
Dim rect As RectangleF = rectPage
Dim s As String
For Each s In  myStringList
    rect = RenderParagraph(s, font, rect, rectPage)
Next s

To write code in C#

C#
Copy Code
private RectangleF RenderParagraph(string text, Font font, RectangleF rect, RectangleF rectPage)
{
// Calculate the necessary height.
    SizeF sz = _c1pdf.MeasureString(text, font, rect.Width);
    rect.Height = sz.Height;
     // If it won't fit this page, do a page break.
    If (rect.Bottom > rectPage.Bottom)
    {
        _c1pdf.NewPage();
        rect.Y = rectPage.Top;
    }
     // Draw the string.
    _c1pdf.DrawString(text, font, Brushes.Black, rect);
     // Update rectangle for next time.
    Rect.Offset(0, rect.Height);
    return rect;
}
 // Use the RenderParagraph method.
Font font = new Font("Arial", 10);
RectangleF rectPage = _c1pdf.PageRectangle;
rectPage.Inflate(-72, -72);
RectangleF rect = rectPage;
foreach (string s in myStringList)
{
    rect = RenderParagraph(s, font, rect, rectPage);
}