Requires the Small Business or Enterprise edition: the unit ships in Lib\SmallBusiness
FlattenPdfXfaToAcroForm reads the active revision, extracts the template and datasets packets from an array-form /XFA entry or a single-stream XDP package (supporting both uncompressed and /FlateDecode-compressed streams), and appends an AcroForm revision carrying one terminal field, widget and appearance stream per supported template field
PDFium exposes no AcroForm field creation, so every field dictionary, widget annotation, appearance stream and the Helvetica resource are authored at the byte level through the sparse-update pipeline; existing object identities stay unchanged
Subforms and exclGroup containers must be absolutely positioned: layout attributes other than position, script elements, non-Flate or predictor-filtered packets, and UI kinds other than textEdit, numericEdit, dateTimeEdit, passwordEdit, checkButton, choiceList, imageEdit, button, signature and barcode reject with profile messages and no output
Geometry accepts attribute or child-element form with unitless points or physical unit suffixes (pt, in, mm, cm, pc, px, mp) and flips from the XFA top-down origin into the page media-box space; field values bind from the template value element (including text, float, integer, decimal, date, time, dateTime and exData children) and override with matching dataset leaf elements resolved by longest matching hierarchical <subform> path suffix (recorded in TPdfXfaFlattenField.SubformPath, disambiguating duplicate leaf names in AcroForm /T); AcroFormName reports the emitted /T name, which is the leaf Name or, when another field shares that leaf name, SubformPath + . + Name; names that remain ambiguous reject the conversion
fxfkText, fxfkNumeric, fxfkDateTime and fxfkPassword fields write /FT /Tx with the value and a Helvetica appearance stream (multi-line textEdit fields set MultiLine and write /Ff 4096 with multi-line appearance positioning, while passwordEdit fields set Password, write /Ff 8192 and mask their appearance stream with asterisks); fxfkCheck fields write /FT /Btn mapping the value 1 to /V /Yes; fxfkButton (<button>) writes a pushbutton /FT /Btn /Ff 65536 widget with /MK /CA caption and button appearance; fxfkSignature (<signature>) writes an unsigned /FT /Sig signature widget; fxfkBarcode (<barcode>) writes a read-only /FT /Tx /Ff 1 widget whose /AP /N Form XObject renders Code 128-B vector barcode bars via GeneratePdfBarcode; fxfkRadio (<exclGroup>) groups collect member checkButton fields into RadioWidgets and write a parent /FT /Btn /Ff 32768 radio field with /Opt and per-option kid widget annotations carrying /Parent, /AS and dual-state /AP /N streams; fxfkChoice fields write /FT /Ch with export items as /Opt, the XFA drop-down default as the Combo flag (/Ff 131072, bit 18), open="always" as a plain list box, and open="multiSelect" with MultiSelect (/Ff 2097152, bit 22), SelectedValues and the sorted /I selection-index array; access="readOnly", access="protected" or access="nonInteractive" sets ReadOnly and adds bit 1 (/Ff 1) to the emitted AcroForm field flags; <font> child elements configure FontSize, Bold/Italic (/Helv, /HelvB, /HelvI, /HelvBI) and RGB text colour in both /DA and /AP /N; <border> and <fill> configure HasBorderColor, BorderColorR/G/B, BorderWidth, HasFillColor and FillColorR/G/B, emitting /MK << /BC ... /BG ... >>, /BS << /Type /Border /W ... /S /S >> and background/border drawing in /AP /N; <para hAlign="..." vAlign="..."/> and rotate="0|90|180|270" configure HAlign, VAlign and Rotation, emitting AcroForm /Q, /MK /R and aligned text placement; <caption> child elements extract CaptionText, CaptionPlacement (left, right, top, bottom, inline) and CaptionReserve, insetting the interactive widget box when CaptionReserve > 0 and painting the caption into the page content stream; widgets join their page annotation array with the /F 4 print flag
Static <draw> elements (TPdfXfaFlattenDrawItem, counted in TPdfXfaFlattenReport.DrawsWritten and returned by the six-parameter FlattenPdfXfaToAcroForm overload) render directly into their target page's /Contents stream and register required font or image XObjects in /Resources, supporting text draws (fxfdkText), sloped lines (fxfdkLine with slope and <edge thickness="..."><color value="R,G,B"/></edge>), stroked/filled rectangles (fxfdkRectangle with <edge> and <fill>), elliptical and circular arcs (fxfdkArc with startAngle, sweepAngle, circular, <edge> and <fill> rendered as cubic Bézier curves) and base64 JPEG/PNG images (fxfdkImage with alpha /SMask extraction)
pageArea siblings number from one in declaration order and claim their nested fields for that source page; fields outside any pageArea stay on page one, each touched page flips coordinates against its own media box, and fields routing beyond the document page count reject
fxfkImage fields decode their base64 image value once: baseline JPEG payloads publish verbatim as a /Subtype /Image object under /Filter /DCTDecode with width and height from the SOF marker, and non-interlaced PNG payloads (Grayscale, RGB, Indexed with PLTE/tRNS, Grayscale+Alpha and RGBA) unfilter scanlines and publish as /Filter /FlateDecode /DeviceRGB or /DeviceGray image XObjects with an attached 8-bit /DeviceGray /SMask soft-mask XObject when alpha or transparency data is present, painted through a /Subtype /Form appearance stretched to the field rectangle on a pushbutton-flagged widget (/Ff 65536, bit 17); other image formats and transfer encodings reject
An indirect AcroForm dictionary rewrites in place, dropping every /XFA reference from the final revision; the catalogue always stages so the appended revision carries the root object
Since v3.245.0, field, radio-member and subform names preserve validated UTF-8 XML input, including supplementary characters and numeric character references; dataset leaf names and hierarchical paths use the same decoded names
Field names, field values and choice items use literal strings when single-line printable ASCII and UTF-16BE <FEFF...> hex strings otherwise; Unicode radio export values also retain their UTF-8 PDF Name encoding and Unicode /Opt strings
Names reject control characters and literal dots to keep path segments unambiguous; duplicate leaf names are qualified by their subform paths, and collisions in the resulting qualified names reject before output publication
Delphi field records expose Unicode strings; FPC/LCL field records retain validated UTF-8 strings, whilst the PDF output uses the same UTF-16BE text-string representation on both compilers
Defaults allow 8 MiB per packet, 512 fields and 512 MiB output; the source position is restored and a failed run leaves the output empty
Since v3.262.0, explicitly enable AllowStaticFlow to arrange one root tb or lr-tb flow across existing fixed PDF pages, using one explicit contentArea per declared pageArea in declaration order
The PDF page tree supplies logical page order and physical MediaBox geometry; the flowed profile requires zero-origin positive MediaBoxes and content areas inside them, and does not create additional PDF pages
Each flowed field, drawing or nested atomic box requires fixed positive width and height and omitted or zero x/y offsets; tb stacks vertically and lr-tb wraps fixed rows before advancing to the next declared content area
Since v3.365.4 a textEdit field with multiline="1" whose template value carries explicit line breaks grows to lines*max(10,FontSize*1.2)+4 when that exceeds the declared height, and the saved appearance uses the same grown height; since v3.366.0 a template-valued multi-line field also wraps at its inner width using the four Helvetica variants' advance widths, growing to the wrapped line count; since v3.366.1 the same wrapping covers dataset-bound values and their repeated instances, and since v3.366.2 a word wider than the field breaks at character boundaries instead of overflowing, WinAnsi specials such as curly quotes, dashes and the euro sign render and wrap since v3.366.3, and template values are decoded as UTF-8 before measurement; draws and characters outside the WinAnsi set keep explicit-line behaviour because the appearance encoder substitutes `?` for them, and wrapping such text would first need a Unicode appearance encoder; since v3.365.5 the line count follows the dataset value when the field is bound, resolved by subform path since v3.365.6 with the first leaf at the deepest path winning since v3.365.7, matching binding; repeated fields take the line count of the dataset leaf binding each instance since v3.365.11, so every instance uses its own bound height; otherwise the template text; a grown item that no longer fits the current content area advances to the next declared page, whilst growth taller than an entire area rejects
Since v3.365.3 a flowed subform may omit h: its height is derived from its children (nested subforms grow recursively, explicit and data-driven occurrences count every instance with that instance's own wrapped height), its own margins are added, and following siblings advance by the grown height; an omitted height on a positioned subform or an atomic item still rejects, and grown content beyond the declared pages retains the existing exhaustion failure
Nested tb/lr-tb containers and positioned boxes fit within their declared fixed dimensions; individual items and nested boxes do not split, and overflow beyond the declared pages returns no output
Validated margins (XFA 3.3 leftInset, rightInset, topInset, bottomInset) may appear on flowed containers, atomic items and content areas: container and content-area margins inset the usable content rectangle for the row and vertical progression (re-applied on every page of a paginating root), whilst atomic-item margins inset the widget or drawing inside its flowed cell
Margin insets must be valid non-negative finite lengths, leave positive container and item content rectangles and place margin elements only under subform, field, draw, exclGroup or contentArea; other placements reject explicitly
Since v3.345.0, explicit equal occurrence counts (occur with matching min/max/initial) repeat flowed items: atomic items and, since v3.346.0, fixed-size subforms each consume their own flowed cell across row wrapping and page boundaries, instances beyond the first emit instance-qualified names (field[1], field[2], ...), repeated same-name dataset rows bind successive instances, and repeated subforms move their recorded sub-tree rigidly; nested repetition inside a repeated item and positioned children reject repetition; since v3.366.5 an occur range with min below max (or max="-1" for no upper bound) repeats an atomic item once per dataset leaf bound to its name, clamped into the declared range, so the instance count follows the data; a missing min defaults to 1, a missing max to min and initial must lie inside the range; since v3.366.17 a growable range may declare min="0", and a zero instance count removes the item from layout and emission like a hidden item, so an optional repeat disappears when the bound data has no leaf; since v3.366.7 the same range on a fixed subform takes its instance count from the dataset leaves bound to the descendant atomic items, which must all agree, and moves each instance's recorded sub-tree onto its own flowed cell; since v3.366.8 a repeated subform whose instances continue onto a later declared page keeps the first instance's sub-tree on the first instance's page, including when that first instance itself starts a new page (v3.366.16), and since v3.366.9 a repeated subform rejects when a later instance's descendant fields grow taller than the recorded cell, because the sub-tree is shifted rigidly; since v3.366.12 an instance that wraps to fewer lines keeps its smaller height inside that cell
Items support the distinct XFA presence semantics: visible paints and occupies layout space, invisible reserves the flowed cell whilst painting nothing (including the content of an invisible subform), and hidden removes the item from layout entirely; structural pageSet/pageArea/contentArea wrappers and the root flow container must stay visible
Root x/y offsets must be zero and optional root dimensions must match the first content area; explicit breakBefore/breakAfter entries require targetType pageArea and a unique forward name/id target, optionally prefixed with #
Scripts/events, dynamic occurrences on subforms, text-driven field growth, template inheritance, multiple content areas, unsupported wrappers, unsupported presence values and other flow directions reject explicitly
MaxFlowPages defaults to 256 with a hard maximum of 4096; MaxFlowNodes defaults to 16384 with a hard maximum of 1000000 and bounds layout work after the packet parser budget, repeated-subform traversal and per-instance field growth checks included
FlowedContainerCount, FlowedItemCount and FlowedPageCount report arranged containers, leaf items and distinct pages containing flowed items; an ordinary positioned template keeps zero flow counters
Capture starts at byte zero regardless of the caller's current input position, validates the source snapshot size before copying and restores the original position; cancellation retains its existing exception contract
Since v3.374.0 text outside the WinAnsi set keeps real glyphs: set AppearanceFontData to one TrueType program, or AppearanceFontName to an installed face that GetSystemFontData resolves, and the flattener embeds a subset Type0/Identity-H appearance font with a ToUnicode map, so field appearances, captions, button labels and draw text carry the source characters instead of ? substitutes; a character the program does not cover still falls back to ?, a TrueType collection is rejected because one appearance face is embedded, and MaxAppearanceGlyphs defaults to 8192
UnicodeAppearanceRuns counts the appearance strings written through the embedded face, SubstitutedAppearanceGlyphs counts the characters it had to replace, and AppearanceFontBytes reports the embedded subset size; the control run that leaves both font fields empty keeps the released ? substitution and reports zero for all three
Since v3.375.0 that text also wraps and grows with the embedded face's own metrics: a multi-line field breaks at its inner width between code points, including inside a run without spaces, grows to the wrapped line count and saves the same lines; without an appearance font the released explicit-line behaviour stays
The unit interface also declares TXfaAppearanceFont, the internal helper that holds that embedded face; it is visible only because the flattening routines share it, is not a supported extension point and may change without notice. Its members serve the flattener: AddCodePoint and Note record the characters to cover, Admits tests a string, PrepareSubset builds SubsetProgram within a glyph budget and HasSubset reports it, Encode writes Identity-H codes, Advance measures a string in points, ToUnicodeCMap, WidthArray and FontBBox produce the font dictionary entries, and UnitsPerEm with ScaledAscent, ScaledDescent and ScaledCapHeight give the metrics
Rebuild packages and clients and regenerate C++ headers after the public option/report record additions
Options := TPdfXfaFlattenOptions.Default; if not FlattenPdfXfaToAcroForm(Source, Options, OutputPdf, Report, Fields) then raise Exception.Create(Report.ErrorText);
type
TPdfXfaFlattenOptions = record
ReadOptions: TPdfActiveObjectReadOptions;
MaxPacketBytes: Integer;
MaxFields: Integer;
MaxOutputBytes: Int64;
CancellationToken: IPdfCancellationToken;
AllowStaticFlow: Boolean;
MaxFlowPages, MaxFlowNodes: Integer;
AppearanceFontData: TBytes;
AppearanceFontName: string;
MaxAppearanceGlyphs: Integer;
class function Default: TPdfXfaFlattenOptions; static;
end;
TPdfXfaFlattenFieldKind = (fxfkText, fxfkCheck, fxfkChoice, fxfkImage,
fxfkNumeric, fxfkDateTime, fxfkPassword, fxfkRadio, fxfkButton,
fxfkSignature, fxfkBarcode);
TPdfXfaFlattenDrawKind = (fxfdkText, fxfdkLine, fxfdkRectangle, fxfdkImage,
fxfdkArc);
TPdfXfaFlattenDrawItem = record
Name: string;
Kind: TPdfXfaFlattenDrawKind;
Text: string;
X, Y, W, H: Double;
PageIndex: Integer;
FontSize: Double;
Bold, Italic: Boolean;
HasTextColor: Boolean;
TextColorR, TextColorG, TextColorB: Byte;
HasStrokeColor: Boolean;
StrokeColorR, StrokeColorG, StrokeColorB: Byte;
StrokeWidth: Double;
HasFillColor: Boolean;
FillColorR, FillColorG, FillColorB: Byte;
SlopeUp: Boolean;
StartAngle, SweepAngle: Double;
Circular: Boolean;
HAlign, VAlign: string;
Rotation: Integer;
ImageData: TBytes;
end;
TPdfXfaFlattenDrawItems = array of TPdfXfaFlattenDrawItem;
TPdfXfaFlattenRadioWidget = record
Name: string;
ExportValue: string;
X, Y, W, H: Double;
PageIndex: Integer;
end;
TPdfXfaFlattenRadioWidgets = array of TPdfXfaFlattenRadioWidget;
TPdfXfaFlattenField = record
Name: string;
AcroFormName: string;
SubformPath: string;
Kind: TPdfXfaFlattenFieldKind;
Value: string;
X, Y, W, H: Double;
PageIndex: Integer;
Choices: array of string;
SelectedValues: array of string;
ListBox: Boolean;
MultiSelect: Boolean;
MultiLine: Boolean;
Password: Boolean;
ReadOnly: Boolean;
FontSize: Double;
Bold, Italic: Boolean;
HasTextColor: Boolean;
TextColorR, TextColorG, TextColorB: Byte;
HasBorderColor: Boolean;
BorderColorR, BorderColorG, BorderColorB: Byte;
BorderWidth: Double;
HasFillColor: Boolean;
FillColorR, FillColorG, FillColorB: Byte;
HAlign, VAlign: string;
Rotation: Integer;
BarcodeType: string;
CaptionText: string;
CaptionPlacement: string;
CaptionReserve: Double;
CaptionX, CaptionY, CaptionW, CaptionH: Double;
ImageData: TBytes;
RadioWidgets: TPdfXfaFlattenRadioWidgets;
end;
TPdfXfaFlattenFields = array of TPdfXfaFlattenField;
TPdfXfaFlattenReport = record
Succeeded: Boolean;
FieldsWritten: Integer;
DrawsWritten: Integer;
TemplateFields: Integer;
DatasetBound: Integer;
PagesWritten: Integer;
FlowedContainerCount, FlowedItemCount, FlowedPageCount: Integer;
UnicodeAppearanceRuns, SubstitutedAppearanceGlyphs, AppearanceFontBytes: Integer;
SourceSha256, OutputSha256: string;
ErrorText: string;
end;
function FlattenPdfXfaToAcroForm(Source: TStream;
const Options: TPdfXfaFlattenOptions; out OutputPdf: TBytes;
out Report: TPdfXfaFlattenReport;
out Fields: TPdfXfaFlattenFields): Boolean; overload;
function FlattenPdfXfaToAcroForm(Source: TStream;
const Options: TPdfXfaFlattenOptions; out OutputPdf: TBytes;
out Report: TPdfXfaFlattenReport;
out Fields: TPdfXfaFlattenFields;
out Draws: TPdfXfaFlattenDrawItems): Boolean; overload;