splittext.go 1018 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package gofpdf
  2. import (
  3. "math"
  4. // "strings"
  5. "unicode"
  6. )
  7. // SplitText splits UTF-8 encoded text into several lines using the current
  8. // font. Each line has its length limited to a maximum width given by w. This
  9. // function can be used to determine the total height of wrapped text for
  10. // vertical placement purposes.
  11. func (f *Fpdf) SplitText(txt string, w float64) (lines []string) {
  12. cw := f.currentFont.Cw
  13. wmax := int(math.Ceil((w - 2*f.cMargin) * 1000 / f.fontSize))
  14. s := []rune(txt) // Return slice of UTF-8 runes
  15. nb := len(s)
  16. for nb > 0 && s[nb-1] == '\n' {
  17. nb--
  18. }
  19. s = s[0:nb]
  20. sep := -1
  21. i := 0
  22. j := 0
  23. l := 0
  24. for i < nb {
  25. c := s[i]
  26. l += cw[c]
  27. if unicode.IsSpace(c) || isChinese(c) {
  28. sep = i
  29. }
  30. if c == '\n' || l > wmax {
  31. if sep == -1 {
  32. if i == j {
  33. i++
  34. }
  35. sep = i
  36. } else {
  37. i = sep + 1
  38. }
  39. lines = append(lines, string(s[j:sep]))
  40. sep = -1
  41. j = i
  42. l = 0
  43. } else {
  44. i++
  45. }
  46. }
  47. if i != j {
  48. lines = append(lines, string(s[j:i]))
  49. }
  50. return lines
  51. }