Technical Article

PDF Annotations with No /AP Stream Can Be Flattened

A filled application form arrives as a PDF printed from a browser, and the flattened copy you send on has empty boxes where the applicant typed a name and an amount. Open the original in a text editor and the data is right there: each widget's field carries /V (Jane Doe), the AcroForm dictionary says /NeedAppearances true, and not one widget has an /AP entry. The value was stored. A picture of the value never was, and flattening copies pictures, so the cure is to draw the missing appearance first and bake that

Why does a flattened form come back with empty fields?

A /NeedAppearances form stores field values without storing what those values look like on the page. ISO 32000-1 12.7.2 lets an interactive form set /NeedAppearances true in the AcroForm dictionary, which asks the viewer to build each field's visual surface at open time from /V, /DA and /Q. Producers that generate forms cheaply — browser print paths, server-side fillers, some scanning front ends — take that offer and write no /AP at all

Flattening, as the appearance algorithm in ISO 32000-1 12.5.5 frames it, is a transcription job. Take the annotation's normal appearance stream, map its /BBox onto the annotation's /Rect, paint it from the page content stream with a Do operator, then delete the annotation. With no source stream there is nothing to transcribe. A flattener that treats that case as "skip" looks reasonable in isolation and goes badly wrong in aggregate, because the documents most likely to need flattening are exactly the ones least likely to carry appearances. Markup suffers the same way: a Highlight from a review tool, a Square from a redline pass or an Ink signature can all arrive without /AP whenever the producer expects the viewer to draw them

Audit the file before you flatten it

Counting annotations without an appearance stream tells you, before anything is baked, how much of the output will be generated rather than copied. HotPDF exposes the pieces needed for that census on a loaded document: GetLoadedAnnotationSubtypes returns one subtype name per annotation on a page, GetLoadedAnnotationAppearanceStream returns the normal appearance (or nil), and IsLoadedAnnotationHidden reads bit 2 of the annotation's /F flags. The procedure below is a reader-side helper built from those calls, not part of the library

// Reader-side helper: lists annotations that will need a generated appearance
procedure AuditMissingAppearances(Doc: THotPDF);
var
  P, A, Missing, Hidden: Integer;
  Subtypes: THPDFAnsiStringArray;
begin
  Missing:= 0;
  Hidden:= 0;
  for P:= 0 to Doc.LoadedPageCount- 1 do
  begin
    Subtypes:= Doc.GetLoadedAnnotationSubtypes(P);
    for A:= 0 to High(Subtypes) do
      if Doc.GetLoadedAnnotationAppearanceStream(P, A, aakNormal)= nil then
      begin
        if Doc.IsLoadedAnnotationHidden(P, A) then
          Inc(Hidden)
        else
        begin
          Inc(Missing);
          Writeln(Format('page %d, annotation %d: %s has no /AP',
            [P+ 1, A, string(Subtypes[A])]));
        end;
      end;
  end;
  Writeln(Format('%d to synthesize, %d hidden and left alone',
    [Missing, Hidden]));
end;

On a browser-printed form the first number is usually every widget in the file. On a document that went through a desktop editor it tends to be zero, and in that case everything that follows is simply the ordinary bake

How FlattenLoadedAnnotations fills the gap

FlattenLoadedAnnotations still asks for the authored appearance first and only generates one when that lookup returns nil. An annotation that already has an /AP is baked exactly as written, byte for byte. Only an annotation with no normal appearance, a /Rect of non-zero width and height, and the hidden flag clear goes on to the synthesis step. That ordering is deliberate: a document author who took the trouble to write an appearance gets their own drawing back, and the library's reconstruction only fills holes

HotPDF decision flow diagram: FlattenLoadedAnnotations asks GetLoadedAnnotationAppearanceStream first, and an annotation that already carries /AP is baked as before, while a nil result passes the non-degenerate Rect and hidden-flag guards and branches on Subtype towards EnsureLoadedFieldAppearanceStream for widgets or SynthesizeMarkupAppearance for markup before the synthesised Form XObject is baked into the page content
The synthesis path only opens after the ordinary appearance lookup has failed and the geometry and visibility guards pass, so documents that carry real /AP streams keep their author's own bytes

From there, widgets and everything else take different paths. A widget is traced back to its owning field with GetLoadedFormFieldIndexForAnnotation and handed to EnsureLoadedFieldAppearanceStream, the same field appearance generator you can call yourself after setting values on a loaded form. It already knows Type0 fonts from the AcroForm /DR, line wrapping and /Q quadding for text fields, list box scrolling for choice fields, push-button captions from /MK /CA, vector check marks and radio dots for the on and off states, and /MK /R rotation. Writing a second, smaller field renderer just for flattening would have meant two renderers that disagree on edge cases. Everything that is not a widget goes to a markup synthesiser that reads the annotation dictionary, described further down

For a form, start with the form-level call. FlattenLoadedFormFields generates each field's appearance, bakes every widget of that field, and then removes the field from the AcroForm tree; in Delphi 2009 and later builds it also checks signature permissions first and raises an exception instead of touching a field locked by DocMDP or FieldMDP. FlattenLoadedAnnotations works one level lower, on page annotations: it edits the page content stream and the page's /Annots array and leaves the field tree to the form API. Run the form pass, then let the annotation pass pick up the markup

Doc:= THotPDF.Create(nil);
try
  Doc.LoadFromFile('needappearances-form.pdf');
  // fields: appearance generated from /V, widgets baked, fields removed
  FieldCount:= Doc.FlattenLoadedFormFields([]);
  // markup without /AP is synthesised from its own dictionary, then baked
  AnnotCount:= Doc.FlattenLoadedAnnotations;           // all pages, all subtypes
  // AnnotCount:= Doc.FlattenLoadedAnnotations('1-3', 'Highlight');
  Writeln(Format('%d fields and %d annotations baked',
    [FieldCount, AnnotCount]));
  Doc.SaveLoadedDocument('flattened.pdf');
finally
  Doc.Free;
end;

Both calls return counts, and on an appearance-less document those counts include every widget and markup annotation that received a generated appearance. An empty array passed to FlattenLoadedFormFields means every field; pass names to limit it. FlattenLoadedAnnotations takes a 1-based page range such as '1-3' as its first parameter, and its second restricts the pass to one subtype such as 'Square' or 'FreeText'

Why do QuadPoints and InkList land in the wrong place?

Those coordinates live in page user space, while a generated appearance stream draws in its own /BBox space, and the two origins are different points. ISO 32000-1 Table 179 defines /QuadPoints for text markup annotations in default user space, Table 175 does the same for the line annotation's /L endpoints, and /InkList follows the same convention. The synthesised form gets a /BBox of [0 0 W H], with its origin at the lower-left corner of /Rect, so every point taken from /QuadPoints, /L or /InkList has to be shifted by the negated /Rect lower-left before it goes into the content stream

HotPDF coordinate diagram: QuadPoints, L endpoints and InkList paths arrive in page user space under ISO 32000-1 Tables 174 and 176, while the appearance SynthesizeMarkupAppearance builds draws in a BBox whose origin sits at the Rect lower-left, so HotPDF subtracts RL and RB from every coordinate before the bake cm maps the box back
Every point pulled from /QuadPoints, /L or /InkList is translated by the negated Rect lower-left before it enters the synthesised stream, and the bake cm cancels that shift to restore absolute page geometry

Suppose a highlight has /Rect [72 690 300 712] and one quad whose corners sit between y 692 and y 710. Inside the generated form those corners must be written at y 2 and y 20. Written as-is, at 692 and 710, they land about 670 points above the top of a 22-point-tall box, far outside the clip, and nothing shows. The correction is one subtraction per coordinate. It composes cleanly with the cm the bake emits afterwards, because that matrix maps the /BBox back onto /Rect and the two steps cancel to the original absolute position. Anyone writing their own appearance generator for these subtypes runs into this within the first test file

What the synthesised markup appearance draws

The markup synthesiser reads the annotation dictionary and nothing else, so its output is predictable and it does not guess at what the producer meant. FreeText and Stamp draw /Contents with the font and colour from /DA (falling back to /Helv 12 Tf 0 g), aligned by /Q, with 2 pt padding, honouring CR and LF line breaks. Square draws a rectangle and Circle an oval outline inscribed in the box, approximated with straight segments, both stroked in /C, filled with /IC when present, at the width from /BS /W. Line and Ink stroke their vertices. Highlight fills each quad, yellow when /C is absent. Underline strokes a rule at the bottom of each quad, StrikeOut at its midpoint, and Squiggly draws a zigzag about a point either side of the baseline. A /CA below 1 becomes an ExtGState with a ca entry, applied with /GSA gs at the head of the stream

HotPDF mapping diagram of what SynthesizeMarkupAppearance draws per subtype: FreeText and Stamp render Contents using the font and colour parsed from DA aligned by Q, Square and Circle stroke C and fill IC at the BS width, Line and Ink stroke their vertices, Highlight fills each quad, and Underline, StrikeOut and Squiggly draw rules or a zigzag
The markup synthesiser reads the annotation dictionary and nothing else, which keeps each subtype's output predictable and keeps it honest about the subtypes it rightly leaves untouched

Text encoding follows the font that /DA names in the AcroForm /DR /Font dictionary. If that font's /Subtype is Type0, the string is written as a UTF-16BE hex literal with a FEFF byte order mark; otherwise it becomes an escaped literal string, with parentheses and backslashes escaped and bytes above 126 written in octal. When /DR has no entry under that name, the form's resources point the name at standard Helvetica. The /DA string is emitted as-is just before BT, which is legal because text state persists across the text object boundary, and it avoids taking /DA apart and reassembling it

Alignment is approximate. Line widths for centred and right-aligned FreeText come from an estimate of half an em per Latin character and a full em per CJK character, so on a proportional font a centred line sits close to the centre rather than exactly on it. Exact metrics would mean resolving and parsing every font program referenced from /DR, for annotations whose producer did not bother to draw them at all. A subtype with nothing to draw from its own dictionary — Popup, Link, a Stamp that only names an icon, a FreeText with empty /Contents — produces no appearance and stays on the page as an annotation, uncounted

Hidden annotations, irreversibility and checking the result

Hidden annotations never go through synthesis. ISO 32000-1 12.5.3 defines bit position 2 of /F as Hidden, and an annotation with that bit set and no /AP stays exactly where it was. Generating an appearance for it would defeat the flag: baking an invisible reviewer note into the page content makes it visible to everyone who opens the file. The audit procedure above counts these separately for that reason. The Hidden check guards the synthesis step; an annotation that carries its own /AP is baked as authored whatever its flags, so pass a SubtypeFilter or remove hidden notes first if they must stay invisible

Be just as clear with your users about what baking costs. Flattening cannot be undone. The annotation leaves the page's /Annots array and its picture becomes page content, so there is no more editing the field value, no comment thread, no checkbox toggling and no structured data to extract short of going back to the original file. Flatten a copy, keep the source, and flatten only when the document stops being a form and becomes a record. If the form is XFA-backed rather than appearance-less, the XFA to AcroForm flattening path in HotPDF is where to begin; if you are still building the form, see adding AcroForm fields to an already-loaded PDF and the notes on wiring AcroForm field actions and validation

Checking the output needs one adjustment to the obvious test. A baked appearance lives inside a Form XObject, and the page content stream holds only a q ... cm /FlatAn... Do Q sequence. ExtractLoadedPageGlyphs reads the page's own content stream, so on a flattened page it finds no field text. ExtractLoadedPageGlyphsWithForms follows each Do into the form it paints and returns those glyphs in painting order, which is exactly what this check needs

var
  Glyphs: THPDFGlyphArray;
  Text: string;
  I: Integer;
begin
  Doc.LoadFromFile('flattened.pdf');
  Text:= '';
  if Doc.ExtractLoadedPageGlyphsWithForms(0, Glyphs) then
    for I:= 0 to High(Glyphs) do
      if Glyphs[I].Unicode<> 0 then
        Text:= Text+ Char(Glyphs[I].Unicode);
  // reader-side assertion: the typed value is now page content
  if Pos('Jane Doe', Text)= 0 then
    raise Exception.Create('field value missing from page 1');
end;

A byte-level check works too: look for the /FlatAn resource name under the page /XObject resources, the matching Do, and /Subtype /Form on the referenced stream. Rendering the page through the rendering pipeline also shows the result, since it expands Form XObjects

Filled forms, review markup and archival copies all reach the same point where an annotation has to become ink on the page, and producers rarely make that easy. The HotPDF Delphi PDF component covers the loaded-document side of AcroForms and annotations for Delphi and C++Builder, from reading field values to generating appearances and baking them