Search code examples
c++windowswinapitruetype

Getting TrueType font "post" table from font name


I am trying to extract the "post" table from an installed TrueType font, which I know only by name. How can I achieve this?

I have seen the GetFontData function, which seems to do almost exactly what I want, except that it gets the font data from the device context's currently loaded font. In my case though I do not have a device context, only the font name.
Additionally I have seen similar queries such as this, for looking up and retrieving the entire font file, but this seems unnecessarily inefficient and long-winded, given that Windows can already load and parse the font data (as we see for GetFontData). Furthermore I don't need the whole file, just the "post" table. Is there really no way except implementing it all myself?


Solution

  • You can call GetFontData(...) without having a window or GUI, e.g. from a command line program, by just making a dummy device context on the fly and selecting a font into it

    #include <Windows.h>
    #include <vector>
    
    std::vector<unsigned char> GetFontDataByName(const wchar_t* font_name)
    {
        HDC hdc = CreateCompatibleDC(NULL);
    
        auto font = CreateFont(0, 0, 0, 0,
            FW_NORMAL, FALSE, FALSE, FALSE,
            ANSI_CHARSET, OUT_DEFAULT_PRECIS,
            CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
            DEFAULT_PITCH,
            font_name);
        SelectObject(hdc, font);
        auto num_bytes = GetFontData(hdc, 0, 0, NULL, 0);
        std::vector<unsigned char> font_data(num_bytes);
        auto result = GetFontData(hdc, 0, 0, &(font_data[0]), num_bytes);
    
        DeleteDC(hdc);
    
        return font_data;
    }
    
    int main()
    {
        auto font_data = GetFontDataByName(L"Times New Roman");
    
        return 0;
    }