Calculate text height based on available width and font?

前端 未结 8 1465
醉酒成梦
醉酒成梦 2020-12-16 13:11

We are creating PDF documents on the fly from the database using PDFsharp.

I need to know the best way to calculate the height of the text area based on the font use

8条回答
  •  有刺的猬
    2020-12-16 14:07

    In case anyone still wants to find an answer, I've implemented a reasonably easy-to-understand method to find out the height of the resulting text.

    Public Function PrintString(text As String, ft As XFont, rect As XRect, graph As XGraphics, b As SolidBrush, Optional tf As XTextFormatter = Nothing) As Integer
        If Not IsNothing(tf) Then
            tf.DrawString(text, ft, b, rect)
        Else
            Dim drawLeft As New XStringFormat
            drawLeft.Alignment = XStringAlignment.Near
    
            graph.DrawString(text, ft, b, rect, drawLeft)
        End If
    
        Dim width As Double = graph.MeasureString(text, ft).Width
        Dim multiplier As Integer = 0
    
        While width > 0
            multiplier += 1
    
            width -= rect.Width
        End While
    
        Dim height As Double = (graph.MeasureString(text, ft).Height) * multiplier
        Return height
    End Function
    

    Explaining the code:

    First, print the text. I included an Optional XTextFormatter called tf because I use either XGraphics or XTextFormatters interchangeably in my application.

    Then, calculate how long the text was by MeasureString().Width.

    Then, calculate how many lines of text there were. This is done by dividing the total length of the text found earlier by the width of the provided rectangle (box) where the tax is printed. I did it with a while loop here.

    Multiply the height of the text (using graph.MeasureString().Height) by the number of lines there were. This is the final height of your text.

    Return the height value. Now, calling the PrintString() function will print the text provided out while returning the height of the printed text afterward.

提交回复
热议问题