之前在寫列印報表功能時,小姐打字一次常常就打一長串不換行,導致列印時 報表破版。因為螢幕看起來一行可以打20字,可是報表長度一行可能只能放得下15字而已
也就是說 我要去偵測 只要一行超過15字時,就要自動插入一個換行的符號
所以我寫了一個叫做 wordsplit的function 使用很簡單
就跟
TextBox2.Text = wordsplit(10, TextBox1.Text) 一樣
TextBox1.Text 就是你原始的input資料,而那個10的數字就是多少字要換行。
以後你只要call 這個function然後告訴他幾個字要換行一次就可以了。
Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox2.Text = wordsplit(10, TextBox1.Text) End Sub Function wordsplit(ByVal Line_num As Integer, input As String) As String Dim a As Array Dim output = "" a = Split(input, vbCrLf) For i As Integer = 0 To a.Length - 1 Step 1 If a(i).Length > Line_num Then For number As Integer = Fix(a(i).Length / Line_num) To 1 Step -1 a(i) = a(i).Insert(Line_num * number, vbCrLf) Next End If output = output + a(i) + vbCrLf Next Return output End Function End Class
後記:
因為寫完後小姐表示 怎切割的長度不太對,後來才想到中文其實是佔用兩個byte的空間,但是英文只有一個byte也就是全形半形的概念,所以中文其實要算兩個字(byte)的寬度而英文只能算一個字的寬度
所以我又改寫了一個出來
Public Class Form1 Function wordsplit(ByVal Line_num As Integer, input As String) As String Dim a As Array Dim output = "" Dim strLen As String a = Split(input, vbCrLf) For k As Integer = 0 To a.Length - 1 Step 1 Dim i = 1 Dim vbvcrf = 0 '塞換行符號算兩字元 Dim tempoutput As String tempoutput = a(k) For j As Integer = 1 To a(k).Length Step 1 strLen = Mid(a(k), i, j - i + 1) If System.Text.Encoding.Default.GetBytes(strLen).Length >= Line_num Then tempoutput = tempoutput.Insert(j + vbvcrf * 2, vbCrLf) vbvcrf = vbvcrf + 1 i = j + 1 End If Next output = output + tempoutput + vbCrLf Next Return output End Function Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click TextBox2.Text = wordsplit(10, TextBox1.Text) End Sub End Class
上面這個就是依照BYTE的寬度在算了 也就是把每個中文字都當兩個字來判斷長度,
這樣中英文混雜來排版列印大抵上應該也比較沒問題了(最多差半個字的排版這樣)