Skip to content

Commit

Permalink
Merge pull request #1 from HENNGE/experiment
Browse files Browse the repository at this point in the history
Enhance performance of loading font
  • Loading branch information
Toshiya Doi committed Apr 2, 2021
2 parents f358157 + bd43160 commit 50312cb
Show file tree
Hide file tree
Showing 7 changed files with 222 additions and 29 deletions.
29 changes: 12 additions & 17 deletions fontmaker/core/ttfparser.go
Expand Up @@ -74,7 +74,7 @@ type TTFParser struct {
groupingTables []CmapFormat12GroupingTable

//data of font
cacheFontData []byte
cachedFontData []byte

//kerning
useKerning bool //user config for use or not use kerning
Expand Down Expand Up @@ -209,23 +209,22 @@ func (t *TTFParser) Parse(filepath string) error {
if err != nil {
return err
}
buff := bytes.NewBuffer(data)
return t.parse(buff)
return t.ParseFontData(data)
}

//ParseByReader parse by io.reader
func (t *TTFParser) ParseByReader(rd io.Reader) error {
return t.parse(rd)
}

func (t *TTFParser) parse(rd io.Reader) error {

fontdata, err := ioutil.ReadAll(rd)
fontData, err := ioutil.ReadAll(rd)
if err != nil {
return err
}
//t.cacheFontData = fontdata
fd := bytes.NewReader(fontdata)

return t.ParseFontData(fontData)
}

// ParseFontData parses font data.
func (t *TTFParser) ParseFontData(fontData []byte) error {
fd := bytes.NewReader(fontData)

version, err := t.Read(fd, 4)
if err != nil {
Expand Down Expand Up @@ -254,7 +253,6 @@ func (t *TTFParser) parse(rd io.Reader) error {
return err
}

//fmt.Printf("offset\n")
offset, err := t.ReadULong(fd)
if err != nil {
return err
Expand All @@ -274,8 +272,6 @@ func (t *TTFParser) parse(rd io.Reader) error {
i++
}

//fmt.Printf("%+v\n", me.tables)

err = t.ParseHead(fd)
if err != nil {
return err
Expand Down Expand Up @@ -322,14 +318,13 @@ func (t *TTFParser) parse(rd io.Reader) error {
}
}

//fmt.Printf("%#v\n", me.widths)
t.cacheFontData = fontdata //t.readFontData(fontpath)
t.cachedFontData = fontData

return nil
}

func (t *TTFParser) FontData() []byte {
return t.cacheFontData
return t.cachedFontData
}

//ParseLoca parse loca table https://www.microsoft.com/typography/otspec/loca.htm
Expand Down
31 changes: 29 additions & 2 deletions gopdf.go
Expand Up @@ -823,12 +823,33 @@ func (gp *GoPdf) SetAnchor(name string) {
gp.anchors[name] = anchorOption{gp.curr.IndexOfPageObj, y}
}

//AddTTFFontByReader add font file
// AddTTFFontByReader adds font data by reader.
func (gp *GoPdf) AddTTFFontData(family string, fontData []byte) error {
return gp.AddTTFFontDataWithOption(family, fontData, defaultTtfFontOption())
}

// AddTTFFontDataWithOption adds font data with option.
func (gp *GoPdf) AddTTFFontDataWithOption(family string, fontData []byte, option TtfOption) error {
subsetFont := new(SubsetFontObj)
subsetFont.init(func() *GoPdf {
return gp
})
subsetFont.SetTtfFontOption(option)
subsetFont.SetFamily(family)
err := subsetFont.SetTTFData(fontData)
if err != nil {
return err
}

return gp.setSubsetFontObject(subsetFont, family, option)
}

// AddTTFFontByReader adds font file by reader.
func (gp *GoPdf) AddTTFFontByReader(family string, rd io.Reader) error {
return gp.AddTTFFontByReaderWithOption(family, rd, defaultTtfFontOption())
}

//AddTTFFontByReaderWithOption add font file
// AddTTFFontByReaderWithOption adds font file by reader with option.
func (gp *GoPdf) AddTTFFontByReaderWithOption(family string, rd io.Reader, option TtfOption) error {
subsetFont := new(SubsetFontObj)
subsetFont.init(func() *GoPdf {
Expand All @@ -841,6 +862,12 @@ func (gp *GoPdf) AddTTFFontByReaderWithOption(family string, rd io.Reader, optio
return err
}

return gp.setSubsetFontObject(subsetFont, family, option)
}

// setSubsetFontObject sets SubsetFontObj.
// The given SubsetFontObj is expected to be configured in advance.
func (gp *GoPdf) setSubsetFontObject(subsetFont *SubsetFontObj, family string, option TtfOption) error {
unicodemap := new(UnicodeMap)
unicodemap.init(func() *GoPdf {
return gp
Expand Down
130 changes: 122 additions & 8 deletions gopdf_test.go
@@ -1,6 +1,8 @@
package gopdf

import (
"bytes"
"errors"
"io/ioutil"
"log"
"os"
Expand All @@ -18,13 +20,13 @@ func BenchmarkPdfWithImageHolder(b *testing.B) {
pdf := GoPdf{}
pdf.Start(Config{PageSize: Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
pdf.AddPage()
err = pdf.AddTTFFont("loma", "./test/res/times.ttf")
err = pdf.AddTTFFont("LiberationSerif-Regular", "./test/res/LiberationSerif-Regular.ttf")
if err != nil {
b.Error(err)
return
}

err = pdf.SetFont("loma", "", 14)
err = pdf.SetFont("LiberationSerif-Regular", "", 14)
if err != nil {
log.Print(err.Error())
return
Expand Down Expand Up @@ -70,13 +72,13 @@ func TestPdfWithImageHolder(t *testing.T) {
pdf := GoPdf{}
pdf.Start(Config{PageSize: Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
pdf.AddPage()
err = pdf.AddTTFFont("loma", "./test/res/times.ttf")
err = pdf.AddTTFFont("LiberationSerif-Regular", "./test/res/LiberationSerif-Regular.ttf")
if err != nil {
t.Error(err)
return
}

err = pdf.SetFont("loma", "", 14)
err = pdf.SetFont("LiberationSerif-Regular", "", 14)
if err != nil {
log.Print(err.Error())
return
Expand Down Expand Up @@ -122,13 +124,13 @@ func TestRetrievingNumberOfPdfPage(t *testing.T) {
}

pdf.AddPage()
err := pdf.AddTTFFont("loma", "./test/res/times.ttf")
err := pdf.AddTTFFont("LiberationSerif-Regular", "./test/res/LiberationSerif-Regular.ttf")
if err != nil {
t.Error(err)
return
}

err = pdf.SetFont("loma", "", 14)
err = pdf.SetFont("LiberationSerif-Regular", "", 14)
if err != nil {
log.Print(err.Error())
return
Expand Down Expand Up @@ -184,13 +186,13 @@ func TestImageCrop(t *testing.T) {
}

pdf.AddPage()
err := pdf.AddTTFFont("loma", "./test/res/times.ttf")
err := pdf.AddTTFFont("LiberationSerif-Regular", "./test/res/LiberationSerif-Regular.ttf")
if err != nil {
t.Error(err)
return
}

err = pdf.SetFont("loma", "", 14)
err = pdf.SetFont("LiberationSerif-Regular", "", 14)
if err != nil {
log.Print(err.Error())
return
Expand Down Expand Up @@ -270,3 +272,115 @@ func TestBuffer(t *testing.T) {
fmt.Printf("+>%s\n", string(b2))
}*/

func BenchmarkAddTTFFontByReader(b *testing.B) {
ttf, err := os.Open("test/res/LiberationSerif-Regular.ttf")
if err != nil {
b.Error(err)
return
}
defer ttf.Close()

fontData, err := ioutil.ReadAll(ttf)
if err != nil {
b.Error(err)
return
}

for n := 0; n < b.N; n++ {
pdf := &GoPdf{}
pdf.Start(Config{PageSize: Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
if err := pdf.AddTTFFontByReader("LiberationSerif-Regular", bytes.NewReader(fontData)); err != nil {
return
}
}
}

func BenchmarkAddTTFFontData(b *testing.B) {
ttf, err := os.Open("test/res/LiberationSerif-Regular.ttf")
if err != nil {
b.Error(err)
return
}
defer ttf.Close()

fontData, err := ioutil.ReadAll(ttf)
if err != nil {
b.Error(err)
return
}

for n := 0; n < b.N; n++ {
pdf := &GoPdf{}
pdf.Start(Config{PageSize: Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
if err := pdf.AddTTFFontData("LiberationSerif-Regular", fontData); err != nil {
return
}
}
}

func TestReuseFontData(t *testing.T) {
ttf, err := os.Open("test/res/LiberationSerif-Regular.ttf")
if err != nil {
t.Error(err)
return
}
defer ttf.Close()

fontData, err := ioutil.ReadAll(ttf)
if err != nil {
t.Error(err)
return
}

pdf1 := &GoPdf{}
rst1, err := generatePDFBytesByAddTTFFontData(pdf1, fontData)
if err != nil {
t.Error(err)
return
}

// Reuse the parsed font data.
pdf2 := &GoPdf{}
rst2, err := generatePDFBytesByAddTTFFontData(pdf2, fontData)
if err != nil {
t.Error(err)
return
}

if bytes.Compare(rst1, rst2) != 0 {
t.Error(errors.New("The generated files must be exactly the same."))
return
}

if err := os.WriteFile("./test/out/result1_by_parsed_ttf_font.pdf", rst1, 0644); err != nil {
t.Error(err)
return
}
if err := os.WriteFile("./test/out/result2_by_parsed_ttf_font.pdf", rst1, 0644); err != nil {
t.Error(err)
return
}
}

func generatePDFBytesByAddTTFFontData(pdf *GoPdf, fontData []byte) ([]byte, error) {
pdf.Start(Config{PageSize: Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
if pdf.GetNumberOfPages() != 0 {
return nil, errors.New("Invalid starting number of pages, should be 0")
}

if err := pdf.AddTTFFontData("LiberationSerif-Regular", fontData); err != nil {
return nil, err
}

if err := pdf.SetFont("LiberationSerif-Regular", "", 14); err != nil {
return nil, err
}

pdf.AddPage()
if err := pdf.Text("Test PDF content."); err != nil {
return nil, err
}

return pdf.GetBytesPdfReturnErr()
}
4 changes: 2 additions & 2 deletions kern_test.go
Expand Up @@ -7,7 +7,7 @@ import (
)

func TestKern01(t *testing.T) {
Wo, err := kern01("test/res/times.ttf", "times", 'W', 'o')
Wo, err := kern01("test/res/LiberationSerif-Regular.ttf", "LiberationSerif-Regular", 'W', 'o')
if err != nil {
t.Error(err)
return
Expand All @@ -18,7 +18,7 @@ func TestKern01(t *testing.T) {
//return
}

Wi, err := kern01("test/res/times.ttf", "times", 'W', 'i')
Wi, err := kern01("test/res/LiberationSerif-Regular.ttf", "LiberationSerif-Regular", 'W', 'i')
if err != nil {
t.Error(err)
return
Expand Down
11 changes: 11 additions & 0 deletions subset_font_obj.go
Expand Up @@ -113,6 +113,17 @@ func (s *SubsetFontObj) SetTTFByReader(rd io.Reader) error {
return nil
}

//SetTTFData set ttf
func (s *SubsetFontObj) SetTTFData(data []byte) error {
useKerning := s.ttfFontOption.UseKerning
s.ttfp.SetUseKerning(useKerning)
err := s.ttfp.ParseFontData(data)
if err != nil {
return err
}
return nil
}

//AddChars add char to map CharacterToGlyphIndex
func (s *SubsetFontObj) AddChars(txt string) error {
for _, runeValue := range txt {
Expand Down
Binary file added test/res/LiberationSerif-Regular.ttf
Binary file not shown.
46 changes: 46 additions & 0 deletions test/res/LiberationSerif-SIL-Open-Font-License.txt
@@ -0,0 +1,46 @@
Digitized data copyright (c) 2010 Google Corporation
with Reserved Font Arimo, Tinos and Cousine.
Copyright (c) 2012 Red Hat, Inc.
with Reserved Font Name Liberation.

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.

The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the copyright statement(s).

"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.

"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.

5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.

0 comments on commit 50312cb

Please sign in to comment.