Technical Article

PDFlibPas EMF Import: PolyDraw, Polyline and Bezier Rules

Draw a three-point V with Canvas.Polyline while a yellow brush is selected, convert the metafile to PDF, and a naive converter hands back a solid yellow triangle. The same converter may bend a Bezier towards the wrong control point and leave a PolyDraw rectangle with three sides. Each case traces back to one [MS-EMF] rule: EMR_POLYBEZIER starts at point 0, polylines are open and stroked only, PT_CLOSEFIGURE is a flag bit, and point counts must fit the record size

A device context has state that a PDF path does not

An enhanced metafile is a recording of GDI calls made against a device context, and half of what a Poly* record means lives outside its points: whether the figure is open, whether it starts at the current position, which pen and brush are selected, and at which byte offset the points begin. PDF has none of that. It has a path, a current point inside that path, and a painting operator that picks stroke (S), fill (f) or both (B). The vector EMF importer in PDFlibPas, the losLab PDF library for Delphi, replays that device context state alongside the coordinates, and the rules below describe how it maps each record

The Poly* family also comes in two widths. Each 32-bit record such as EMR_POLYLINE has a 16-bit twin such as EMR_POLYLINE16 that stores points as SmallInt pairs, and GDI records the compact form whenever every coordinate fits. Everyday drawings therefore rarely reach the 32-bit handlers of a converter. Feed the same points through both widths and compare the paths; that is the cheapest audit there is. All records covered here belong to the drawing record group in [MS-EMF] 2.3.5

RecordStarts atClosed?Current position
EMR_POLYBEZIERPoint 0NoNot used, not updated
EMR_POLYLINEPoint 0No (pen only)Not used, not updated
EMR_POLYLINETOCurrent positionNo (pen only)Used and updated
EMR_POLYPOLYLINEFirst point of each polylineNo (pen only)Not used, not updated
EMR_POLYDRAWFirst PT_MOVETO, or current positionOnly where PT_CLOSEFIGURE is setUsed and updated

Where does an EMR_POLYBEZIER curve actually start?

An EMR_POLYBEZIER curve starts at point 0, and only the points from index 1 onward are grouped in threes as control point, control point, end point. A record with 7 points draws two cubic segments: point 0 is the start, points 1 to 3 form the first segment, and 4 to 6 form the second. Start grouping at point 0 instead and the start point gets consumed as the first control point. Every later segment shifts by one. The output is still a smooth curve, just the wrong one. PDFlibPas opens the path with m at point 0, in both record widths, and writes one c per complete triple after it

PDFlibPas diagram of an EMR_POLYBEZIER record with seven points where point zero opens the path with m and points one to three and four to six each form one cubic c segment, contrasting the correct grouping with one that consumes the start point as a control point
Point 0 is the start point and only complete triples after it become cubic segments, so a seven-point PolyBezier renders as m plus two c operators

What about a count that is not 1 plus a multiple of 3? The record is malformed. Our position is that the trailing one or two points should be dropped. Stitching them into a curve by inventing a missing control point produces a shape that no GDI device ever drew, and a reader comparing the PDF with the original has no way to tell which half of the curve is invented

PolyDraw type bytes 3 and 5

In EMR_POLYDRAW, PT_CLOSEFIGURE (value 1) is a bit that gets ORed into PT_LINETO (2) or PT_BEZIERTO (4), so a perfectly valid type byte can be 3 or 5. The point type is the byte with that bit masked off; the flag itself means "close the figure after the segment that ends on this point". A handler that matches the byte against single values in a Pascal case statement never sees 3 or 5 match anything. Those points are skipped. A rectangle drawn with PolyDraw loses its closing side, and a Bezier triple whose last point carries the flag loses that point, which throws every later triple out of step by one

PDFlibPas dispatches on Types[i] and not PT_CLOSEFIGURE and closes the figure only once a segment is complete: right after the line for a closed PT_LINETO, and after the third point of a Bezier group. A malformed file that sets the flag on the first or second point of a triple therefore does not close the figure halfway through a curve. Two more rules belong in the same handler:

  • Only the first PT_MOVETO in a record starts the path; later moves open new subpaths. A 16-bit EMR_POLYDRAW16 holding three figures must produce three subpaths, and a handler that restarts the path on every move keeps only the last one
  • A PolyDraw record that does not begin with PT_MOVETO starts at the current position, as the record definition says. Writing an l or c operator with no preceding m is a content stream error that each PDF viewer resolves differently
PDFlibPas anatomy of an EMR_POLYDRAW type byte where PT_CLOSEFIGURE is flag bit zero ORed into PT_LINETO or PT_BEZIERTO, so valid type bytes 3 and 5 must be masked with and not PT_CLOSEFIGURE before dispatch; a plain case statement skips both bytes and closed figures lose their last side
Mask the close flag off before dispatching and emit the close only after a completed line or Bezier triple, or PolyDraw silently drops points

The yellow triangle: why a polyline is never filled

EMR_POLYLINE and EMR_POLYPOLYLINE are open figures drawn with the pen alone, and in PDF a fill operator closes any open subpath before painting it (ISO 32000-1 §8.5.3). Emit B or f for a three-point polyline and the viewer paints a filled triangle in whatever brush colour is current. That is the yellow V from the opening paragraph, or the wedge under a chart trend line. PDFlibPas ends both polyline widths with S and never touches the brush, which keeps the GDI semantics intact: Polygon closes and fills, Polyline does neither

PDFlibPas comparison of an open V polyline exported from EMR_POLYLINE: a correct converter ends the path with the stroke operator S and ignores the selected brush, while emitting f or B closes the open subpath implicitly under ISO 32000-1 8.5.3 and paints the filled wedge under a chart line
A fill operator closes any open subpath before painting, so polylines must end in S with no h, f or B on the subpath

PolylineTo and the pen it must leave alone

EMR_POLYLINETO draws from the current position through every point in the record, stays open, and leaves the current position on the last point. Pen state is owned by EMR_SELECTOBJECT and EMR_CREATEPEN, never by a drawing record handler. A special case that switches the pen off inside one record has nothing that switches it back on, so every later record loses its outline. For the one-point form, read exactly the points the record holds and stop

PolyPolyline points sit after the counts array

The 32-bit EMR_POLYPOLYLINE stores nPolys counts and then cptl points, so the points begin at byte offset 32 + nPolys * 4. The trap is in the Delphi RTL. The Windows unit declares TEMRPolyPolyline with aPolyCounts and aptl as one-element arrays, which means aptl[0] is the first point only when nPolys is 1. Index aptl directly and every multi-line record reads count values as coordinates. Worse, a size check built on that layout rejects valid multi-line records outright. PDFlibPas computes the offset the same way it does for PolyPolygon and draws each polyline as its own open subpath, with a single stroke at the end. The 16-bit twin follows the same pattern; drawing it segment by segment would break line joins and ignore a selected NULL_PEN

Default objects and path brackets

  • A fresh GDI device context already has BLACK_PEN and WHITE_BRUSH selected. A metafile that draws without a single EMR_SELECTOBJECT is legal and still gets black outlines; a converter that starts with no pen writes n (end path, paint nothing) for those records
  • Inside a BeginPath / EndPath bracket, a Polyline neither uses nor updates the current position, so it opens a new subpath at its first point instead of joining the previous figure. Nothing is painted until the bracket is stroked or filled

Recording a test metafile with TMetafileCanvas

The quickest way to put a converter through these rules is to record the three risky calls into one enhanced metafile with TMetafileCanvas. The procedure below draws the curves with a hollow brush, then deliberately selects a solid yellow brush before the polyline. A correct converter ignores that brush. Any yellow in the output PDF means the polyline was filled. PolyDraw has no TCanvas wrapper, so it goes through the Windows API on the canvas handle, with type bytes 3 and 5 exercising the close flag

uses
  Winapi.Windows, System.Types, Vcl.Graphics;

procedure BuildPolyTestEmf(const FileName: string);
const
  // A closed square (3 = LINETO + CLOSEFIGURE), then a closed Bezier
  // figure whose last control triple ends with 5 = BEZIERTO + CLOSEFIGURE
  DrawPts: array[0..7] of TPoint = (
    (X: 300; Y: 40), (X: 380; Y: 40), (X: 380; Y: 120), (X: 300; Y: 120),
    (X: 420; Y: 120), (X: 440; Y: 40), (X: 520; Y: 40), (X: 540; Y: 120));
  DrawTypes: array[0..7] of Byte = (
    PT_MOVETO, PT_LINETO, PT_LINETO, PT_LINETO or PT_CLOSEFIGURE,
    PT_MOVETO, PT_BEZIERTO, PT_BEZIERTO, PT_BEZIERTO or PT_CLOSEFIGURE);
var
  Mf: TMetafile;
  Canvas: TMetafileCanvas;
begin
  Mf := TMetafile.Create;
  try
    Mf.Enhanced := True;
    Mf.Width := 600;
    Mf.Height := 260;
    Canvas := TMetafileCanvas.Create(Mf, 0);
    try
      Canvas.Pen.Color := clNavy;
      Canvas.Pen.Width := 2;
      Canvas.Brush.Style := bsClear;    // outlines only for the curves
      // Point 0 is the start; 1..3 and 4..6 are two cubic segments
      Canvas.PolyBezier([Point(20, 120), Point(60, 20), Point(100, 220),
        Point(140, 120), Point(180, 20), Point(220, 220), Point(260, 120)]);
      PolyDraw(Canvas.Handle, DrawPts[0], DrawTypes[0], Length(DrawPts));
      // Open V shape with a solid brush selected: stroked, never closed
      // into a yellow triangle
      Canvas.Brush.Style := bsSolid;
      Canvas.Brush.Color := clYellow;
      Canvas.Polyline([Point(20, 240), Point(120, 160), Point(220, 240)]);
    finally
      Canvas.Free;   // ends the recording
    end;
    Mf.SaveToFile(FileName);
  finally
    Mf.Free;
  end;
end;

Every coordinate here fits in a SmallInt, so GDI will normally store the 16-bit variants. Reaching the 32-bit handlers takes a producer that writes them, or records assembled by hand. Hand-built files have their own trap, and it surfaces as a VCL "Metafile is not valid" error: TMetafile.LoadFromStream treats the stream as an EMF only when the remaining length is strictly greater than the 108-byte TEnhMetaHeader. A short header, or an empty EMF that is exactly 108 bytes, is taken for a WMF and rejected. Write the full 108-byte header, extension fields included, before the first test record

Importing the metafile with ImportEMFFromFile

PDFlibPas imports an EMF through ImportEMFFromFile or ImportEMFFromStream. Both return a non-zero image ID on success and 0 on failure. GeneralOptions = 0 keeps the vector path this article is about, while 1 rasterises the metafile to a bitmap. FontOptions = 1 adds the fonts the metafile uses and embeds them as subsets. The stream variant rewinds to position 0 before loading, so hand it a stream that contains the metafile and nothing else

uses
  System.SysUtils, PDFlibrary;

procedure EmfToPdf(const EmfFile, PdfFile: WideString);
var
  PDF: TPDFlib;
  ImageID: Integer;
  PageOps: AnsiString;
begin
  PDF := TPDFlib.Create;
  try
    PDF.SetOrigin(1);              // top-left origin for DrawImage
    PDF.SetMeasurementUnits(0);    // points
    // FontOptions 1 = add the metafile fonts as embedded subsets
    // GeneralOptions 0 = vector import, 1 = bitmap
    ImageID := PDF.ImportEMFFromFile(EmfFile, 1, 0);
    if ImageID = 0 then
      raise Exception.Create('The metafile could not be imported');
    PDF.SelectImage(ImageID);
    // For an EMF, ImageWidth / ImageHeight are the frame size in points
    PDF.DrawImage(36, 36, PDF.ImageWidth, PDF.ImageHeight);

    // The page only invokes the imported form: q ... cm /Name Do Q
    // (an optional sanity check you can add to your own code)
    PageOps := PDF.GetPageContentToString;
    if Pos(AnsiString(' Do'), PageOps) = 0 then
      raise Exception.Create('Expected a form XObject invocation');

    if PDF.SaveToFile(PdfFile) <> 1 then
      raise Exception.Create('The PDF could not be saved');
  finally
    PDF.Free;
  end;
end;

A vector EMF import becomes a form XObject, so GetPageContentToString returns only the save, transform, Do and restore sequence. The m, l, c, h and S operators generated from the Poly* records live in the compressed form XObject stream. Open the saved file in a PDF object inspector, decompress that stream, and check three things for the test file above: the polyline ends in S with no h before it, each close flag in the PolyDraw figures produced an h, and no f or B appears on any of those subpaths. DrawImage scales an imported EMF uniformly by the smaller of Width and Height, so the drawing keeps its aspect ratio even when the box you pass does not match it

Free Pascal users can read how the PDFlibPas EMF vector importer builds under Free Pascal; the record semantics are identical wherever the importer compiles

Point counts in an EMF file are untrusted input

Every point count in a metafile should be checked against the record size before a single point is copied. EnumEnhMetaFile guarantees only that each record's nSize stays inside the file. It never checks that cptl agrees with nSize. A handler that copies cptl points with Move will happily read into the following records, or past the end of the metafile, once the count is forged or corrupt. PDFlibPas compares fixed header plus count times bytes per point against nSize for PolyDraw, PolyBezier, PolyBezierTo, Polyline, PolylineTo and Polygon in both widths, adding one byte per point for the PolyDraw type array. For the PolyPoly records the per-figure counts must also sum to no more than the declared total, and figures with zero points are skipped

We prefer skipping a record that fails this test over clamping the count to whatever fits. A clamped record still draws, and a partially drawn figure in a report is harder to spot than a missing one. The check is short enough to drop into your own parser; this version validates a 32-bit EMR_POLYPOLYLINE and returns a pointer to its real point array:

uses
  Winapi.Windows;

// A check to add to your own EMF parser (not a library routine).
// Returns nil unless the record really holds the points it declares.
// Points start after the counts array: 32 + nPolys * 4 bytes in, not at
// aptl[0], which the RTL declares as a one-element array
function PolyPolylinePoints(Rec: PEnhMetaRecord): PPoint;
var
  P: PEMRPolyPolyline;
  Count: PDWORD;
  PointsOffset, Total: Int64;
  I: Cardinal;
begin
  Result := nil;
  if (Rec^.iType <> EMR_POLYPOLYLINE) or (Rec^.nSize < 32) then
    Exit;
  P := PEMRPolyPolyline(Rec);
  if P^.nPolys = 0 then
    Exit;
  PointsOffset := 32 + Int64(P^.nPolys) * SizeOf(DWORD);
  if PointsOffset + Int64(P^.cptl) * SizeOf(TPoint) > Rec^.nSize then
    Exit;                         // forged or truncated count
  Total := 0;
  Count := @P^.aPolyCounts[0];    // walk by pointer: [0..0] trips range checks
  for I := 1 to P^.nPolys do
  begin
    Inc(Total, Count^);
    Inc(Count);
  end;
  if Total > P^.cptl then
    Exit;                         // figures claim more points than exist
  Result := PPoint(NativeUInt(Rec) + NativeUInt(PointsOffset));
end;

Order matters here. The points-fit test runs first, which proves the counts array lies inside the record before the loop walks it. The arithmetic uses Int64 because nPolys * 4 and cptl * 8 computed in 32 bits can wrap around to a small number and pass the comparison

The same record semantics apply whichever component renders your reports. HotPDF EMF and WMF vector import covers how that component turns gradient and hatch brushes into PDF patterns, and vector graphics, shaders and gradients in PDFlibPas shows how to draw the same shapes directly with the library API, skipping the metafile entirely

To run your own report metafiles through this importer, the PDFlibPas Delphi PDF library page has product details and the trial download