Home > Mobile >  How can I get the font family name from a .ttf file in golang?
How can I get the font family name from a .ttf file in golang?

Time:01-29

As we know, a .ttf(or otf) font file's file name is not always the same with the font family name, for example, if I rename Arial.ttf to abcd.ttf, it's font family name is still Arial, so is there a package or library in golang to parse .ttf and get that name?

I've tried enter image description here

There are few methods of *truetype.Font

Name returns the Font's name value for the given NameID

Where can I the the NameID? enter image description here


Edit:

It turns out that NameID is a go constant that represents a field of the TrueType font attributes, I found that the value of NameIDPostscriptName field will be used as font unique name, for example, a .fcpxml file will use this value as it's font name

The following snippet can get the unique font name of a .ttf file

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"

    // the original freetype has a bug for utf8: https://github.com/golang/freetype/issues/66
    // "github.com/golang/freetype"

    // so we use this beta one
    "github.com/beta/freetype"
    "github.com/beta/freetype/truetype"
)

// getPostscriptName returns the PostscriptName of a .ttf font file
func getPostscriptName(fontFilePath string) (postscriptName string, err error) {
    postscriptName = ""
    fontBytes, err := ioutil.ReadFile(fontFilePath)
    if err == nil {
        font, err := freetype.ParseFont(fontBytes)
        if err == nil {
            postscriptName = font.Name(truetype.NameIDPostscriptName)
        }
    }
    return postscriptName, err
}

func main() {
    fontFileRelative := "Downloads/New Folder With Items 5/Arial.ttf"
    homeDir, _ := os.UserHomeDir()
    fontFile := filepath.Join(homeDir, fontFileRelative)

    postscriptName, _ := getPostscriptName(fontFile)
    fmt.Println(postscriptName)
}

CodePudding user response:

It is possible to read the data of a ttf file with this go library freetype, you just need to provide the font data and it will parse all the data. There is also an article about reading ttf files content manually with javascipt here.

Edit: If you are using freetype to get the family name or other information, you can use the Name reciever function of the struct, it accepts a NameId which is an alias for uint16. (You can find the complete table of the valid value here in the name id codes section)

for example, you can get the font family name by using the following code:

package main

import (
    "fmt"
    "io/ioutil"

    "github.com/golang/freetype"
)

func main() {
    fontFile := "./font.ttf"
    fontBytes, err := ioutil.ReadFile(fontFile)
    font, err := freetype.ParseFont(fontBytes)
    if err == nil {
        fmt.Println(font.Name(1))
    }
}
  •  Tags:  
  • Related