From 8f080922446313698730071fd92ca15900e6a941 Mon Sep 17 00:00:00 2001 From: Kurt Date: Fri, 10 May 2019 17:47:17 -0400 Subject: Add SplitText() method for splitting utf-8 strings constrained by rendered width --- splittext.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 splittext.go (limited to 'splittext.go') diff --git a/splittext.go b/splittext.go new file mode 100644 index 0000000..3902199 --- /dev/null +++ b/splittext.go @@ -0,0 +1,54 @@ +package gofpdf + +import ( + "math" + // "strings" + "unicode" +) + +// 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 { + c := s[i] + l += cw[c] + if unicode.IsSpace(c) { + // if c == ' ' || c == '\t' || c == '\n' { + sep = i + } + if c == '\n' || l > wmax { + if sep == -1 { + if i == j { + i++ + } + sep = i + } else { + i = sep + 1 + } + lines = append(lines, string(s[j:sep])) + sep = -1 + j = i + l = 0 + } else { + i++ + } + } + if i != j { + lines = append(lines, string(s[j:i])) + } + return lines +} -- cgit v1.2.1-24-ge1ad From 5cb8bab84fe08b93191ed0385c016592d2ac7cc4 Mon Sep 17 00:00:00 2001 From: hyzgh <31174102+hyzgh@users.noreply.github.com> Date: Tue, 20 Aug 2019 19:50:37 +0800 Subject: fix split line bug Change-Id: I224a7ec1af8386dcbef757c76389fb88316401bc --- splittext.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'splittext.go') diff --git a/splittext.go b/splittext.go index 3902199..525f93b 100644 --- a/splittext.go +++ b/splittext.go @@ -26,8 +26,7 @@ func (f *Fpdf) SplitText(txt string, w float64) (lines []string) { for i < nb { c := s[i] l += cw[c] - if unicode.IsSpace(c) { - // if c == ' ' || c == '\t' || c == '\n' { + if unicode.IsSpace(c) || isChinese(c) { sep = i } if c == '\n' || l > wmax { -- cgit v1.2.1-24-ge1ad