PDF for UWP | ComponentOne
Using PDF for UWP / Adding Text / Measuring Text
In This Topic
    Measuring Text
    In This Topic

    In many cases, you will need to check whether the string will fit on the page before you render it. You can use the C1PdfDocument.MeasureString method for that. C1PdfDocument.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:

    Visual Basic
    Copy Code
    Private Function RenderParagraph(text As String, font As Font, rect As Rect, rectPage As Rect) As Rect
    
        ' 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, Colors.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 Rect = _c1pdf.PageRectangle()
    rectPage.Inflate(-72, -72)
    Dim rect As Rect = rectPage
    Dim s As String
    For Each s In  myStringList
        rect = RenderParagraph(s, font, rect, rectPage)
    Next s
    

    C#
    Copy Code
    private Rect RenderParagraph(string text, Font font, Rect rect, Rect 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, Colors.Black, rect);
    
        // Update rectangle for next time.
        Rect.Offset(0, rect.Height);
        return rect;
    }
    
    // Use the RenderParagraph method.
    Font font = new Font("Arial", 10);
    Rect rectPage = _c1pdf.PageRectangle();
    rectPage.Inflate(-72, -72);
    Rect rect = rectPage;
    foreach (string s in myStringList)
    {
        rect = RenderParagraph(s, font, rect, rectPage);
    }