font

package
v0.0.0-...-efd2d09 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2023 License: MIT Imports: 19 Imported by: 0

README

Font API reference

This library contains font parsers for WOFF, WOFF2, and EOT. It takes a byte-slice as input and converts it to SFNT formats (either TTF or OTF). As font formats for the web, WOFF, WOFF2, and EOT are really just containers for SFNT fonts (such as TTF and OTF) that have better compression.

The WOFF and WOFF2 converters have been testing using the validation tests from the W3C. Font collections (such as TTC and OTC) are not yet supported, but will be in the near future. Compression in EOT files are also not yet supported.

Usage

Import using:

import "github.com/tdewolff/canvas/font"

Then we can parse any byte-slice that is in the WOFF/WOFF2/EOT file format and extract its TTF/OTF content.

font, err := ioutil.ReadFile("DejaVuSerif.woff")
if err != nil {
    panic(err)
}

sfnt, err := font.ToSFNT(font)
if err != nil {
    panic(err)
}

or using an io.Reader

font, err := os.Open("DejaVuSerif.woff")
if err != nil {
    panic(err)
}

font, err = font.NewSFNTReader(font)
if err != nil {
    panic(err)
}
WOFF
woff, err := ioutil.ReadFile("DejaVuSerif.woff")
if err != nil {
    panic(err)
}

sfnt, err := font.ParseWOFF(woff)
if err != nil {
    panic(err)
}

ext := font.Extension(sfnt)
if err = ioutil.WriteFile("DejaVuSerif"+ext, sfnt, 0644); err != nil {
    panic(err)
}

Tested using https://github.com/w3c/woff/tree/master/woff1/tests.

WOFF2
woff2, err := ioutil.ReadFile("DejaVuSerif.woff2")
if err != nil {
    panic(err)
}

sfnt, err := font.ParseWOFF2(woff2)
if err != nil {
    panic(err)
}

ext := font.Extension(sfnt)
if err = ioutil.WriteFile("DejaVuSerif"+ext, sfnt, 0644); err != nil {
    panic(err)
}

Tested using https://github.com/w3c/woff2-tests.

EOT
eof, err := ioutil.ReadFile("DejaVuSerif.eot")
if err != nil {
    panic(err)
}

sfnt, err = font.ParseEOT(eot)
if err != nil {
    panic(err)
}

ext := font.Extension(sfnt)
if err = ioutil.WriteFile("DejaVuSerif"+ext, sfnt, 0644); err != nil {
    panic(err)
}

License

Released under the MIT license.

Documentation

Index

Constants

View Source
const (
	PlatformUnicode   = PlatformID(0)
	PlatformMacintosh = PlatformID(1)
	PlatformWindows   = PlatformID(3)
	PlatformCustom    = PlatformID(4)
)

see PlatformID

View Source
const (
	EncodingUnicode2BMP                 = EncodingID(3)
	EncodingUnicode2FullRepertoir       = EncodingID(4)
	EncodingUnicodeVariationSequences   = EncodingID(5)
	EncodingUnicodeFullRepertoire       = EncodingID(6)
	EncodingMacintoshRoman              = EncodingID(0)
	EncodingMacintoshJapanese           = EncodingID(1)
	EncodingMacintoshChineseTraditional = EncodingID(2)
	EncodingMacintoshKorean             = EncodingID(3)
	EncodingMacintoshArabic             = EncodingID(4)
	EncodingMacintoshHebrew             = EncodingID(5)
	EncodingMacintoshGreek              = EncodingID(6)
	EncodingMacintoshRussian            = EncodingID(7)
	EncodingMacintoshRSymbol            = EncodingID(8)
	EncodingMacintoshDevanagari         = EncodingID(9)
	EncodingMacintoshGurmukhi           = EncodingID(10)
	EncodingMacintoshGujarati           = EncodingID(11)
	EncodingMacintoshOriya              = EncodingID(12)
	EncodingMacintoshBengali            = EncodingID(13)
	EncodingMacintoshTamil              = EncodingID(14)
	EncodingMacintoshTelugu             = EncodingID(15)
	EncodingMacintoshKannada            = EncodingID(16)
	EncodingMacintoshMalayalam          = EncodingID(17)
	EncodingMacintoshSinhalese          = EncodingID(18)
	EncodingMacintoshBurmese            = EncodingID(19)
	EncodingMacintoshKhmer              = EncodingID(20)
	EncodingMacintoshThai               = EncodingID(21)
	EncodingMacintoshLaotian            = EncodingID(22)
	EncodingMacintoshGeorgian           = EncodingID(23)
	EncodingMacintoshArmenian           = EncodingID(24)
	EncodingMacintoshChineseSimplified  = EncodingID(25)
	EncodingMacintoshTibetan            = EncodingID(26)
	EncodingMacintoshMongolian          = EncodingID(27)
	EncodingMacintoshGeez               = EncodingID(28)
	EncodingMacintoshSlavic             = EncodingID(29)
	EncodingMacintoshVietnamese         = EncodingID(30)
	EncodingMacintoshSindhi             = EncodingID(31)
	EncodingMacintoshUninterpreted      = EncodingID(32)
	EncodingWindowsSymbol               = EncodingID(0)
	EncodingWindowsUnicodeBMP           = EncodingID(1)
	EncodingWindowsShiftJIS             = EncodingID(2)
	EncodingWindowsPRC                  = EncodingID(3)
	EncodingWindowsBig5                 = EncodingID(4)
	EncodingWindowsWansung              = EncodingID(5)
	EncodingWindowsJohab                = EncodingID(6)
	EncodingWindowsUnicodeFullRepertoir = EncodingID(10)
)

see EncodingID

View Source
const (
	NameCopyrightNotice            = NameID(0)
	NameFontFamily                 = NameID(1)
	NameFontSubfamily              = NameID(2)
	NameUniqueIdentifier           = NameID(3)
	NameFull                       = NameID(4)
	NameVersion                    = NameID(5)
	NamePostScript                 = NameID(6)
	NameTrademark                  = NameID(7)
	NameManufacturer               = NameID(8)
	NameDesigner                   = NameID(9)
	NameDescription                = NameID(10)
	NameVendorURL                  = NameID(11)
	NameDesignerURL                = NameID(12)
	NameLicense                    = NameID(13)
	NameLicenseURL                 = NameID(14)
	NamePreferredFamily            = NameID(16)
	NamePreferredSubfamily         = NameID(17)
	NameCompatibleFull             = NameID(18)
	NameSampleText                 = NameID(19)
	NamePostScriptCID              = NameID(20)
	NameWWSFamily                  = NameID(21)
	NameWWSSubfamily               = NameID(22)
	NameLightBackgroundPalette     = NameID(23)
	NameDarkBackgroundPalette      = NameID(24)
	NameVariationsPostScriptPrefix = NameID(25)
)

see NameID

View Source
const (
	UnknownScript = ScriptTag("")
	DefaultScript = ScriptTag("DFLT")
)
View Source
const (
	UnknownLanguage = LanguageTag("")
	DefaultLanguage = LanguageTag("DFLT") // permanently reserved and not used in font

)
View Source
const MaxCmapSegments = 20000

MaxCmapSegments is the maximum number of cmap segments that will be accepted.

View Source
const (
	UnknownFeature = FeatureTag("")
)

Variables

View Source
var ErrExceedsMemory = fmt.Errorf("memory limit exceded")

ErrExceedsMemory is returned if the font is malformed.

View Source
var ErrInvalidFontData = fmt.Errorf("invalid font data")

ErrInvalidFontData is returned if the font is malformed.

View Source
var MaxMemory uint32 = 30 * 1024 * 1024

MaxMemory is the maximum memory that can be allocated by a font.

Functions

func Extension

func Extension(b []byte) string

Extension returns the file extension for a given font. An empty string is returned when the font is not recognized.

func FromGoFreetype

func FromGoFreetype(font *truetype.Font) []byte

FromGoFreetype parses a structure from truetype.Font to a valid SFNT byte slice.

func FromGoSFNT

func FromGoSFNT(font *sfnt.Font) []byte

FromGoSFNT parses a structure from sfnt.Font to a valid SFNT byte slice.

func MediaType

func MediaType(b []byte) (string, error)

MediaType returns the media type (MIME) for a given font.

func NewSFNTReader

func NewSFNTReader(r io.Reader) (*bytes.Reader, error)

NewSFNTReader takes an io.Reader and transforms it into an SFNT reader. That is, given TTF/OTF/WOFF/WOFF2/EOT input, it will return TTF/OTF output.

func ParseEOT

func ParseEOT(b []byte) ([]byte, error)

ParseEOT parses the EOT font format and returns its contained SFNT font format (TTF or OTF). See https://www.w3.org/Submission/EOT/

func ParseWOFF

func ParseWOFF(b []byte) ([]byte, error)

ParseWOFF parses the WOFF font format and returns its contained SFNT font format (TTF or OTF). See https://www.w3.org/TR/WOFF/

func ParseWOFF2

func ParseWOFF2(b []byte) ([]byte, error)

ParseWOFF2 parses the WOFF2 font format and returns its contained SFNT font format (TTF or OTF). See https://www.w3.org/TR/WOFF2/

func ToSFNT

func ToSFNT(b []byte) ([]byte, error)

ToSFNT takes a byte slice and transforms it into an SFNT byte slice. That is, given TTF/OTF/WOFF/WOFF2/EOT input, it will return TTF/OTF output.

func Uint16ToFlags

func Uint16ToFlags(v uint16) (flags [16]bool)

Uint16ToFlags converts a uint16 in 16 booleans from least to most significant.

func Uint8ToFlags

func Uint8ToFlags(v uint8) (flags [8]bool)

Uint8ToFlags converts a uint8 in 8 booleans from least to most significant.

Types

type BinaryReader

type BinaryReader struct {
	// contains filtered or unexported fields
}

BinaryReader is a binary big endian file format reader.

func NewBinaryReader

func NewBinaryReader(buf []byte) *BinaryReader

NewBinaryReader returns a big endian binary file format reader.

func (*BinaryReader) EOF

func (r *BinaryReader) EOF() bool

EOF returns true if we reached the end-of-file.

func (*BinaryReader) Len

func (r *BinaryReader) Len() uint32

Len returns the remaining length of the buffer.

func (*BinaryReader) Pos

func (r *BinaryReader) Pos() uint32

Pos returns the reader's position.

func (*BinaryReader) ReadByte

func (r *BinaryReader) ReadByte() byte

ReadByte reads a single byte.

func (*BinaryReader) ReadBytes

func (r *BinaryReader) ReadBytes(n uint32) []byte

ReadBytes reads n bytes.

func (*BinaryReader) ReadInt16

func (r *BinaryReader) ReadInt16() int16

ReadInt16 reads a int16.

func (*BinaryReader) ReadInt16LE

func (r *BinaryReader) ReadInt16LE() int16

ReadInt16LE reads a int16 little endian.

func (*BinaryReader) ReadInt32

func (r *BinaryReader) ReadInt32() int32

ReadInt32 reads a int32.

func (*BinaryReader) ReadInt64

func (r *BinaryReader) ReadInt64() int64

ReadInt64 reads a int64.

func (*BinaryReader) ReadInt8

func (r *BinaryReader) ReadInt8() int8

ReadInt8 reads a int8.

func (*BinaryReader) ReadString

func (r *BinaryReader) ReadString(n uint32) string

ReadString reads a string of length n.

func (*BinaryReader) ReadUint16

func (r *BinaryReader) ReadUint16() uint16

ReadUint16 reads a uint16.

func (*BinaryReader) ReadUint16LE

func (r *BinaryReader) ReadUint16LE() uint16

ReadUint16LE reads a uint16 little endian.

func (*BinaryReader) ReadUint32

func (r *BinaryReader) ReadUint32() uint32

ReadUint32 reads a uint32.

func (*BinaryReader) ReadUint32LE

func (r *BinaryReader) ReadUint32LE() uint32

ReadUint32LE reads a uint32 little endian.

func (*BinaryReader) ReadUint64

func (r *BinaryReader) ReadUint64() uint64

ReadUint64 reads a uint64.

func (*BinaryReader) ReadUint8

func (r *BinaryReader) ReadUint8() uint8

ReadUint8 reads a uint8.

func (*BinaryReader) Seek

func (r *BinaryReader) Seek(pos uint32)

Seek set the reader position in the buffer.

type BinaryWriter

type BinaryWriter struct {
	// contains filtered or unexported fields
}

BinaryWriter is a big endian binary file format writer.

func NewBinaryWriter

func NewBinaryWriter(buf []byte) *BinaryWriter

NewBinaryWriter returns a big endian binary file format writer.

func (*BinaryWriter) Bytes

func (w *BinaryWriter) Bytes() []byte

Bytes returns the buffer's bytes.

func (*BinaryWriter) Len

func (w *BinaryWriter) Len() uint32

Len returns the buffer's length in bytes.

func (*BinaryWriter) WriteByte

func (w *BinaryWriter) WriteByte(v byte)

WriteByte writes the given byte to the buffer.

func (*BinaryWriter) WriteBytes

func (w *BinaryWriter) WriteBytes(v []byte)

WriteBytes writes the given bytes to the buffer.

func (*BinaryWriter) WriteInt16

func (w *BinaryWriter) WriteInt16(v int16)

WriteInt16 writes the given int16 to the buffer.

func (*BinaryWriter) WriteInt32

func (w *BinaryWriter) WriteInt32(v int32)

WriteInt32 writes the given int32 to the buffer.

func (*BinaryWriter) WriteInt64

func (w *BinaryWriter) WriteInt64(v int64)

WriteInt64 writes the given int64 to the buffer.

func (*BinaryWriter) WriteInt8

func (w *BinaryWriter) WriteInt8(v int8)

WriteInt8 writes the given int8 to the buffer.

func (*BinaryWriter) WriteString

func (w *BinaryWriter) WriteString(v string)

WriteString writes the given string to the buffer.

func (*BinaryWriter) WriteUint16

func (w *BinaryWriter) WriteUint16(v uint16)

WriteUint16 writes the given uint16 to the buffer.

func (*BinaryWriter) WriteUint32

func (w *BinaryWriter) WriteUint32(v uint32)

WriteUint32 writes the given uint32 to the buffer.

func (*BinaryWriter) WriteUint64

func (w *BinaryWriter) WriteUint64(v uint64)

WriteUint64 writes the given uint64 to the buffer.

func (*BinaryWriter) WriteUint8

func (w *BinaryWriter) WriteUint8(v uint8)

WriteUint8 writes the given uint8 to the buffer.

type BitmapReader

type BitmapReader struct {
	// contains filtered or unexported fields
}

BitmapReader is a binary bitmap reader.

func NewBitmapReader

func NewBitmapReader(buf []byte) *BitmapReader

NewBitmapReader returns a binary bitmap reader.

func (*BitmapReader) EOF

func (r *BitmapReader) EOF() bool

EOF returns if we reached the buffer's end-of-file.

func (*BitmapReader) Pos

func (r *BitmapReader) Pos() uint32

Pos returns the current bit position.

func (*BitmapReader) Read

func (r *BitmapReader) Read() bool

Read reads the next bit.

type EncodingID

type EncodingID uint16

EncodingID is the encoding identifier for the name table

type FeatureTag

type FeatureTag string

type Hinting

type Hinting int

Hinting specifies the type of hinting to use (none supported yes).

const (
	NoHinting Hinting = iota
)

see Hinting

type LanguageTag

type LanguageTag string

type NameID

type NameID uint16

NameID is the name identifier for the name table

type Pather

type Pather interface {
	MoveTo(float64, float64)
	LineTo(float64, float64)
	QuadTo(float64, float64, float64, float64)
	CubeTo(float64, float64, float64, float64, float64, float64)
	Close()
}

Pather is an interface to append a glyph's path to canvas.Path.

type PlatformID

type PlatformID uint16

PlatformID is the platform identifier for the name table

type SFNT

type SFNT struct {
	Data              []byte
	Version           string
	IsCFF, IsTrueType bool // only one can be true
	Tables            map[string][]byte

	// required
	Cmap *cmapTable
	Head *headTable
	Hhea *hheaTable
	Hmtx *hmtxTable
	Maxp *maxpTable
	Name *nameTable
	OS2  *os2Table
	Post *postTable

	// TrueType
	Glyf *glyfTable
	Loca *locaTable

	// CFF
	CFF *cffTable

	// optional
	Kern *kernTable
	Vhea *vheaTable
	//Hdmx *hdmxTable // TODO
	Vmtx *vmtxTable
	Gpos *gposgsubTable
	Gsub *gposgsubTable
	Jsft *jsftTable
}

SFNT is a parsed OpenType font.

func ParseEmbeddedSFNT

func ParseEmbeddedSFNT(b []byte, index int) (*SFNT, error)

ParseEmbeddedSFNT is like ParseSFNT but for embedded font files in PDFs. It allows font files with fewer required tables.

func ParseFont

func ParseFont(b []byte, index int) (*SFNT, error)

ParseFont parses a byte slice and of a TTF, OTF, WOFF, WOFF2, or EOT font format. It will return the parsed font and its mimetype.

func ParseSFNT

func ParseSFNT(b []byte, index int) (*SFNT, error)

ParseSFNT parses an OpenType file format (TTF, OTF, TTC). The index is used for font collections to select a single font.

func (*SFNT) GlyphAdvance

func (sfnt *SFNT) GlyphAdvance(glyphID uint16) uint16

GlyphAdvance returns the (horizontal) advance width of the glyph.

func (*SFNT) GlyphBounds

func (sfnt *SFNT) GlyphBounds(glyphID uint16) (int16, int16, int16, int16, error)

GlyphBounds returns the bounding rectangle (xmin,ymin,xmax,ymax) of the glyph.

func (*SFNT) GlyphIndex

func (sfnt *SFNT) GlyphIndex(r rune) uint16

GlyphIndex returns the glyphID for a given rune.

func (*SFNT) GlyphName

func (sfnt *SFNT) GlyphName(glyphID uint16) string

GlyphName returns the name of the glyph.

func (*SFNT) GlyphPath

func (sfnt *SFNT) GlyphPath(p Pather, glyphID, ppem uint16, x, y, scale float64, hinting Hinting) error

GlyphPath draws the glyph's contour as a path to the pather interface. It will use the specified ppem (pixels-per-EM) for hinting purposes. The path is draws to the (x,y) coordinate and scaled using the given scale factor.

func (*SFNT) GlyphVerticalAdvance

func (sfnt *SFNT) GlyphVerticalAdvance(glyphID uint16) uint16

GlyphVerticalAdvance returns the vertical advance width of the glyph.

func (*SFNT) Kerning

func (sfnt *SFNT) Kerning(left, right uint16) int16

Kerning returns the kerning between two glyphs, i.e. the advance correction for glyph pairs.

func (*SFNT) NumGlyphs

func (sfnt *SFNT) NumGlyphs() uint16

NumGlyphs returns the number of glyphs the font contains.

func (*SFNT) Subset

func (sfnt *SFNT) Subset(glyphIDs []uint16, writeTables WriteTables) ([]byte, []uint16)

Subset regenerates a font file containing only the passed glyphIDs, thereby resulting in a significant size reduction. The glyphIDs will apear in the specified order in the file, and their dependencies are added to the end. It returns the compressed font file and the glyphIDs in the order in which they appear.

func (*SFNT) Write

func (sfnt *SFNT) Write() []byte

Write writes out the SFNT file.

type ScriptTag

type ScriptTag string

type ValueRecord

type ValueRecord struct {
	XPlacement       int16
	YPlacement       int16
	XAdvance         int16
	YAdvance         int16
	XPlaDeviceOffset uint16
	YPlaDeviceOffset uint16
	XAdvDeviceOffset uint16
	YAdvDeviceOffset uint16
}

type WriteTables

type WriteTables int
const (
	WriteAllTables WriteTables = iota
	WriteMinTables
	WritePDFTables
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL