From 845888136482c81fd76860b57e254c0e8fa6c149 Mon Sep 17 00:00:00 2001 From: Kurt Jung Date: Wed, 4 Sep 2013 15:06:56 -0400 Subject: Set error condition if out-of-range Unicode rune is encountered in GetStringWidth --- fpdf.go | 13 ++++++++++++- ttfparser_test.go | 20 ++++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/fpdf.go b/fpdf.go index 7b286a2..a7fb350 100644 --- a/fpdf.go +++ b/fpdf.go @@ -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 } diff --git a/ttfparser_test.go b/ttfparser_test.go index 00f4030..9bb3d71 100644 --- a/ttfparser_test.go +++ b/ttfparser_test.go @@ -19,8 +19,7 @@ package gofpdf_test import ( "code.google.com/p/gofpdf" "fmt" - -// "testing" + // "testing" ) func ExampleTtfParse() { @@ -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 +} -- cgit v1.2.1-24-ge1ad