Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code has to load a font file, how to embed inside the built binary

I have this code inside a Go package of mine. It must load the cmr10.ttf font file. So, the font file must be next to every executable which is using this package.


import (
    "github.com/deadsy/sdfx/sdf"
)

func Text(txt string, height, thickness, roundness float32) (sdf.SDF3, error) {
    f, err := sdf.LoadFont("cmr10.ttf")
    if err != nil {
        return nil, err
    }

    t := sdf.NewText(txt)

    s2d, err := sdf.TextSDF2(f, t, float64(height))
    if err != nil {
        return nil, err
    }

    // Extrude the 2D SDF to a 3D SDF.
    return sdf.ExtrudeRounded3D(s2d, float64(thickness), float64(roundness))
}

Question

Is there a way to avoid copying the cmr10.ttf font file next to any executable using this package?

For example, like embedding the font file into the built binary. If possible, how to exactly do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any other idea to try?

>Solution :

Starting with Go 1.16 the go tool has support for embedding static files directly in the executable binary. You can embed the binary data of the font file using the //go:embed directive:

import (
    _ "embed"
)

//go:embed cmr10.ttf
var cmr10FontData []byte

The content of cmr10.ttf will be inserted into the cmr10FontData variable by the compiler. For other options see What's the best way to bundle static resources in a Go program?

Now since github.com/deadsy/sdfx/sdf only offers an sdf.LoadFont(fname) helper function, you have to use github.com/golang/freetype/truetype to parse the font data. Note that sdf.LoadFont() also uses this under the hood, calling truetype.Parse() with the binary data of the font file:

f, err := truetype.Parse(cmr10FontData)
// Check error
// use f if no error
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading