我想出的另一个解决方案是使用 VB.NET,特别是 TextRenderer.MeasureText() 函数。
为了完成这项工作,我在报告中添加了以下代码:
Public Function TextWidth(str As String) AS Double
'Returns the width, in pixels, of a string, assuming Tahoma size 8.
Dim size As System.Drawing.SizeF
Dim font As New system.Drawing.Font("Tahoma", 8)
size = System.Windows.Forms.TextRenderer.MeasureText(str, font)
TextWidth = size.Width
End Function
Public Function TextCap(str As String, maxWidth As Integer, Optional suffix As String = "") As String
'Truncates a string to fit within maxWidth pixels, optionally adding a suffix string if
'any characters were truncated.
Dim w As Integer, l As Integer
l = Len(str)
w = TextWidth(str)
For i As Integer = 1 To 10
If (w > maxWidth) Then
l = (l * maxWidth / w)
If (l < 0) Then
l = 0
Exit For
End If
w = TextWidth(Left(str, l) + suffix)
Else
Exit For
End If
Next i
If l < Len(str) Then
TextCap = Left(str, l) + suffix
Else
TextCap = Left(str, l)
End If
End Function
记得添加对程序集 System.Drawing (2.0.0.0) 和 System.Windows.Forms (2.0.0.0) 的引用。 TextWidth 函数将使用 Tahoma 字体,大小 8 计算文本字符串的宽度。通过将字体名称和字体大小作为附加参数添加到这两个函数中,可以轻松实现动态化。
从这样的 SSRS 表达式调用 TextCap 函数时:
=Code.TextCap(Fields!CustomerName.Value, 150, "...")
文本将自动被截断为 150 像素,并且将添加后缀参数“...”以防任何字符被截断。