Render text using pangocairo with custom font stored in memory

I want to render some text using my custom ttf font stored in a c++ header file. This is my code:

#include <cairo-ft.h>
#include <cairo.h>
#include <fmt/core.h>
#include <fontconfig/fcfreetype.h>
#include <fontconfig/fontconfig.h>
#include <ft2build.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include <pango/pangofc-fontmap.h>
#include <pango/pangoft2.h>

#include "RubikMonoOne-Regular.h"
#include FT_FREETYPE_H

FT_Library ft;
FT_Face face;
FcPattern* pat;
FcFontSet* set;
int main(int argc, char* argv[]) {
  FT_New_Memory_Face(ft, RubikMonoOne_Regular_ttf, RubikMonoOne_Regular_ttf_len, 0, &face);

  cairo_font_face_t* ct = cairo_ft_font_face_create_for_ft_face(face, 0);

  FcConfigAppFontAddFile(nullptr, (const FcChar8*)":/non-existent");
  set = FcConfigGetFonts(nullptr, FcSetApplication);
  pat = FcFreeTypeQueryFace(face, (const FcChar8*)":RubikMonoOne-Regular.ttf", 0, nullptr);
  FT_New_Memory_Face(ft, RubikMonoOne_Regular_ttf, RubikMonoOne_Regular_ttf_len, 0, &face);
  FcPatternAddFTFace(pat, FC_FT_FACE, face);
  FcFontSetAdd(set, pat);

  PangoFontMap* fm = pango_cairo_font_map_new_for_font_type(CAIRO_FONT_TYPE_FT);
  PangoFontFamily** families;
  int n_families;
  pango_font_map_list_families(fm, &families, &n_families);
  for (int i = 0; i < n_families; i++) {
    PangoFontFamily* family = families[i];
    const char* family_name = pango_font_family_get_name(family);
    fmt::print("Family: {}\n", family_name);

  cairo_t* cr = cairo_create(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1920, 1080));
  PangoContext* context = pango_font_map_create_context(fm);
  PangoLayout* layout = pango_layout_new(context);
  PangoFontDescription* desc = pango_font_description_from_string("Rubik Mono One Regular 50");

  cairo_set_source_rgb(cr, 1, 1, 1);
  pango_layout_set_font_description(layout, desc);

  pango_layout_set_text(layout, "ABCDE", -1);
  cairo_set_source_rgb(cr, 0, 0, 0);

  pango_cairo_show_layout(cr, layout);
  cairo_surface_write_to_png(cairo_get_target(cr), "hello.png");
  return 0;

This code cannot load fonts from memory. pangocairo always loads fonts through file names. Is there any way to make pango cairo render use the FT_Face stored in PangoFont to render text?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.