Technical Article

EMF Vector Import on Free Pascal With PDFlibPas

Grep a 6500-line EMF-to-PDF converter for everything it touches in Vcl.Graphics and the list fits on an index card: TBitmap for its pixel format, stream saving, handle, canvas and scanlines; TMetafile for its width, height and handle; TColor with clWhite and clBlack. Three types and two constants. For a parser that reads Windows metafiles record by record and turns them into PDF paths, that short list changes a Free Pascal port from a rewrite into a one-line conditional plus a small unit of Win32 declarations

We had started from the obvious assumption. The converter was written against the VCL, Free Pascal has no VCL, so the converter would need to be rebuilt on something else. That assumption survived until somebody counted members instead of reading the uses clause. Every item on the short list above already existed in the library's own graphics unit, which is there precisely so builds without the VCL have drop-in equivalents. The real blocker sat elsewhere: the Free Pascal Windows unit, which declares a different subset of the Win32 headers than Delphi's Winapi.Windows

Count members, not imports

The converter in question is the EMF vector import behind ImportEMFFromFile in PDFlibPas, about 6500 lines written against the VCL. A uses Vcl.Graphics line tells you a unit compiles against the VCL. It says nothing about how much of the VCL the code leans on. For a parser like this one the honest answer was three types and two constants, and a dependency that small is a substitution job

The audit can be mechanical. Remove the import, compile, and write down every identifier the compiler rejects. Then group them by owner. For this converter the names split cleanly into two piles: a handful of graphics classes that had drop-in replacements, and a much longer list of GDI record types, constants and functions that the Free Pascal RTL simply spells differently or leaves out. The second pile is what decided the work

Why is Windows the right compile-time axis?

An enhanced metafile is a Windows container, and the converter is a parser for Windows GDI records from the first line to the last. Whether the host application uses the VCL, FireMonkey, the LCL or no widget set at all has no bearing on whether those records can be interpreted. Whether the target is Windows decides it completely. So the conditional that guards the converter moved from "not built with the VCL" to "not built for Windows"

// The guard keys on the platform the data format belongs to.
// The widget set the host application uses is irrelevant here.
{$IFNDEF OS_WINDOWS}
// No GDI records to interpret: the unit compiles a stub whose
// conversion method raises
//   'Vector metafile conversion is not available in this build;
//    import the metafile as a raster image instead'
{$ELSE}
uses
  Windows,
  {$IFDEF FPC}
  WinEMF,      // declarations the FPC Windows unit leaves out
  {$ENDIF}
  Classes;
// ... the full record-by-record converter follows
{$ENDIF}

Once the axis is right, every build lands where it belongs without anyone writing new code for it. Delphi VCL builds are untouched. macOS keeps the exception, correctly, because there is no GDI there to speak of. C++Builder builds of this library undefine the Windows symbol, so they also get the exception and behave as they always have. A Windows build with a non-VCL widget set, FireMonkey included, gains vector EMF import as a side effect

EMF import conditional re-axed from VCL membership to the Windows platform, keeping stubs elsewhere and giving non-VCL Windows builds vector import
Re-axing the stub condition to the Windows platform keeps every existing build behaviour and gives non-VCL Windows targets EMF vector import for free

We think this is the general lesson worth taking away, and it is a firm opinion: if a conditional names a framework when the real dependency is an operating system or a file format, it will eventually block a port that should have cost an afternoon. The cost shows up much later, as a rewrite estimate that nobody schedules

Filling the gaps in the Free Pascal Windows unit

The missing pieces were all declarations. Free Pascal's Windows unit leaves out the EMR_* record type constants that the converter's main dispatch switches on, the two ExtTextOut option flags ETO_IGNORELANGUAGE and ETO_PDY, and the three GRADIENT_FILL_* modes. It spells several types differently, so TTRIVERTEX, TGRADIENTRECT, TGRADIENTTRIANGLE and PHandleTable need aliases. And it has no declaration at all for three records the parser reads: the alpha-blend record, the transparent-blit record that shares its layout, and the ICM-mode record

All of it went into one compatibility unit, WinEMF, which the parser lists after Windows only when compiled by Free Pascal. We chose that over sprinkling {$IFDEF FPC} through 6500 lines, and we would make the same call again. A single unit can be diffed against wingdi.h in one sitting; scattered conditionals get reviewed one at a time and drift. The parser body keeps reading as plain Delphi-flavoured Win32 code on both compilers

Win32 declarations missing from the Free Pascal Windows unit, collected into one compatibility unit for the EMF to PDF vector converter
Record constants, flags, aliases and three absent record types all live in one compatibility unit that can be diffed against the header documentation

Why does a brush record misread only on Win64?

Two of the declarations Free Pascal does provide are the trap. Its EMRCREATEBRUSHINDIRECT embeds the run-time LOGBRUSH, and its EMREXTCREATEPEN embeds the run-time EXTLOGPEN. In both run-time structures the hatch member is declared as ULONG_PTR, pointer sized, because in a live GDI call that member can carry a handle. A metafile stores the 32-bit form, always. The record layout is part of the serialised file format and does not grow when the reading process is 64-bit

On Win32 the two layouts coincide and nothing goes wrong. On Win64 the hatch occupies eight bytes in the declaration and four in the file. Everything the parser reads after that member comes from the wrong offset: for an extended pen that means the style-entry count and the dash array, which then feed straight into PDF line-dash output. No exception is raised and no parse error is reported. You get a drawing whose pens and fills are subtly wrong, and it looks exactly like a rendering bug in the converter rather than a struct layout mismatch two layers down. Delphi ships TLogBrush32 and EXTLOGPEN32 for this exact reason, and WinEMF redeclares both records with the stored layout

Byte layout of the EMF brush record showing a pointer-sized hatch field shifting later fields by four bytes on Win64 versus the fixed 32-bit layout
The serialised record always stores a 4-byte hatch, so the pointer-sized run-time structure silently misreads every later field on Win64
type
  // Stored form of LOGBRUSH: lbHatch stays 32 bits inside a metafile,
  // while the run-time structure widens it to a pointer on Win64
  TLogBrush32 = record
    lbStyle: UINT;
    lbColor: COLORREF;
    lbHatch: LONG;
  end;

  // Redeclared so the embedded brush uses the stored layout
  TEMRCreateBrushIndirect = record
    emr: EMR;
    ihBrush: DWORD;
    lb: TLogBrush32;
  end;
  PEMRCreateBrushIndirect = ^TEMRCreateBrushIndirect;

initialization
  // A check we suggest adding to your own unit; WinEMF itself has no Assert.
  // 8-byte record header + handle index + 12-byte brush, on every bitness
  Assert(SizeOf(TEMRCreateBrushIndirect) = 24);
end.

The rule we now apply to any record that appears both as an API argument and inside a file: declare it twice, and give the serialised copy fixed-width members only. A size assertion like the one above costs nothing and turns a silent misread on the first 64-bit build into a failed assert at startup. Pointer-sized members in a file format are a 64-bit bug that has not been compiled yet

Signature mismatches go in one wrapper

The remaining differences were ordinary signature mismatches, and they belong in a forwarding function so the call sites stay identical on both compilers. CombineTransform is the clearest case. Delphi declares the destination as a var parameter. Free Pascal takes the destination as a pointer and both sources as var parameters, which means a const argument cannot be passed straight through

// Delphi-shaped signature, forwarded to the FPC import
function CombineTransform(var xformResult: XFORM;
  const xform1, xform2: XFORM): BOOL;
var
  Source1, Source2: XFORM;
begin
  // Copy first: the import wants var sources, and some callers pass
  // the destination matrix as one of the sources
  Source1 := xform1;
  Source2 := xform2;
  Result := Windows.CombineTransform(@xformResult, Source1, Source2);
end;

The copies carry more weight than they look. The converter has call sites where the destination matrix is also one of the inputs, a normal pattern when a transform is accumulated in place. Handing the same address in twice to a function that may write the result while still reading its inputs produces a matrix that is slightly off, and the error only becomes visible on rotated content. Copying both sources into locals removes the aliasing for every caller at once

Rectangles and points were the other case. Free Pascal treats RECTL and POINTL as distinct from TRect and TPoint, so eight assignments needed an explicit cast between records of identical layout. Both compilers accept the cast form. Those eight sites carry no conditional at all, and a slightly ugly cast is a better trade than eight more {$IFDEF} blocks

Importing EMF from a Free Pascal application

From the calling side the result is that the same code runs under Delphi and Free Pascal on Windows. ImportEMFFromFile returns an image ID, or 0 when the import fails, and GetLastMetafileDiagnostics returns a JSON report describing which conversion path ran and why it stopped. With GeneralOptions set to 0 you get vector page content; 1 renders the metafile through GDI+ into a bitmap instead

uses
  PDFlibrary;

var
  PDF: TPDFlib;
  ImageID: Integer;
begin
  PDF := TPDFlib.Create;
  try
    // FontOptions = 1 adds the fonts the metafile uses as embedded subsets,
    // GeneralOptions = 0 requests vector output
    ImageID := PDF.ImportEMFFromFile('chart.emf', 1, 0);
    if ImageID = 0 then
    begin
      Writeln(PDF.GetLastMetafileDiagnostics);
      // Raster route: GeneralOptions = 1
      ImageID := PDF.ImportEMFFromFile('chart.emf', 1, 1);
    end;
    if ImageID <> 0 then
      PDF.DrawImage(50, 50, 400, 300);
    PDF.SaveToFile('chart.pdf');
  finally
    PDF.Free;
  end;
end.

On Windows, under either compiler, the vector import emits paths as paths, gradients as pattern content and text as text, so a chart or CAD drawing stays sharp at any zoom. Off Windows the vector call fails on purpose, and the diagnostics say so in a form a log parser can match: backend native-vector, status failed, one issue with code unsupported-backend and the message "Vector metafile conversion is not available in this build". That limit comes from the format itself, since GDI records have nothing to replay against outside Windows, and the exception text names the raster route as the alternative

The page geometry the converter writes into is covered in the content stream CTM and clipping tracker article, the primitives it emits in vector graphics, shaders and gradients, and other Delphi-only assumptions that surface during a Free Pascal port in code that only works on Delphi by accident. Device-context capture as a source of metafile content is described in the print preview and device context article

Compiler and platform support for EMF import, including the Free Pascal targets, is listed on the losLab PDF Developer Library product page