Skip to content
Font Extraction

Font Extraction

ExtractFonts reports the fonts a page uses, including the raw bytes of any font embedded in the file:

ex, err := extractor.New(page)
if err != nil {
    return err
}

pageFonts, err := ex.ExtractFonts(nil)
if err != nil {
    return err
}

for _, font := range pageFonts.Fonts {
    fmt.Println(font.FontName, font.FontType, font.IsCID)
}

Each Font describes one font: FontName, FontType such as Type0, TrueType or Type3, ToUnicode for whether the font supplies a Unicode mapping, and IsCID and IsSimple for whether it is composite or limited to single-byte codes. PdfFont gives you the underlying model object.

Building a document-wide list

The argument to ExtractFonts is what makes multi-page collection work. Passing the result of the previous page merges the two lists and drops duplicates, so you can accumulate across a document without seeing the same font repeatedly:

var fonts *extractor.PageFonts
for i := 0; i < numPages; i++ {
    // ... build ex for page i+1 ...
    fonts, err = ex.ExtractFonts(fonts)
    if err != nil {
        return err
    }
}

Passing nil returns every font on that page with no deduplication, which is what you want for a single page.

Saving embedded fonts

FontData holds the raw bytes of the embedded font file, taken from whichever of FontFile, FontFile2 or FontFile3 the descriptor uses. The format follows from that: TrueType, PostScript Type 1, or Compact Font Format. FontFileName gives a usable name to write it under.

FontData is empty for a font that is referenced but not embedded, which is normal for the standard 14 fonts. Check its length before writing a file.

Run the example

The example takes an input PDF, a page number, and a zip path. Pass 0 as the page number to walk the whole document. extractSpecificPageFont handles one page and threads the accumulated PageFonts through, which is where the deduplication above happens.

git clone https://github.com/unidoc/unipdf-examples.git
cd unipdf-examples/extract
go run pdf_extract_fonts.go input.pdf 0 fonts.zip

If this is your first time using UniPDF, follow the getting started guide to create an API key and set up your development environment.

View the full source
Last updated on