package gofpdf import ( "math" ) // SplitText splits UTF-8 encoded text into several lines using the current // font. Each line has its length limited to a maximum width given by w. This // function can be used to determine the total height of wrapped text for // vertical placement purposes. func (f *Fpdf) SplitText(txt string, w float64) (lines []string) { cw := f.currentFont.Cw // 字符宽度 wmax := int(math.Ceil((w - 2*f.cMargin) * 1000 / f.fontSize)) // 框的宽度 s := []rune(txt) // Return slice of UTF-8 runes nb := len(s) // 字符长度 // 去掉结尾的换行符 for nb > 0 && s[nb-1] == '\n' { nb-- } s = s[0:nb] //去掉结尾的换行符 //sep := -1 i := 0 // 遍历时的下标 j := 0 // 换行时保留的上一行结束的位置 l := 0 // 现在的长度 // 遍历字符串(去掉换行符之后的) for i < nb { // 这里是为了防止内存溢出,曾出现过前面是汉字后面是非汉字,lines为["汉字汉字汉字","","","".....]无限个""导致内存溢出 if len(lines) > len(s) { break } c := s[i] // 当前字符 l += cw[c] // 当前需要的长度 //if unicode.IsSpace(c) || isChinese(c) { // 判断是不是空格类字符和中文 // sep = i //} // 如果换行或者超长了 if c == '\n' || l > wmax { /////////////// // 如果第一个字就超宽了,别循环了,会死循环 if i == 0 { break } //if sep == -1 { // if i == j { // i++ // } // sep = i //} else { // /////////////// // //i = sep + 1 // ////////////// // i = sep //} lines = append(lines, string(s[j:i])) //sep = -1 j = i l = 0 } else { i++ } } // 把最后一行补上 if i != j { lines = append(lines, string(s[j:i])) } return lines }