Calculate text height based on available width and font?

前端 未结 8 1525
醉酒成梦
醉酒成梦 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:01

    The OP asked how to calculate text height based on available width and font. Windows .NET provides an API call for this which takes a width argument; the version of PDFsharp I'm using (0.9.653, .NET 1.1) does not.

    My solution - use the .NET API call with a Graphics object allocated for a custom-created Bitmap object to get the answer.

    What worked for me was to use a Bitmap that had 100 DPI resolution (critical) and happened to be the size of a Portrait page (probably less critical).

    Then I just asked .NET what the pixel size would be for painting on that bitmap.

    You probably will then want to convert the units from 1/100th of an inch to Points (for PDFsharp).

    ''' Adapted Code - this not tested or even compiled - Caveat Emptor!
    ''' Target: Visual Basic, .NET 1.1 (VS2003) [adapt as necessary]
    
    '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '
    '  GraphicsAlt.MeasureString() does substantially what System.Drawing MeasureString(...,Integer) does.
    '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '
    Public Module GraphicsAlt
    
        '
        ' Static data used Only to compute MeasureString() below.
        '
        '     Cache a single copy of these two objects, to address an otherwise unexplained intermittent exception.
        '
        Private Shared myImage As Bitmap = Nothing
        Private Shared myGraphics As Graphics = Nothing
    
        Public Shared Function GetMeasureGraphics() As Graphics
            If myImage Is Nothing Then
                myImage = New Bitmap(1700, 2200)  '' ... Specify 8.5x11 
                myImage.SetResolution(100, 100)   '' ... and 100 DPI (if you want different units, you might change this)
                myGraphics = Graphics.FromImage(myImage)
            End If
            Return myGraphics
        End Function
    
        'Given 1/100TH inch max width, return Rect to hold with units 1/100TH inch
        '
        Public Function MeasureString(ByVal text As String, ByVal aFont As System.Drawing.Font, ByVal width As Integer) As System.Drawing.SizeF
            Return (GraphicsAlt.GetMeasureGraphics()).MeasureString(text, aFont, width)
        End Function
    
    End Module
    

提交回复
热议问题