Technical Article

Embed Missing Fonts in Existing PDFs for PDF/A in Delphi

A supplier PDF looks perfect on screen, yet the PDF/A validator rejects it with one line: 00030 At least one font is not embedded. The viewer was borrowing fonts from your machine all along. Open the font descriptor inside the file and nearly everything an embedded font needs is already there, down to the stem width and bounding box; what is missing is one stream reference holding the font program itself

The batch version of this is familiar to anyone who runs an archive ingestion pipeline. Invoices, contracts and scanned forms arrive from suppliers and bureaus, every desk in the building renders them fine, and the validator rejects file after file with that same line. Nobody upstream is going to regenerate anything. The pipeline has to fix what it receives, and that is the job this article covers. Its companion, the article on detecting PDF/A and PDF/UA violations with the preflight report, tells you which files are broken; this one deals with the single most frequent way they break

What error 00030 is actually asking for

ISO 19005-1 §6.3.4 requires every font used by a conforming file to carry its font program inside that file. The reasoning is plain archival logic. A document opened fifty years from now, on a machine that shares no fonts with the one that produced it, has to render identically, and a non-embedded font is just an instruction to go find something called Arial on whatever system happens to be reading. Whatever glyphs and metrics the substitute has, that is what the reader sees

The habit of not embedding goes back to the Standard 14 convention. Early PDF promised that every viewer ships Helvetica, Times, Courier, Symbol and ZapfDingbats, so generators learned to reference those by name and embed nothing. Plenty of tooling still does. PDF/A revokes that exemption, and losLab PDF Library for Delphi applies it on the writer side: with PDF/A or PDF/X mode active, AddStandardFont returns 0 without selecting a font, because the library does not bundle the Standard 14 outlines and will not write a reference it cannot back with a program. AddTrueTypeFont with Embed=0 is promoted to a full embed under PDF/A mode, while Embed=2 (subset) passes through unchanged since a subset is still an embedded program

That covers files you write yourself. A supplier's file is harder, because the font dictionaries were written by someone else's generator and you have no way to ask it for a second attempt. For those files the library provides EmbedMissingFonts, which repairs a loaded document in place by copying each missing program from the installed fonts into the descriptor the document already carries

Why does a non-embedded font need only one extra key?

A generator that writes a non-embedded TrueType font still produces a complete FontDescriptor: FontName, FontBBox, Flags, Ascent, Descent, StemV, CapHeight. What it leaves out is the stream holding the font program, referenced from the descriptor as /FontFile2 for TrueType outlines or /FontFile3 for CFF-based CID fonts. So EmbedMissingFonts adds exactly that. It reads the program bytes, writes them as a new Flate-compressed stream with a /Length1 entry, and attaches the reference to the descriptor that is already there

PDF Library for Delphi diagram of a FontDescriptor dictionary before and after EmbedMissingFonts: every entry already present and only the missing FontFile2 stream appended from the installed system font
EmbedMissingFonts appends one stream reference to a descriptor that is already complete

We think this in-place approach is the right default for inherited files, and the reason is the Widths array. Text positions in a PDF content stream are already fixed; the viewer advances by the widths the original generator recorded. Rebuilding the font dictionary from the installed font would replace those widths with freshly measured ones, and if the installed version of the face differs even slightly from the author's, you have changed the document you were supposed to preserve. Leaving the dictionary, encoding, widths and every content stream untouched means the pages still point at the same resource names with the same metrics

The walk covers every Font dictionary in the file, not just the ones reachable from page resources, so fonts used only in annotation appearances or shared between pages are picked up too. Composite Type0 fonts, the kind produced for CJK text and most modern Unicode output, are handled through their descendant CIDFont. The whole repair is one call on a loaded document:

var
  PDF: TPDFlib;
  Repaired: Integer;
begin
  PDF := TPDFlib.Create;
  try
    if PDF.LoadFromFile('supplier-invoice.pdf', '') <> 1 then
      raise Exception.Create('Could not load PDF');

    // Returns how many fonts gained a program. Fonts already
    // embedded are left alone; fonts with no installed match
    // are skipped and simply not counted.
    Repaired := PDF.EmbedMissingFonts;
    Writeln(Format('%d font program(s) embedded', [Repaired]));

    PDF.SaveToFile('supplier-invoice-repaired.pdf');
  finally
    PDF.Free;
  end;
end;

How the installed-font lookup matches names

BaseFont names in real files rarely match the family name Windows knows. EmbedMissingFonts normalizes each name before the lookup:

  • A subset prefix (six capital letters and a plus sign, as in KQBWTE+Calibri) is stripped
  • Anything after the first comma or hyphen is read as the style, so Arial,BoldItalic and Arial-BoldMT both ask for a bold face, and Italic or Oblique asks for an italic one
  • Trailing MT and PS suffixes are dropped, so ArialMT resolves to Arial
  • When the face lives inside a TrueType Collection (.ttc), the table offsets are adjusted so the embedded program is a valid standalone font

The harder problem is that the Windows font mapper never says no. Ask GDI for a family that is not installed and it hands back a substitute face without complaint; ask for bold on a family that only has a regular face and it emboldens the outlines on screen. Either result would give you a perfectly loadable font program that is the wrong font. So the lookup checks the face GDI actually selected against the requested family, ignoring spaces and case, and checks the face's own bold and italic bits against the requested style. A mismatch on either means the font is skipped

That is a deliberate trade. A more permissive lookup would raise the repair count on every batch, and some of those "repairs" would embed Arial Regular under a font the document calls Arial,Bold. ISO 19005-1 §6.3.6 requires the widths in the font dictionary to agree with the embedded program, so a near miss can trade error 00030 for a width-consistency error, and in the worst case it passes validation while rendering slightly differently than the author intended. We would rather report a skip than archive a guess

The lookup reads installed fonts through Windows GDI. On Linux or macOS builds the system path returns nothing, and the file-based call in the next section is the way to supply programs

What happens when the font is not installed?

The return value tells you. If EmbedMissingFonts reports fewer fonts than you know are missing, the difference is fonts the machine does not have, or does not have in the right style. For those, EmbedFontProgramFromFile(FontName, FileName) attaches a program from a .ttf or .otf file you provide, which lets a pipeline ship the corporate faces it expects to meet and fall back to them on purpose

PDF Library for Delphi decision flow enumerating every font dictionary, normalizing BaseFont names against the installed system, embedding found programs with EmbedFontProgram or falling back to EmbedFontProgramFromFile, and reporting the repaired count
Name normalization makes the system lookup forgiving, and the return count keeps skipped faces visible

The pattern that works best in practice is two passes. Run EmbedMissingFonts and save, then load the result, enumerate what is still unembedded, and offer each remaining name to your own font folder. The reload matters: the embedded flag that GetFontIsEmbedded reports for an enumerated font reflects the file as it was when FindFonts ran, so enumerating in the same session as the repair would show stale answers

function FontFileFor(const BaseFont: string): string;
begin
  // Your own helper (not part of the library): map document
  // font names to font files shipped with the app.
  // An empty result makes EmbedFontProgramFromFile return 0
  // without touching the file system.
  if Pos('CorporateSans', BaseFont) > 0 then
    Result := ExtractFilePath(ParamStr(0)) + 'fonts\CorporateSans.ttf'
  else
    Result := '';
end;

procedure EmbedFromShippedFonts(const InFile, OutFile: string);
var
  PDF: TPDFlib;
  I, FontID: Integer;
  Name: string;
begin
  PDF := TPDFlib.Create;
  try
    if PDF.LoadFromFile(InFile, '') <> 1 then
      Exit;
    PDF.FindFonts;
    for I := 1 to PDF.FontCount do
    begin
      FontID := PDF.GetFontID(I);
      if (FontID > 0) and (PDF.SelectFont(FontID) = 1) and
         (PDF.GetFontIsEmbedded = 0) then
      begin
        // Pass the name exactly as stored, subset prefix included
        Name := PDF.FontName;
        if PDF.EmbedFontProgramFromFile(Name, FontFileFor(Name)) = 0 then
          Writeln('Still not embedded: ', Name);
      end;
    end;
    PDF.SaveToFile(OutFile);
  finally
    PDF.Free;
  end;
end;

Three details decide whether that loop succeeds. The by-name calls, EmbedFontProgram for the installed font and EmbedFontProgramFromFile for a file, compare against the BaseFont exactly as the document stores it and act on the first Font dictionary carrying that name, which is why the loop passes PDF.FontName straight through instead of a cleaned-up family name. The program format has to suit the font type: glyph-outline TrueType data for a TrueType or CIDFontType2 font, an OpenType CFF program (one starting with the OTTO tag) for a CIDFontType0 font, which is then written as /FontFile3 with subtype OpenType. Hand a CFF file to a TrueType font and the call returns 0. And the repair path covers TrueType and CID fonts; a Type1 font's /FontFile needs the three-segment PFB layout with explicit length keys, so Type1 references are skipped and left for the return count to flag. Standard 14 references are usually written as Type1, so expect to see them in that leftover list

There is also a question the library cannot answer for you. A TrueType font's embedding permissions belong to its foundry, and a pipeline that writes licensed programs into documents leaving the organization needs someone to confirm the licenses allow it. The code will embed whatever file you point it at. Whether you are allowed to is a legal question

Closing the loop with CreatePreflightReport

The audit that rejected the file should be the one that clears it. CreatePreflightReport with ComplianceTests = 1 runs the PDF/A checks, and finding 00030 is reported once for the whole file, so a single overlooked font keeps it in the report. Run it on the source, repair and save, then run it again on the output

PDF Library for Delphi: Closed repair loop where CreatePreflightReport flags error code 00030, EmbedMissingFonts embeds the flagged fonts, SaveToFile writes the repaired PDF and a second report run verifies the batch passes
Run the preflight report first, let it drive the repair, then let the same audit certify the output
function HasFontEmbeddingViolation(PDF: TPDFlib;
  const FileName: string): Boolean;
var
  Report: string;
begin
  // ComplianceTests = 1 selects the PDF/A checks
  Report := PDF.CreatePreflightReport(FileName, '', 1, 0);
  Result := Pos('00030', Report) > 0;
end;

One result surprises people the first time. The font check ignores fonts that content only ever draws invisibly, in text rendering mode 3, which is how most OCR engines lay a searchable text layer over a scanned image. A scanned file can therefore pass 00030 while FindFonts still lists a non-embedded face. That is consistent with how PDF/A treats invisible text, and it means a per-font listing and the per-file verdict can legitimately disagree on the same document

For batch logs that need to name exactly which face in which file stayed unembedded, the per-font listing is the better tool: load the output, call FindFonts, then SelectFont and GetFontIsEmbedded for each entry. The article on extracting text, images and fonts from loaded PDFs uses the same enumeration to feed extraction instead of repair

Embedding clears one finding, and your own output should never need it

Embedding fonts removes error 00030 and nothing else. A file that also fails on encryption, missing XMP metadata, a device-dependent color space without an OutputIntent, or fonts lacking ToUnicode maps will still fail after every program is in place, so the repair belongs inside the preflight loop and works through what the report names. Size is the other cost. A full CJK font program can run to several megabytes, and embedding a few of them can make a one-page invoice many times its original size; the article on PDF file size optimization and font subsetting covers cutting each embedded program down to the glyphs the pages actually use

On the writing side, SetEmbedAllFonts(1) stops your own code from producing the files this article repairs. It applies the same promotion PDF/A mode uses to an ordinary document: any later AddTrueTypeFont call with Embed=0 embeds the full program. The setting belongs to the selected document and affects fonts added after the call, so set it right after NewDocument. Our recommendation is to turn it on for anything that might end up in an archive, PDF/A or not, since the files you create today are the inherited files of whoever reads them later

PDF.NewDocument;
PDF.SetEmbedAllFonts(1);
// From here on AddTrueTypeFont('Segoe UI', 0) embeds the
// full program, exactly like AddTrueTypeFont('Segoe UI', 1)
PDF.AddTrueTypeFont('Segoe UI', 0);

The load-repair-save path, the file-based fallback and the writer-side guard all ship in losLab PDF Library for Delphi, C# and VB.NET, together with the preflight engine used above to confirm the result; the product page documents the rest of the font API, including per-font inspection and subsetting