Technical Article

Web Fonts in PDF: WOFF2 and Variable Axes in Delphi

A .woff2 file that has been through a Brotli decompressor is still not a font, and no TrueType parser will open the result. There is no sfnt table directory in it, and the glyf and loca data come out in a transformed layout that has to be rebuilt glyph by glyph. Get past that and the variable font itself is waiting: a PDF font program has no way to say "draw this at weight 620", so whatever you embed renders at the default location of its design space

The fonts in question usually come from a design system. Marketing settled on one variable family, the web team ships it as WOFF2, and the reporting service is expected to produce PDFs that look like the website. The traditional workaround is to ask the foundry for static TTF cuts of every weight in use. That takes weeks, and the static files drift out of step with the web build the first time the family is updated

Why is a WOFF2 file not just a compressed TTF?

A WOFF2 file is a re-encoded font, and decompression is only the first of three steps. The W3C WOFF2 format stores the table directory in its own compact encoding, compresses all tables as one Brotli stream, and may store glyf, loca and hmtx in transformed forms: point coordinates split into separate streams, loca dropped entirely and recomputed from the glyph data, side bearings omitted where they can be derived from glyph bounds. Undoing that is a font-format job, and a general-purpose decompressor never attempts it

PDF Library for Delphi accepts WOFF2 through the same calls as TTF, OTF and WOFF1: AddTrueTypeFontFromFile, or AddOpenTypeFontFromFile with Options = 0. The container is recognized by its signature and unwrapped before the sfnt parser ever sees it, so streams and embedded fonts take the same route as files. In Delphi builds on Windows, the WOFF2 decode is handed to DirectWrite (IDWriteFactory5, present since Windows 10 version 1703). Using the system decoder instead of a second bundled Brotli and transform implementation removes a DLL from every deployment and puts the transform reversal in code the operating system's own text stack already exercises daily. Free Pascal builds and non-Windows targets decode WOFF1 in pure Pascal; for WOFF2 there the font call returns 0, and you convert to TTF once at build time

A web font is downloaded content, so the import checks the container before and after decoding. Before: the file must be at least 48 bytes, the length stored in the header must equal the actual file length, the reserved field must be zero, and the declared sfnt size must be non-zero and no larger than 512 MiB. After: the size of the decoded stream must match that declaration exactly. Those two checks cover the failure modes worth blocking in a font pulled off a CDN, a truncated or padded download and a decompression bomb, and either one ends with the font ID coming back as 0

This pipeline diagram shows how the Delphi PDF library imports a WOFF2 web font through header validation, system decoding, sfnt transform reversal and a post-decode size audit
WOFF2 containers arrive as downloaded content, so the import validates the header and declared sizes before and after decoding
uses
  SysUtils, PDFlibrary;

var
  Lib: TPDFlib;
  FontID: Integer;
  AxesJSON: WideString;
begin
  Lib := TPDFlib.Create;
  try
    Lib.NewDocument;
    Lib.SetPageSize('A4');      // NewDocument already made page 1

    // WOFF2, WOFF1, TTF, OTF and TTC all go through this call;
    // any Options value other than 0 makes it return 0
    FontID := Lib.AddOpenTypeFontFromFile('Inter.woff2', 0);
    if FontID <= 0 then
      raise Exception.Create('font could not be imported');

    // Returns the number of axes; 0 and '[]' for a static font
    if Lib.GetFontVariationAxes(FontID, AxesJSON) > 0 then
      WriteLn(AxesJSON);
    // [{"tag":"wght","name":"Weight","minimum":100,"default":400,
    //   "maximum":900,"hidden":false}, ...]
  finally
    Lib.Free;
  end;
end;

Asking the font which axes it has

GetFontVariationAxes is the call to make before choosing any coordinates. It returns the axis count and fills a JSON array with one object per axis: the four-letter tag, the display name from the name table, the minimum, default and maximum design values, and the hidden flag that foundries set on axes they do not want in a UI. Inter, Roboto Flex and a typical in-house brand family will all report wght; beyond that the sets diverge quickly, with wdth, opsz, slnt, ital or custom uppercase tags

The coordinate string is forgiving about format and strict about content. Pairs can be separated by commas or semicolons, and either = or : works between tag and value, so 'wght=620,wdth=87.5' and 'wght:620; wdth:87.5' mean the same thing. A value outside an axis's declared range is clamped to the nearest end. A tag the font does not declare is a different story: the whole call fails and returns 0. That bites shared configuration code. A style table that adds opsz=12 to every request works for the family that has an optical-size axis and fails for the one that does not, so build the string from the tags the axis JSON actually lists

There are two instancing calls, one per outline format. CreateTrueTypeFontVariation handles fonts with glyf outlines, which is most of what ships as WOFF2 today. CreateOpenTypeFontVariation handles CFF2 outlines and returns 0 straight away for anything without a CFF2 table. Both return a new font ID and select the new font, leaving the original variable font loaded so you can cut further instances from it

// Helper suggested for your own code: cut one static instance
// without having to know the outline format in advance
function MakeInstance(Lib: TPDFlib; FontID: Integer;
  const Coords: WideString): Integer;
begin
  // CFF2 outlines; returns 0 at once when the font has no CFF2 table
  Result := Lib.CreateOpenTypeFontVariation(FontID, Coords);
  if Result = 0 then
    // TrueType (glyf) outlines
    Result := Lib.CreateTrueTypeFontVariation(FontID, Coords);
end;

// ...
InstanceID := MakeInstance(Lib, FontID, 'wght=620,wdth=87.5');
if InstanceID = 0 then
  raise Exception.Create('unknown axis tag or unusable variation data');

Lib.DrawOpenTypeText(56, 760, InstanceID, 24, 'Quarterly results', 0);

What instancing rebuilds in a TrueType variable font

A variable TrueType font stores one default outline per glyph plus deltas keyed to regions of the design space. Making a static instance means turning the requested design values into normalized coordinates (adjusted by avar when the font has one), summing the deltas from gvar that apply at that point, moving the outline points, and then recomputing everything that was derived from them

The points are only the visible part. Deltas in gvar can use shared or private point numbers, and points without an explicit delta have to be interpolated from their neighbors along the contour; get that wrong and curves develop kinks only at certain weights. The four phantom points at the end of each glyph carry its advance width and side bearings, and HVAR can override them, which is why a condensed instance really does get narrower advances. Composite glyphs reference other glyphs with offsets, scales and point attachments, so their components are resolved first. Composite nesting is capped at 32 levels, because a malformed or hostile font can describe a component graph that never terminates

Metadata moves too, and this is where many instancers stop short. MVAR adjusts the global metrics in hhea, OS/2 and post, so ascender, line gap, underline position and strikeout size match the instance. The wght, wdth, ital and slnt coordinates also rewrite usWeightClass, usWidthClass, the selection flags, macStyle and the italic angle. A static font whose outlines are semibold while its OS/2 table still says 400 gets mislabelled by every tool downstream, including PDF viewers that build a font list from those fields

The output flattens composites into simple glyphs and drops what no longer applies: the variation tables, the hinting tables (cvt , fpgm, prep, gasp, LTSH, hdmx, VDMX) and any DSIG signature, which the rebuilt tables would invalidate anyway. Glyph bounding boxes, the hhea extremes, the maxp point and contour maxima, every table checksum and the whole-font checksum adjustment are then recomputed

PDF Library for Delphi: This diagram shows variable font instancing rebuilding a TrueType face by interpolating gvar deltas, expanding composite glyphs, recomputing advances and rewriting style metadata before stripping the variation tables
Instancing rebuilds everything the deltas touched, then strips the variation machinery so ordinary embedding sees a plain static font

CFF2 fonts take a different road

A CFF2 font program cannot go into a PDF as it is. Its charstrings carry no advance widths, it leans on the surrounding OpenType tables for glyph order and metrics, and the CFF font program types in ISO 32000 are built around the original CFF format. So CreateOpenTypeFontVariation produces a CID-keyed CFF OpenType font that keeps the original cmap and glyph order, which the existing drawing, embedding and subsetting code already knows how to handle

Loading a CFF2 font creates a static instance at the default coordinates right away, so the font is drawable without any instancing call. The original CFF2 data stays attached to the font object, which is why GetFontVariationAxes and later instancing still see the full design space rather than the frozen default

The conversion has one trap that is easy to miss when reading the two specifications side by side. A CFF2 charstring may push up to 513 operands; a CFF1 Type 2 interpreter only has to support 48. Copying long path segments across verbatim produces charstrings that overflow the reader's stack, so long hlineto, vlineto and curve runs are split into chunks that keep alternating directions and the optional trailing coordinates in the right place

Each glyph is also de-subroutinized during instancing. That removes the blend arithmetic completely and lets the existing CFF subsetter work unchanged. The price is size: an instance can be somewhat larger than one that kept shared subroutines. We think that is the right trade. A second subsetter that understands subroutine graphs would be a much larger surface for bugs than a few extra kilobytes per embedded subset, and only the glyphs actually used end up in the PDF anyway

Checking an instance before it ships

A broken instance usually renders. That is the problem: a slightly wrong advance or a dropped ToUnicode entry passes a visual check and shows up weeks later as overflowing text or a document nobody can search. Three checks cover most of it

Dump the font program. SaveFontToFile writes the currently selected font, and the instancing calls select the new instance, so the static file can be written without generating a PDF at all. Open it in a font inspection tool of your choice: it should parse cleanly, list no fvar, gvar, HVAR or MVAR table, and report the weight class you asked for along with the matching width class. usWidthClass is a 1–9 enumeration rather than a percentage, so wdth=87.5 shows up as class 4, Semi-condensed

Compare advances at a non-default location. If your pipeline can produce the same instance another way, such as an instancer in your font build tooling, compare advance widths and glyph bounds glyph by glyph at the exact same coordinates. Testing at the default location proves very little, since every delta is zero there

Extract the text from the finished PDF. An instance that embeds correctly but yields no extractable text has lost its Unicode mapping, which matters for search and screen readers long after the layout was approved. The extraction side is covered in text, image and font extraction

PDF Library for Delphi: This diagram shows three verification checks for a generated variable font instance: dumping the exported font file, comparing glyph advances against an independent instancing and extracting text back out of the PDF
A subtly wrong instance throws no exception, so the exported file, glyph advances and extracted text are each verified in turn
// Measure with the instance you will draw with, not the source font
TitleWidth := Lib.GetOpenTypeTextWidth(InstanceID, 24,
  'Quarterly results', 0);
if TitleWidth > BoxWidth then
  // ShrinkToFit is your own layout routine
  ShrinkToFit(Lib, InstanceID, BoxWidth);

// SaveFontToFile writes the selected font; select it explicitly
// in case other font calls ran after the instance was created
Lib.SelectFont(InstanceID);
if Lib.SaveFontToFile('Inter-620-87.ttf') = 0 then
  WriteLn('no font selected or file could not be written');

Running brand fonts through a report pipeline

Cache instances by coordinate string. Every distinct set of coordinates is a separate font program, so a document that mixes weight 400 and weight 620 embeds two subsets, not one shared face. Cutting the same instance again for every page wastes CPU; letting each template pick its own weight wastes file size. Snap the design system's weights to a short fixed list, say 400, 600 and 700, and keep one instance per entry for the lifetime of the TPDFlib object. The web can afford a continuous weight scale. A 40-page report with eleven nearly identical weights cannot

Measure with the instance. A condensed instance has narrower advances than the default, so any layout that measured strings against the variable font before instancing measured the wrong widths. GetOpenTypeTextWidth takes the instance's font ID and applies the same shaping as DrawOpenTypeText, so the number you measure is the width you draw. This mismatch is the most common way a heading fits in testing and spills over its box once someone switches the template to the condensed style

Plan for the glyphs your brand font lacks. A variable brand font often covers Latin and little else, and a customer name in Cyrillic or Greek will otherwise come out as missing glyphs; automatic font fallback for missing glyphs describes how to chain a second font behind the instance. And when the real goal is a smaller file rather than a particular weight, subsetting does far more than instancing does, as shown in PDF file size optimization and font subsetting

WOFF2 import, axis enumeration, TrueType and CFF2 instancing, shaping and subsetting all ship in the same library for Delphi, C++Builder and Free Pascal. Editions, platforms and the full API reference are listed on the PDF Library for Delphi product page