Skip to content

Commit

Permalink
Set error condition if out-of-range Unicode rune is encountered in Ge…
Browse files Browse the repository at this point in the history
…tStringWidth
  • Loading branch information
Kurt Jung committed Sep 4, 2013
1 parent 9b78fbb commit 8458881
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
13 changes: 12 additions & 1 deletion fpdf.go
Original file line number Diff line number Diff line change
Expand Up @@ -658,9 +658,20 @@ func (f *Fpdf) SetTextColor(r, g, b int) {

// Returns the length of a string in user units. A font must be selected.
func (f *Fpdf) GetStringWidth(s string) float64 {
if f.err != nil {
return 0
}
w := 0
count := rune(len(f.currentFont.Cw))
for _, ch := range s {
w += f.currentFont.Cw[ch]
if ch < count {
w += f.currentFont.Cw[ch]
} else {
if f.err == nil {
f.err = fmt.Errorf("Unicode strings not supported")
}
return 0
}
}
return float64(w) * f.fontSize / 1000
}
Expand Down
20 changes: 18 additions & 2 deletions ttfparser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ package gofpdf_test
import (
"code.google.com/p/gofpdf"
"fmt"

// "testing"
// "testing"
)

func ExampleTtfParse() {
Expand Down Expand Up @@ -67,3 +66,20 @@ func ExampleTtfParse() {
// }
// }
// }

func ExampleFpdf_GetStringWidth() {
pdf := gofpdf.New("", "", "", FONT_DIR)
pdf.SetFont("Helvetica", "", 12)
pdf.AddPage()
for _, s := range []string{"Hello", "世界"} {
fmt.Printf("Width of \"%s\" is %.2f\n", s, pdf.GetStringWidth(s))
if pdf.Err() {
fmt.Println(pdf.Error())
}
}
pdf.Close()
// Output:
// Width of "Hello" is 9.64
// Width of "世界" is 0.00
// Unicode strings not supported
}

0 comments on commit 8458881

Please sign in to comment.