Automatic XFA native PDF creation
Code39 and Extended Code39 fields share the native vector appearance and committed-value workflow, with authored width ratios and optional Mod43 checksum legends
Code128 barcode fields generate vector bars and legends, preserve module sizing and refresh appearances from committed runtime values
Instance bookends place opening and final closing content around the complete owning body, including repeated data, empty instances and cross-page content
Unit: HPDFXFAHeadless
Version 2.1150.1 shares the supplied TrueType font-program stream across repeated text appearances instead of embedding an identical copy for every run. Each appearance retains its own Type0 and CIDFont dictionaries, CID/GID mapping and ToUnicode mapping, so saved and reloaded PDFs preserve their text while duplicate font payload bytes are removed within the existing output, object and cancellation limits
Version 2.1149.14 preserves complete glyphs in already positioned rich-text runs, avoiding a second field inset that could clip glyph caps. Ordinary fields and buttons retain their original appearance spacing. See the real-font saved-PDF and ordinary-field compatibility evidence (Tests/XFA/GrowableRichDraw/HeadlessRunInsets/README.en-us.md); this finite consumer correction does not implement cross-page rich-draw continuation or arbitrary font ink overhang handling
A rich-enabled textEdit whose effective value is XHTML exData becomes an AcroForm rich text field. Portable output stores the styled value in /RV, its plain text in /V and a matching initial appearance in /AP. The field keeps the XFA editability and multiline settings. Nested XHTML paragraphs and divisions retain their boundaries when followed by inline text, and explicit line breaks stay in the exported value and appearance. A block with line-height styling contributes line metrics when it has visible content, without adding blank lines for empty blocks. Plain bound values continue through the ordinary text path
HPDFXFAWriteHeadlessPDF creates a fresh native PDF directly from XDP bytes and an application-supplied TrueType font, without an input PDF or prepared field slots
The adapter consumes the existing XFA binding, repeated-instance and pagination layout callbacks and builds native page and AcroForm object graphs with real embedded-font appearance streams
Text, numeric, date and password fields, push buttons, combo and list choices, checkbox and radio groups, static text, rectangle, line, arc and inline PNG or JPEG image draws are consumed; signatures and additional draw consumers require further adapter integration
Choice and boolean creation preserves separate display and export values, editable and multi-select behavior, native appearance states and independent repeated radio groups
Boolean styles and captions consumes actual vector markers, size, outline colors and thickness, Unicode caption regions and third checkbox states
Native graphics and images consumes actual vector paths, PNG sample formats and transparency, baseline or progressive JPEG, physical aspect and affine placement
Passwords use a masked appearance while retaining the native field value; document-wide Editable and effective XFA readOnly access determine native field flags
XFA point coordinates use a top-left origin and are converted once into native widget rectangles and draw translations; separate repeated occurrences receive distinct native field names from the layout engine
Native /AP, /DR and /DA resources are generated with the supplied font and effective size, color and alignment; the supplied face is used for every field, so typeface selection and multiple style faces are application responsibilities in this stage
Version 2.1152.1 preserves XFA typeface values literally, including semicolons, equals signs and Unicode characters. Delimiters inside a typeface no longer create additional style properties, so the declared font size remains authoritative in field and rich-draw appearances
Use TXFAWidgetRuntime to execute lifecycle or interaction events and save the resulting XDP before creation when the document requires those events, including script-created bookend and keep properties and saved repeated-instance references. The adapter's ScriptOptions control calculate, validate and conditional page-break script processing during flattening
Data-aware native Form preparation
Supported named-subform binding prepares real, independently addressable Form instances before native layout and flattening when the library generates the Form packet from a template and nonempty datasets. Matching data groups determine the instances within occur limits; initial does not add extra instances in this nonempty-data merge
If no matching data group exists, occur min still supplies distinct Form instances without inventing corresponding datasets groups. A zero minimum supplies none; layout measurement and width or terminal replay consume the prepared structure without performing another merge
An existing caller-provided Form packet is not taken over by automatic data synchronization. Runtime data synchronization describes subsequent data edits, explicit Form deletion and saved-document behavior for the library-generated model
Physical pagination and empty trailing pages
Applications consuming the native layout engine can inspect each accepted leaf fragment's content-area assignment, including distinct regions on the same physical page
Supported unconditional page-area and content-area breaks remain ordered layout boundaries even when the following visible subform contains no field or draw; consecutive terminal requests retain their order and can therefore preserve real empty trailing pages
A content-area break advances within the current page until its available content areas are exhausted, while a page-area break enters another physical page; omitted hidden or inactive containers do not add these boundaries, and a request carried by an ordinary following field or draw is not applied a second time
A leading subform can select the initial target region when the root has no explicit startup target. A later subform's break stays at its own ordered boundary and does not redirect preceding fields or draws
The layout's physical count and instance page associations describe the same pagination, and native PDF creation materializes the otherwise empty final pages without adding dummy fields, draws or glyphs
The full HPDFXFAFlatten overload adds a final out PhysicalPageCount: Integer argument to report the completed layout count; the existing overloads, field and draw callbacks, and TXFAFlattenResult record remain available unchanged
function HPDFXFAFlatten(const XDPBytes: TBytes; PageW, PageH: Double;
Editable: Boolean; const EmitField: TXFAEmitField;
const EmitDraw: TXFAEmitDraw; Warnings: TStringList;
const AScriptOptions: TXFAFormScriptOptions;
const AInstanceAction: TXFAFormInstanceAction;
const AMeasureText: TXFAMeasureTextFunc;
out PhysicalPageCount: Integer): TXFAFlattenResult; overload;
The page-count output is initialized to zero and published after successful layout and emission; native PDF preparation uses the existing page allocator and page, object and cancellation limits before publishing its candidate
Component ApplyXFAAsAcroForm and FlattenLoadedXFA extend from the caller's original current page, retain existing document pages and restore that current-page selection in cleanup; this adds no whole-document rollback guarantee to their immediate callbacks
Native content-area assignments
After a successful TXFALayoutEngine.ComputeLayout, each TXFAPositionedItem.ContentAreaIndex identifies the content-area definition selected by the actual placement cursor. Combine it with PageIndex to distinguish region occurrences on different physical pages; the same definition index can recur on later pages
property ContentAreaCount: Integer;
function TryGetContentArea(Index: Integer;
out Area: TXFAContentAreaInfo): Boolean;
TXFAContentAreaInfo supplies Node, PageAreaNode, X, Y, Width and Height. Coordinates use page-relative points with a top-left origin. The query returns a record copy and returns False with a cleared record for an invalid index
ContentAreaCount counts definitions in the current layout model, including definitions belonging to unselected masters; it is not the number of occupied regions or physical pages
An index of -1 means that placement has no assigned content area. This includes fixed master-page fields and draws and positioned overflow projected directly between page media without region routing. An item's rectangle overlapping a region does not establish an assignment
A synthetic whole-page region remains a valid index even though its Node can be nil. The index and node references belong to the current engine layout and document; consume them before recomputing layout or releasing the owning document
The assignment follows accepted flow, text continuations, repeated positioned sections and generated decorations through pagination and replay. For parent-relative container geometry and script x/y/w/h queries, use layout fragment capture
Optional native placement capture
Set TXFALayoutEngine.CapturePlacements := True before computing layout to retain source plans and accepted pagination decisions. Capture defaults to disabled and is reset on each computation; consume the records after a successful ComputeLayout
LayoutPlacementCount and TryGetLayoutPlacement enumerate records with stable indices within that computation. Accepted items retain their PlacementId, SourcePlanIndex and SourceScopeIndex; unrecorded references use -1
Version 2.1150.0 adds styled rich draw continuation. When HasTextRange is true, inspect TextRangeKind before using TextOffset and TextLength: xltrkPlainUTF16 retains the existing plain-text coordinates, and xltrkRichSourceUTF16 counts the decoded rich source, including collapsed whitespace and structural break/paragraph units. Continued rich pieces share their original node/data identity. Rebuild consumers of the changed public record declarations
LayoutSourcePlanCount, TryGetLayoutSourcePlan, TryGetLayoutSourceItem, TryGetLayoutSourceBox and TryGetLayoutSourceScope expose the source measurement plan, parent scopes and authored container extents independently of the accepted leaf rectangles. Source item ranges are half-open and split text ranges use zero-based UTF-16 code units
Record kinds distinguish accepted items, text pieces, row and tile allocations, positioned units, scope events, query anchors, movements and discards. Use HasTargetBox and HasAllocation before interpreting the corresponding rectangle fields; an empty scope's entry or exit cursor is not a container rectangle. Later xlpkMove and xlpkDiscard records identify the original accepted item through RelatedPlacementId; apply them when reading final item state. Query-anchor bookkeeping is not a final container box origin
xlpkSpace records vertical space actually consumed by an empty container or trailing content reservation. Its allocation starts at the previous cursor and has zero width; it does not assert the container's full width
Query methods return record copies and independent presentation arrays, and return False with cleared outputs for invalid indices. Node references still belong to the document; retain neither their identity nor a placement index across document changes or a new layout computation
Capture uses the layout operation limit and a 32 MiB accounting budget for capture work during a computation, including copied source and presentation data. Enable CaptureFragments to publish final container and leaf rectangles through LayoutFragmentCount and TryGetLayoutFragment; the final fragments resolve accepted movements and geometric parents
Ordered page masters
The orderedOccurrence page-set strategy selects page areas in document order, honors finite occurrence limits and repeats nested page sets with their own counters; ordinary flow, positioned repeating content and supported explicit page/content-area breaks share the resulting page sequence
Each selected master supplies its own content-area origins and heights, and its fixed fields and draws are copied only onto pages using that master; unselected masters do not paint on the first page
Page-area and page-set occurrence defaults are min=0 and max=-1; initial does not create page instances, max=0 skips a master, and minimum occurrences can retain otherwise empty pages after the content ends
When all finite page-set occurrences are exhausted, layout retains the placed prefix, stops placing subsequent content and records a warning; it does not silently repeat the final master or switch to another top-level page set
Physical page queries and logical numbering use the same selected masters and retained pages
Each realized page can also use its selected master's physical media size and remeasure flowing content for its actual content width; qualified simplex and duplex strategies select masters through a separate qualification and terminal-replay process
Qualified simplex and duplex page masters
For simplexPaginated and duplexPaginated page sets, natural foreground pagination chooses the first suitable direct pageArea in document order, using pagePosition first, rest or any; page-set and page-area occur properties do not limit qualified instances
Each contiguous run of a selected qualified set has its own first/rest and terminal state; nested qualified sets are reached through explicit breaks, and a transition ends the old run before starting the new one. Ordered and qualified page sets cannot be nested inside one another
At the end of a one-page run, an only master is tried by actually laying out its content at the candidate content-area widths and heights; a successful trial replaces the page, while a trial that cannot fit retains the original page without adding an only or last page
For last, replacement also requires the same number of content areas and an existing terminal master not qualified as first or last. A fitting trial replaces the terminal foreground page; otherwise the original foreground stays and the designated last background is appended, with any required duplex side filler
Terminal trials preserve the complete source text, data-instance identity, ordered boundaries and already committed prefix geometry; real font measurements, text continuation, rows and flow lines participate in replay. Layout and measurement work remain budgeted, and resource or budget errors are not treated as ordinary non-fit fallback
Duplex selection combines page position, physical front/odd or back/even side, and blankOrNotBlank reason. Physical sides start with the first XFA surface as front/odd and are independent of initialNumber, numbered and a component destination's preceding pages
Unconditional pageOdd and pageEven breaks, named-target side alignment and duplex closure can retain real background-only filler pages; blank is a pagination reason rather than a test for an empty widget list, and foreground content is not placed on a filler surface
For simplex, this implementation follows the relation-property reference in XFA 3.3 printed page 798 and ignores oddOrEven and blankOrNotBlank during qualification. The processing discussion at printed page 304 instead describes a fixed odd/front state; choosing the relation-specific rule resolves that conflict for this implementation and is not an Adobe interoperability measurement
A missing suitable natural foreground candidate is a layout error, not permission to repeat an unsuitable master or manufacture blank foreground pages. Native page and content-area SOM routing, modern break decorations and medium prototype and supplied-stock resolution retain their documented profiles; more general XFA layout remains active work
Per-master physical media
The selected page area's medium supplies a physical size in PDF points when short and long are finite positive lengths with long greater than short; portrait places short across the page width, and landscape places long across the width without adding a second content rotation
Medium prototype and supplied-stock resolution prepares use/usehref inheritance once and optionally resolves a zero/default edge pair through a caller-supplied stock provider; valid explicit edges retain priority. With no stock provider, unresolved dimensions retain the caller's page size, while malformed explicit pairs retain the existing warning and fallback. Configure TXFAHeadlessPDFOptions.MediumResolution or use the medium-aware full flatten overload
The final physical-page sequence supplies each page's size, including minimum-occurrence and terminal empty pages; positioned overflow and instance page queries use the same actual page heights and content-area origins
TXFAPageSize stores Width and Height as Double values, and TXFAPageSizes is their physical-page vector. The media-aware full HPDFXFAFlatten overload accepts a TXFAEmitPage callback after AMeasureText and before out PhysicalPageCount
function HPDFXFAFlatten(const XDPBytes: TBytes; PageW, PageH: Double;
Editable: Boolean; const EmitField: TXFAEmitField;
const EmitDraw: TXFAEmitDraw; Warnings: TStringList;
const AScriptOptions: TXFAFormScriptOptions;
const AInstanceAction: TXFAFormInstanceAction;
const AMeasureText: TXFAMeasureTextFunc;
const EmitPage: TXFAEmitPage;
out PhysicalPageCount: Integer): TXFAFlattenResult; overload;
EmitPage(PageIndex, Width, Height) reports contiguous zero-based pages before any field or draw callback; existing overloads delegate without this callback and remain source-compatible, while custom consumers need the media-aware overload to apply mixed sizes
Native headless creation writes each page's own MediaBox and converts top-left field and draw coordinates once using that page's height, retaining page budgets and candidate-stream publication
Component flattening applies each size from the original current-page destination onward, validates component coordinate and device limits before adding that page, and restores the original current-page selection in cleanup; preceding pages remain untouched and earlier content on resized destination pages is not automatically scaled
Changing content-area widths
Flowing content uses the actual destination content-area width when computing omitted widths and intrinsic text heights; supported top-to-bottom flow, left-to-right flow lines and table rows can therefore remeasure and repack when the selected area changes
Explicit field and container widths remain explicit, while inherited available widths account for container insets and positioning offsets. A text continuation measures its remaining source text at the destination width and places subsequent content after the committed fragment
Rows and flow lines move together according to their recomputed height, retaining repeated data-instance identity and source-ordered break and query associations. If a starting area has no usable inherited width after its insets, content can remain pending for a later usable area instead of disappearing
Native headless creation supplies intrinsic text measurements from the same supplied TrueType font and appearance layout used for output, with temporary-work budgets and cancellation checks. This does not add font fallback, additional typeface selection or general glyph-ink containment beyond the existing appearance clip
Finite page-master exhaustion retains the placed text prefix and its actual pages without publishing later content; it does not turn a measurement or resource failure into a successful partial document
Named page and content-area breaks
breakBefore and breakAfter can target a pageArea or contentArea by its case-sensitive XML ID or supported native structural SOM expression, resolved in the actual asserting instance and data context; routing can leave an unlimited earlier master directly instead of waiting for its repetitions to end. Within qualified pagination, the existing pageSet target profile enters that set through its qualifying initial master
With startNew=0, a request matching the current target preserves the current layout position; startNew=1 requires an unused matching instance, and another unused contentArea on the current page can satisfy a content-area request
Ordered routing preserves occurrence counts within the actual enclosing page-set instance, creates a new enclosing instance only when permitted and emits required minimum pages when leaving a branch; an exhausted finite destination retains the placed prefix and produces a warning. A qualified same-set page-area target preserves the current run rather than restarting its first-page state; explicitly blank masters cannot be direct break targets
A root-subform entry target normally selects the initial destination without adding a preceding page. An enabled startup trailer is placed in the original initial area before routing, so its actual placement can retain preceding pages; without a root target, only an actual leading subform can supply the initial destination. A later subform's break remains ordered after preceding fields, and an explicit startNew request can retain an initially blank destination page
Outgoing after-breaks and incoming before-breaks run in order, including empty containers and terminal after-breaks; fixed master content and page queries follow the resulting physical sequence
Body coordinates begin at the actual initial content-area origin, including ordinary startup without a named target; fixed master content retains page-relative coordinates, and natural overflow skips areas already entered through a reverse target
Native SOM page routing preserves actual occurrence and entered-area history, destination-width continuation and overflow-trailer reservation; invalid targets retain diagnosed fallback, while script, cancellation and budget failures propagate. Independent overflow-decoration inheritance, shared presentation maxima and ordered target lists follow their own instance-scoped rules; broader dynamic XFA layout remains active work
Conditional page-break scripts
A nonempty script on breakBefore or breakAfter executes at its layout boundary in the actual enclosing subform instance and its bound data context; startup target selection also evaluates its condition before choosing the initial master
An absent or empty script leaves the break unconditional. An omitted or empty contentType selects FormCalc; JavaScript requires ScriptOptions.EnableJavaScript. FormCalc uses the native expression evaluator where applicable and the configured native script bridge for compiled event statements, without enabling raw JavaScript globally
A false result suppresses the page-break action while preserving the script's effects; a script with targetType auto or no targetType still executes even when it requests no page movement
Each layout cycle records condition decisions by actual instance identity. Internal destination-width plans, terminal only/last trials and mutation-driven layout restarts reuse those decisions, so speculative replay does not repeat published side effects; a later real layout request starts a new cycle
Supported data or instance mutations restart layout safely and invalidate dependent flatten text values before remeasurement. Script failures propagate through the existing runtime transaction or native PDF preparation boundary rather than being treated as an ordinary false condition
Conditions retain the runtime's completed-snapshot contract for physical and logical page queries; they do not force synchronous layout queries at the partially placed boundary. Movement-target predicates follow the trailer at actual placement and reuse accepted decisions across internal replay; medium resolution retains its separate preparation and fixed-session lookup contract
Modern break leaders and trailers
Supported breakBefore and breakAfter boundaries process their condition, place the trailer at the outgoing cursor, apply the page or content-area route, and then place the leader at the resulting cursor; an entry leader precedes the parent content, while an exit trailer follows it
A false condition suppresses both decorations and the route without discarding otherwise successful script effects. An absent or empty script is unconditional; a true boundary with auto or omitted targetType, or a matching target that needs no movement, still inserts its trailer and leader in that order
The leader and trailer references select one subform or subformSet by XML ID or supported native structural SOM, in the actual form and repeated-data context. Structural selection and supported literal property filters do not require a script bridge; computed predicates use the existing script configuration and limits rather than bypassing JavaScript opt-in
Reusable template or ID targets and shared targets without a selected repeated instance use the asserting owner's data context; a target resolved to an actual repeated instance retains that instance's data, including inferred or relative occurrences. The resolved instance determines this choice, not the presence of brackets in the reference
Generated content is measured and placed at the actual content-area cursor and available width, consumes flow space, and uses the existing overflow and destination-width planning rules. Internal width plans and only/last terminal replay retain its generated source identity and condition decisions instead of adding another published decoration or repeating side effects
Native flattening and headless PDF creation consume the resulting fields, draws and physical pages through the existing adapters, preserving the effective owner and target data bindings. At emission, each generated copy reads its original shared XFA form value while PDF field names remain distinct
This profile covers modern breakBefore and breakAfter decorations. Overflow trailer reservation and actual-cursor placement, overflow presentation maxima and target lists and bookend entry and final-exit content retain their separate contracts
Bidirectional keep and intact content
keep.next and keep.previous establish the same adhesion between adjacent actual sibling instances. Repeated instances keep their own source and data identity, and a transparent subformSet exposes its logical children for adjacency; an ordinary nested subform remains an ownership boundary
contentArea requires the touching content to share one region. pageArea permits different content areas on the same physical page and preserves a legal placement across remaining regions before moving to another page. If the two declarations disagree, contentArea is the tighter constraint; a missing neighbor or two none values adds no adhesion
An intact owner remains indivisible within its requested scope. A splittable owner instead contributes its adjoining legal fragment to the neighboring keep constraint, so earlier and later text may remain on other pages. Linking both ends does not turn the entire multiline object into one indivisible box, and continuation preserves complete source text and instance identity
Explicit keep.intact values remain authoritative. An unassigned intact uses the owning object's current class and layout: position or row subforms and draws default to contentArea, while flowing or table subforms and fields default to none. This implementation follows the property reference on XFA 3.3 printed page 762; the processing discussion on printed page 292 describes a different container-layout default
Placement measures complete occupied container, row or tiled-line extents and remeasures moved owners and text fragments at the actual destination width. The next legal destination follows the accepted overflow target, rather than an unrelated sequential page. Bookend entry and final-exit content, overflow-trailer reservation and accepted presentation limits remain part of the available capacity
If an empty current region and its next legal region both cannot accommodate the constrained content, even by an allowed split, layout force-uses the current region and retains logical overrun instead of generating blank pages indefinitely or discarding the content. Existing appearance clipping remains in effect; finite page sequences do not gain fabricated destinations
An accepted mandatory break movement retains its routing semantics and ends the current keep segment. This is the compatibility policy for conflicting authoring constraints; a false condition or a boundary that does not move does not sever adhesion. Rejected destination trials and qualified terminal replay retain accepted instance, presentation and script-decision state
The same native layout contract is used by Flatten, headless creation and Runtime reflow. Broader layout and script-event compatibility and general dynamic XFA remain separate work
Bookend entry and final-exit content
Each admitted actual subform or subformSet instance can insert a bookend leader before its ordinary body and a trailer after the complete body. A body split across content areas receives one opening and one final closing presentation, rather than a pair per fragment; admitted empty instances retain both ordered events, while omitted instances add no content
Entry order is the admitted modern breakBefore trailer, route and leader, then the bookend leader and ordinary body. At final exit the bookend trailer precedes the admitted modern breakAfter trailer, route and leader. A false modern break condition does not suppress the object's bookends, and bookends themselves do not force a page transition
A single XML ID reference prefixed with # or a supported native SOM expression selects a positioned subform or subformSet source. Empty or blank references add nothing, and an absent child bookend does not inherit its containing owner's bookend. Reusable sources use the asserting instance's data; an explicitly selected actual repeated target retains its selected data context
Placement uses the actual destination width and page/content-area cursor, including source height and final tail space. A final bookend trailer can advance normally when it does not fit; it is not the overflow trailer reserved on each body fragment, is not an overflow target list and does not spend an overflow presentation pool
Bookend placement preserves complete row and container extents and their natural gaps within the owning body; unrelated designer-positioned siblings retain their original positioning contract
Root, nested and repeated owners follow these same entry and final-exit rules. Generated interaction identities distinguish bookends from ordinary break and overflow presentations while retaining the underlying shared values. Internal width planning and accepted terminal replay retain the existing transaction and decision-reuse rules; broader layout and script-event compatibility remain separate scope
Preparation and limits
TXFAHeadlessPDFOptions bounds XDP and font bytes, output and object bytes, object and page counts, fields and aggregate UTF-16 glyph units
Object, page and glyph budgets are checked before their corresponding allocations; embedding checks bound aggregate font and image streams, image decoders bound their working buffers, and native serialization enforces object and complete candidate byte limits
Cancellation is checked throughout graph creation, appearance generation and serialization; all preparation failures leave the destination stream's position, length and existing bytes unchanged
The complete candidate is prepared in memory before one WriteBuffer call to the destination; destination I/O errors propagate and may leave partial writes according to the caller's stream behavior
The output is a new unsigned document; preserving imported encryption, existing signatures and source revisions belongs to the native document import and revision APIs
Acceptance
Tests/Linux/XFAHeadlessCreationTests.pas produces actual repeated, paginated and globally read-only documents, an event-mutated saved-XDP document and a styled Unicode draw document without opening a reader UI
Tests/Linux/Verify-XFAHeadlessCreation.py independently verifies native values, field flags, page ownership, /AP and embedded font resources with pypdf, and real text and rendered appearance pixels with MuPDF
Tests/Linux/XFAHeadlessChoiceTests.pas and Verify-XFAHeadlessChoice.py add actual choice values and flags, radio parents and repeated scope identities, reserved export states, runtime save/reload and rollback, and rendered selection pixels
TXFAHeadlessPDFResult reports the actual native graph and serialization counts