diff --git a/model/font_simple.go b/model/font_simple.go index 426e7ab3..577552d7 100644 --- a/model/font_simple.go +++ b/model/font_simple.go @@ -6,8 +6,11 @@ package model import ( + "bytes" "errors" + "io" "io/ioutil" + "os" "strings" "github.com/unidoc/unipdf/v3/common" @@ -379,16 +382,35 @@ func (font *pdfFontSimple) ToPdfObject() core.PdfObject { return font.container } -// NewPdfFontFromTTFFile loads a TTF font and returns a PdfFont type that can be used in text -// styling functions. +// NewPdfFontFromTTFFile loads a TTF font file and returns a PdfFont type +// that can be used in text styling functions. // Uses a WinAnsiTextEncoder and loads only character codes 32-255. func NewPdfFontFromTTFFile(filePath string) (*PdfFont, error) { + f, err := os.Open(filePath) + if err != nil { + common.Log.Debug("ERROR: reading TTF font file: %v", err) + return nil, err + } + defer f.Close() + + return NewPdfFontFromTTF(f) +} + +// NewPdfFontFromTTF loads a TTF font and returns a PdfFont type that can be +// used in text styling functions. +// Uses a WinAnsiTextEncoder and loads only character codes 32-255. +func NewPdfFontFromTTF(r io.ReadSeeker) (*PdfFont, error) { const minCode = textencoding.CharCode(32) const maxCode = textencoding.CharCode(255) - ttf, err := fonts.TtfParseFile(filePath) + ttfBytes, err := ioutil.ReadAll(r) if err != nil { - common.Log.Debug("ERROR: loading ttf font: %v", err) + common.Log.Debug("ERROR: Unable to read font contents: %v", err) + return nil, err + } + ttf, err := fonts.TtfParse(bytes.NewReader(ttfBytes)) + if err != nil { + common.Log.Debug("ERROR: loading TTF font: %v", err) return nil, err } @@ -457,12 +479,6 @@ func NewPdfFontFromTTFFile(filePath string) (*PdfFont, error) { descriptor.ItalicAngle = core.MakeFloat(float64(ttf.ItalicAngle)) descriptor.MissingWidth = core.MakeFloat(k * float64(ttf.Widths[0])) - ttfBytes, err := ioutil.ReadFile(filePath) - if err != nil { - common.Log.Debug("ERROR: Unable to read file contents: %v", err) - return nil, err - } - stream, err := core.MakeStream(ttfBytes, core.NewFlateEncoder()) if err != nil { common.Log.Debug("ERROR: Unable to make stream: %v", err) diff --git a/model/font_test.go b/model/font_test.go index 9f6dafc1..b0f3c151 100644 --- a/model/font_test.go +++ b/model/font_test.go @@ -864,3 +864,10 @@ func newStandandTextEncoder(t *testing.T) textencoding.SimpleEncoder { } return enc } + +func TestNewFontFromFile(t *testing.T) { + _, err := model.NewPdfFontFromTTFFile("testdata/font/OpenSans-Regular.ttf") + if err != nil { + t.Fatalf("Failed to load font from file. err=%v", err) + } +} diff --git a/model/testdata/font/OpenSans-Regular.ttf b/model/testdata/font/OpenSans-Regular.ttf new file mode 100644 index 00000000..29bfd35a Binary files /dev/null and b/model/testdata/font/OpenSans-Regular.ttf differ