Help us shape the future of Go! Take the 2026 Go Developer Survey

xfa

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

README

xfa — go-pdfkit

License

Read the form inside a PDF whose pages are blank. Pure Go, no cgo.

A PDF form comes in two kinds and only one of them is a PDF form. Of 2 240 real government forms, 560 carry an XFA package — and 546 of those are static: a second, proprietary description of a form already drawn on the pages, which go-pdfkit/forms reads and fills without help.

The other fourteen are dynamic. Their pages hold a panel reading "Please wait... your PDF viewer may not be able to display this type of document", and the form exists only as XML. Adobe removed the format from PDF 2.0; no browser and no other reader lays one out. Somebody handed such a file has a document that looks blank and is not.

What it does not do, and why that is a decision

It does not run the forms' scripts. That is measured, not assumed: of 5 744 scripts across those fourteen forms, 5 131 are handlers for enter, exit, change and click — they fire when somebody types. Only 188 run at load, so the form a reader first sees does not depend on them.

FormCalc, XFA's other scripting language, is not read either: every script in the corpus declares itself as JavaScript. The reference implementation (pdf.js) spends 37 KB on FormCalc that this does not need.

Joining a field to its value

Bind takes a parsed template and parsed datasets and hands back each field with the value bound to it — name, path, data path, value — so a caller can fill in a form without knowing XFA.

That is not name-matching. A form binds explicitly through <bind> elements, and where it does not, each container consumes the next unclaimed data node of its own name in document order. The two trees are named differently on purpose: the template names a field for the layout, the data names it for the record. In one real form the field at FormulaireGf.Page1.MEP.NumeroCerfa takes its value from the attribute at FormulaireGf.MetierGf.DemandePensionAscendants/@Cerfa.

Measured over all 560 XFA packages in the corpus:

templates read 560
<bind> elements 26 573
— match="none" 11 875
— match="global" 11 544
— no match (means once) 2 589
— match="dataRef", every one with a ref 565
fields placed 80 482
fields bound to a data node 60 865
<bind> expressions holding a construct this does not read 0

Every ref in the corpus is a plain path, a $record path, a $ path, or one of those with [*]. None of SOM's hard parts — FormCalc subexpressions .[…], JavaScript predicates .(…), negative indices — occurs even once.

Where this deliberately differs from pdf.js

The reference implementation is Mozilla's src/core/xfa/bind.js, and this follows it closely. Four differences, each deliberate:

  • It invents no data nodes. pdf.js, meeting a ref that matches nothing, creates the nodes the expression describes so a person can type into them. This reads documents rather than editing them, so the field is reported unbound — the same answer, since an invented node is empty.
  • It does not repeat a container to satisfy occur's initial. Those clones carry no data; they change the layout, not the values.
  • It descends into pageSet and pageArea. pdf.js binds nothing there. Of 82 386 template fields in the corpus, 628 sit under a page area across 177 forms — and one form has no fields anywhere else, so dropping them silently would lose it whole.
  • It stops a global search that has begun to repeat. pdf.js's global lookup does not skip what it has already handed back, so match="global" under an unbounded occur asks for the same node for ever.

It is also linear where pdf.js is quadratic: a search for a name under a data node resumes where the last one stopped, rather than beginning again.

Where a field goes on the page

Expand joins the two trees and returns the form as a document holds it — one node per occurrence, so a table row written once and filled three times is three nodes. Layout runs over that and never over the template, which is what pdf.js's binder does too (bind.js:61).

Place lays a form out on paper. Under a positioned layout a box's place is its own x and y added to those of every container above it, down from the content area's origin, with anchorType and rotate resolved. Under a flow layout the coordinates are thrown away and the children are stacked, and this follows two of the six:

  • tb and table stack downwards. Each child begins where the one above it ends (layout.js:144-158, extra.height += h), and a container's own height is the taller of what it holds and what the template writes for it (template.js:5222) — so the heights are arrived at from the leaves upwards, out of the literal w and h the template already carries. A container's margin is outside what it holds: it moves the children in and adds all four insets to the height reported upwards.
  • row cuts its cells from the columnWidths of the table above it (html_utils.js:81-106), a cell spanning colSpan of them, and stretches every cell to the height of the tallest.

lr-tb wraps its children onto lines, which needs a line-breaking rule; rl-tb and rl-row fill from the right, which needs a width. Only the first child of an lr-tb is placed.

Nothing is dropped. Every field and every draw of the form's body comes back in exactly one of Page.Boxes and Layout.Unplaced, and each unplaced one carries the reason in words. A layout that reaches part of a form is useful; one that silently drops the rest is not, because nothing downstream can tell a form that was laid out from a form that was half laid out. A page area's own furniture is the exception, and it is not a leak: a letterhead belongs to the sheet, so it is drawn once on every sheet that page area makes.

Where it runs off the bottom, it turns the page

Which page comes next is not "another of the same". It is decided by a state machine — the page set's relation, each page area's <occur>, the parity of the page number, and the explicit <breakBefore> and <breakAfter> the template writes — and this follows pdf.js's (template.js:4064-4236, 5418-5657) rather than assuming. Every container of the chain being flowed begins again at the top of the new content area, which is what pdf.js arrives at by re-entering the whole tree with a new space.

Breaks are not a corner: 435 of the 560 forms carry a <breakBefore>, and 2 155 of the 2 561 in the corpus are startNew="1", which means "a fresh sheet here, once".

A container that would have to be broken in two for its parts to fit is not broken. pdf.js keeps [$extra].children, a generator and a failingNode to do that (layout.js:38-53); this does not. A container that may be split (Subform[$isSplittable], template.js:4940-4975) has its children distributed across sheets instead, which is the same thing where the container itself draws nothing. One that may not — a positioned layout, a row, or anything with keep intact — moves whole, and is reported unplaced where it fits no sheet at all. 1 355 elements in the corpus carry keep intact="contentArea", which is a designer saying "do not let this row land half on one page and half on the next".

The recursion pdf.js dies on is not in the branch it looks to be in

pdf.js exhausts its stack on 7 of the 560 forms, going round between PageSet[$getNextPage] and PageArea[$getNextPage]. The branch it is usually blamed on is the last one:

this[$cleanPage]();
return this[$getNextPage]();

$cleanPage clears the [$extra] of every page area and page set below the set and not the set's own, so the call returns to state no different from the state it left.

The defect is not in that one branch. The branch above it does the same thing — a page set whose <occur> still allows another run resets its own indices and calls itself, and comes back to the same place when every page area below it has spent its own <occur>. A faithful port has to guard every way a page set can start itself again, not the one named after cleaning. So here a page set may restart at most once per request for a page, cleaning really does reset the set's own place in its list, and a page set holding neither a page area nor a page set says so rather than looping. Both branches were found by porting the machine and running it over the corpus, not by reading it: the second one was a stack overflow in this package's own tests.

Measured over the same 560 packages:

fields in the body of the expanded forms 81 750
placed 29 123
draws placed with them 49 329
sheets they came to 1 237
waiting on a height only measuring text would give 44 246
a height written as =0mm, which is not a length 3 649
under a layout this does not follow (lr-tb) 3 124
a place computed and nowhere left to put it 1 608
The prediction was 36 494, and the gap is the finding

Slice 2 placed 15 400 fields and reported that 21 094 more had a place computed that fell past the bottom of the one content area it laid out — so "the arithmetic reaches 36 494" once the page turns. It reaches 29 123.

Of those 21 094 (20 736 counted by path), pagination placed 14 077 — 68% of them. The other third were never behind pagination at all:

what became of a field that fell past the bottom
placed, once the sheet turned 14 077
held up by a leaf above it with no written height, further down the same stack 5 156
taller than a whole content area, and cannot be broken 885
the form ran out of pages 405
no room inside a container that moves whole 167
other 46

The page-1 cutoff was masking text measurement. A field reported as "past the bottom" was one whose place had been computed on the assumption that everything above it on that page had a height; once the page turns and the stack goes on, a quarter of them turn out to sit below a leaf that writes none. Which is the same shape of error as the two before it: a question asked about one node — does this one's place fall past the bottom? — where the structure is a chain.

Checked against pdf.js, which CAN see this

pdf.js emits one <div class="xfaPage"> per sheet, with every element inside the one it belongs to. That is said outright, in the structure of the output rather than in a style, so page count and per-page membership are comparable even where a coordinate is not.

It has to be narrowed, because pdf.js measures text and this package does not: on a form where a leaf writes no height pdf.js lays out elements this leaves unplaced, and more elements need more sheets. So the count is compared strictly only on the forms where every element of the body was placed.

forms where this package placed every element of the body 199
of those, agreeing with pdf.js on the number of sheets 198 99.5%
boxes paired on those forms 23 006
on the same sheet as pdf.js put them 23 006 100.00%
on another sheet 0 0.00%
forms where fewer elements were placed, and so fewer sheets used 221
... the same number of sheets 63
... MORE sheets, which would be a defect 0 0.00%

The one disagreement, us-opm__sf813, is not pagination: its outermost subform is positioned, and pdf.js's checkDimensions position arm (layout.js:355-364) sends children that reach past the bottom of the content area onto a second sheet. This package does not fit-check a positioned layout at all — it did not in slice 1 either — so it draws them where their coordinates say, off the bottom of the one sheet.

The heights and the placements are still checked, and both still agree exactly:

container heights this package computes, paired with pdf.js's 7 072
agree to within 1/100 pt 7 072 100.00%
boxes where pdf.js emits a real place 450
agree exactly 450 100.00%
boxes pdf.js placed by flexbox, none above or left of its container 51 312

What none of this covers: where inside a container the children ended up (two orderings come to the same total); borders, margins and insets on positioned layouts, which pdf.js writes as CSS calc(); text measurement; anything under a rotated ancestor; and breaking one container in two across a sheet. It also could not run on 77 of the 560 forms — 70 because pdf.js's selectFont dereferences a null typeface when no font is supplied (fonts.js:159), and 7 for the recursion above.

Lengths

XFA's units are mm, pt, in, cm, pc, mp, em and % — the list Foxit's implementation recognises in pdfium's CXFA_Measurement, which is the implementation closest to Adobe's own. px is not one of them. pdf.js reads it as one point and this package used to read it as 72/96 of one; both were HTML habits carried into a format that does not have the unit. A length in px is now refused rather than guessed at, and the element carrying it is reported unplaced. No x, y, w or h in the corpus is written in it.

Node.Measure answers three ways, not two: the attribute is absent, or it is a length, or it is there and unreadable. XFA's "unspecified" and its "zero" are different things — a field with no width has no width until its text is measured, which is not the same as a field nought wide — and pdf.js loses the distinction in measureToString, which turns any string into "0px".

Documentation

Overview

Package xfa reads Adobe's XML Forms Architecture — the form description carried inside a PDF whose pages are a placeholder.

Why this exists

A PDF form comes in two kinds, and only one of them is a PDF form. Measured over 2 240 real government forms: 560 carry an XFA package, and 546 of those are STATIC — a second, proprietary description of a form that is already drawn on the pages, which go-pdfkit/forms reads and fills without help.

The other fourteen are DYNAMIC. Their pages hold a panel reading "Please wait... your PDF viewer may not be able to display this type of document", and the form exists only as XML, laid out when the document is opened. Adobe removed the format from PDF 2.0; no browser and no other reader lays one out. A person handed such a file has a document that looks blank and is not.

What it does, and what it will not

This reads the template — the description of the form — into a typed tree, and the datasets, which hold what has been filled in. It does not run the forms' scripts, and that is a measured decision rather than a shortcut: of 5 744 scripts across those fourteen forms, 5 131 are handlers for enter, exit, change and click. They fire when somebody types. Only 188 run at load, so the form a reader first sees does not depend on them.

FormCalc, XFA's other scripting language, is not read either: every script in the corpus declares itself as JavaScript.

Joining a field to its value

Bind does that, and it is not a matter of matching names. A form binds its fields to its data explicitly, through <bind> elements — 26 573 of them across the 560 XFA packages in the corpus — and where it does not, each container consumes the next unclaimed data node of its own name, in document order. The two trees are named differently on purpose: the template names a field for the layout and the data names it for the record.

Taking the fourteen dynamic forms and asking how many template paths the data happens to answer:

cerfa_12064      212 fields, 220 values,  0 paths in common
t657-fill-25e    459 fields, 459 values,  0 paths in common
cerfa_12818       72 fields,  72 values, 47 paths in common
CA-27_sample     136 fields,  99 values, 69 paths in common

The same count of each and not one path in common is what settles it: two of these forms name every field twice over, and only the binding says which goes with which. Guessing by name would answer confidently and wrongly.

Measured over all 560 packages:

560 templates read, 560 with a data tree
26 573 <bind> elements: 11 875 match="none"
                        11 544 match="global"
                         2 589 with no match, which means "once"
                           565 match="dataRef", every one with a ref
80 482 fields placed, 60 865 of them bound to a data node
     0 <bind> expressions holding a construct this does not read

Where a field goes

Expand joins the two trees and returns the form as a document holds it — one node per occurrence, so a table row written once in the template and filled three times by the data is three nodes. Layout runs over that and never over the template, which is what pdf.js's binder does too and for the same reason (bind.js:61).

Place then lays a form out on paper. Under a POSITIONED layout a box's place is its own x and y added to those of every container above it, down from the content area's origin, with anchorType and rotate resolved. Under a FLOW layout the coordinates are thrown away and the children are stacked instead, and this follows two of the six: tb and table stack downwards, each child beginning where the one above it ends, and row cuts its cells from the table's columnWidths. A container's height is the taller of what it holds and what the template writes for it, so the heights are arrived at from the leaves upwards.

Where the stack runs off the bottom, the page turns. Which page comes next is a state machine rather than "another of the same" — the page set's relation, each page area's occur, the parity of the page number, and the explicit breaks the template writes — and Place follows pdf.js's (template.js:4064-4236, 5418-5657). A container that MAY be split has its children distributed across sheets; one that may not — a positioned layout, a row, anything with keep intact — moves whole. Breaking one container in two is a slice of its own.

Everything it does not reach — lr-tb and the two layouts that fill from the right, sizes only text measurement would give, a container taller than any sheet, a form that runs out of pages — comes back in Layout.Unplaced with the reason written out, one element at a time. Nothing of the body is dropped. A page area's own furniture is drawn once on every sheet that page area makes, which is the one thing not in one-to-one correspondence with the boxes on the paper.

Measured over the same 560 packages:

81 750 fields in the body of the expanded forms
29 123 placed, 49 329 draws with them, on 1 237 sheets
44 246 wait on ONE thing: a height only measuring text would give, nearly
       all of them a leaf ABOVE them in the same stack
 6 773 sit under a layout this does not follow, or below a height written
       as "=0mm", which is not a length
 1 608 have a place computed and nowhere left to put it

What checks it

pdf.js emits no coordinates for a child of a flow layout — it writes them into a flexbox column and lets the browser stack them — so for exactly the layouts this computes, its output says where the CONTAINER is and nothing about where the second child went. It does emit the accumulation itself, as a number: a subform's style.height is Math.max(extra.height + marginV, this.h || 0) (template.js:5222).

It also emits one div per SHEET, with every element inside the one it belongs to — which is a thing it says outright, so the page a box landed on can be compared even where its coordinates cannot:

 7 072 container heights this package computes, all agreeing with pdf.js's
       to within 1/100 pt
   450 boxes placed where pdf.js also emits a place: all agreeing
   199 forms where every element of the body was placed, so that the two
       are laying out the same thing
   198 of those agreeing with pdf.js on the NUMBER of sheets
23 006 boxes paired on them, every one on the same sheet as pdf.js put it,
       and none on another

The 44 246 fields waiting on text measurement are the finding of these two slices, and they overturned an earlier count twice. A count over the templates said 446 fields — half of one per cent — need their text measured. Only 8 466 draws and 598 fields of the corpus's 234 000 leaves lack a height, but a stack is a chain, and one unmeasurable height leaves every sibling below it with nowhere to begin. Then the one-page bound was found to be masking more of the same: of the 21 094 fields reported as falling past the bottom of the first sheet, pagination placed 14 077, and a quarter of the rest turned out to sit below a leaf with no written height further down.

Values and FieldNames remain what they were — what the data says, and what the template says, each on its own — for a caller that wants one side without the other. Values names a repeated sibling the way a binding does, "Row[1]", because a form's table is repeated siblings and naming them alike was losing 10 125 of the corpus's 71 346 values.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FieldNames added in v0.2.0

func FieldNames(template *Node) []string

FieldNames are the paths the TEMPLATE gives its fields, in the order it places them.

The path is the template's, and it is NOT necessarily the path the data uses. XFA binds a field to its data explicitly, through <bind> elements — one real form here carries 222 of them — and a form may name its root subform one thing while its data calls it another. Joining the two by path is right for a form that binds implicitly and wrong for one that does not, which is why this does not try: Bind does the joining properly, and hands back each field with the value actually bound to it.

Fields are looked for inside page areas as well as inside subforms. That is not a nicety: of the 212 fields in one real form, every one sits under a pageArea, and a walk that followed only subforms found none of them.

func Value added in v0.2.0

func Value(data *Node, path string) (string, bool)

Value is one field's value, by its whole name. The second and later of repeated siblings are addressed by index — "form1.Row[1].Cell".

func Values added in v0.2.0

func Values(data *Node) map[string]string

Values are what a form has been filled with, by the whole name of each field: "form1.Page1.Line101".

The names are joined with dots, as XFA's own scripting language names them, and the root of the data tree is included because a package may hold more than one form.

Repeated siblings are numbered the way Bind numbers them and the way a SOM expression addresses them: the first of a name plain, the rest "Row[1]", "Row[2]", counting from zero. Without the numbers they collide, and a table of six rows comes back as one — 10 125 of the 71 346 values the corpus carries, across 216 of its 560 forms, were lost that way before this counted them.

A field a person has not filled in has an empty value rather than no entry. The difference matters: "this field exists and is empty" and "there is no such field" are different answers, and a caller checking whether a form is complete needs the first.

Every value the data carries comes back. There is one entry per leaf and one per group that carries text of its own, and no two share a key.

Types

type Binding added in v0.3.0

type Binding struct {
	// Name is the field's own name, as the template writes it.
	Name string
	// Path is where the FORM puts it: dotted names from the root, with an
	// index — "Row[2]" — on the second and later of repeated siblings. A
	// nameless container contributes nothing to it.
	Path string
	// Kind is "field" or "exclGroup".
	Kind string
	// Node is the template element.
	Node *Node
	// Data is the data element it was bound to, or nil.
	Data *Node
	// DataPath is where that element sits in the DATA, which is a different
	// tree and often a differently named one. Empty when nothing was bound.
	DataPath string
	// Value is what the data says, trimmed. Empty when nothing was bound.
	Value string
	// Bound says a data node was found. A false here with a non-empty form is
	// the ordinary state of a blank document, not an error.
	Bound bool
}

A Binding is one value-carrying container of a form — a field, or the exclusion group a set of radio buttons shares — joined to the data node it draws its value from.

Every such container appears, filled or not. Bound says which: a field the form places but the data never mentions has Bound false and an empty Value, and that is a different answer from a field bound to an empty string. A caller checking whether a form is complete needs the difference.

type Box added in v0.5.0

type Box struct {
	// Node is the occurrence this box was placed for.
	Node *FormNode
	// Kind is "field" or "draw".
	Kind string
	// Path is [FormNode.Path], repeated here so a box can be reported on its
	// own.
	Path string
	// Rect is where it goes, absolute on the page, with anchorType and rotate
	// already resolved.
	Rect
	// Rotate is what the template says, in degrees clockwise: 0, 90, 180 or
	// 270. Rect is the box the rotated element occupies; this says how the
	// content inside it is turned.
	Rotate int
	// Value is what the data put in it, for a bound field. Empty otherwise.
	Value string
	// Hidden says the template asks for it not to be drawn: presence
	// "hidden" or "inactive". pdf.js emits display:none for both
	// (html_utils.js:133-141) and a flow layout gives them no room, so the
	// element after one begins where it does. It is reported rather than left
	// out, because a caller counting what is on a page needs to know that
	// something is there and asked not to be seen.
	Hidden bool
}

A Box is one element of the form, placed.

type Form added in v0.5.0

type Form struct {
	// Root is the <template> element's node. Under it sit the form's
	// outermost subform and, inside that, the page set.
	Root *FormNode
	// Unsupported are the <bind> expressions that were not followed, as
	// [Bind] reports them.
	Unsupported []Unsupported
	// Truncated says expansion stopped early. See [Result.Truncated].
	Truncated bool
}

A Form is a template and the data that fills it, joined and expanded: the tree layout runs over.

func Expand added in v0.5.0

func Expand(template, data *Node) *Form

Expand joins a template to its data and returns the form tree, with every container repeated once per record that fills it.

Why this exists beside [Bind]

Bind answers "what is in this form", and a flat list of fields answers it well. Layout asks a different question — where does each one go — and the answer is in the shape: a field's place is its own x and y added to those of every container above it, and a container repeated eleven times is in eleven different places. A list of bindings has nowhere to put the eleven.

This follows pdf.js, whose binder does the same thing and for the same reason: Binder.bind returns a clone of the template (bind.js:61) into which _bindOccurrences (bind.js:385-417) inserts one copy of the container per matched data node. Layout there never sees the template either.

Where it goes further than [Bind]

It descends into an exclGroup. A group of radio buttons carries one value between them, so binding stops at the group; but each button is drawn in its own place inside the group's box, so layout needs them. They appear with Bound false, which is what they are: the value belongs to the group.

It carries <draw> — the static text, lines and boxes a form is mostly made of. A draw holds no data, so Bind has nothing to say about it and does not report it. It is half of what is on the paper.

Where it stops, as [Bind] does

It does not clone a container to satisfy occur's initial count when the data is empty, which pdf.js's _createOccurrences (bind.js:421-462) does. Those clones carry no data; they are blank rows on a blank form.

type FormNode added in v0.5.0

type FormNode struct {
	// Template is the element this was made from. Everything the template
	// says that this struct does not carry — x, y, w, h, layout, border,
	// caption — is read from there.
	Template *Node
	// Kind is the element's name: "subform", "field", "draw", "pageArea".
	Kind string
	// Name is what the template calls it, which may be empty.
	Name string
	// Path is where this occurrence sits in the form: dotted names from the
	// root, with an index — "Row[2]" — on the second and later of repeated
	// siblings. It is the same path [Binding] carries, for the containers
	// that carry one.
	Path string
	// Kids are the containers inside it, in the order the form places them.
	Kids []*FormNode
	// Data is the data element this occurrence was bound to, or nil.
	Data *Node
	// Value is what that element says. Empty when nothing was bound.
	Value string
	// Bound says a data node was found for this occurrence.
	Bound bool
}

A FormNode is one container of the expanded form: one subform, one field, one draw, as the document actually holds it rather than as the template writes it.

The difference is repetition. A template writes a table row once and says, in its <occur>, that there may be many; the document has one row per record. Expand does that expansion, so a FormNode tree has one node per occurrence and a template tree has one per element. Two nodes cloned from the same template element share their Template and differ in their Path and their value.

func (*FormNode) Walk added in v0.5.0

func (n *FormNode) Walk(visit func(*FormNode))

Walk calls visit on the node and everything under it, depth first, in the order the form places them.

type Layout added in v0.5.0

type Layout struct {
	// Pages is the sheets the form came to, in order.
	Pages []Page
	// Unplaced is everything it did not place, with a reason each.
	Unplaced []Unplaced
}

A Layout is a form placed on paper.

func Place added in v0.5.0

func Place(form *Form) *Layout

Place lays a form out on paper.

What it does

Under a POSITIONED layout every container has an x and a y that mean what they say, so a box's place on the page is its own x and y added to those of every container above it, down from the content area's origin, with anchorType and rotate resolved on the way (pdf.js layout.js:202-259). That is what pdf.js computes too — under "position" it emits style.left and style.top from the node's own x and y (html_utils.js:112-123).

Under a FLOW layout the coordinates are thrown away (html_utils.js:347-350) and the children are stacked instead. This follows two of the six:

  • tb and table stack downwards. The first child sits at the container's own origin, and each one after it begins where the one above it ends (layout.js:144-158, extra.height += h). A container's own height is the taller of what it holds and what the template writes for it (template.js:5221-5223), so the heights are arrived at from the bottom of the tree upwards, out of the literal w and h of the fields and draws at the leaves.
  • row cuts its cells from the columnWidths of the table above it (html_utils.js:81-106), a cell spanning colSpan of them, and stretches every cell to the height of the tallest (layout.js:135-143).

A container's margin is its own, outside what it holds: it moves the children in by the left and top insets and adds all four to the height the container reports upwards (template.js:5217-5223, layout.js:162-171). A field's and a draw's margin is not — both turn it into padding (template.js:1949-1952, 2917-2920), inside a box the template already sized.

Where it runs off the bottom, it turns the page

A form is longer than a sheet, and the page it goes onto next is not simply "another of the same". Which page area comes next is decided by a state machine — the page set's relation, each page area's <occur>, the parity of the page number, and the explicit <breakBefore> and <breakAfter> the template writes — and [pager] follows pdf.js's (template.js:4064-4236, 5418-5657) rather than assuming. Every container of the chain being flowed begins again at the top of the new content area, which is what pdf.js arrives at by re-entering the whole tree with a new space.

A container that would have to be BROKEN in two for its parts to fit is not broken: pdf.js keeps [$extra].children, a generator and a failingNode to do that (layout.js:38-53), and this does not. A container that may be split (Subform[$isSplittable], template.js:4940-4975) has its children distributed across pages instead, which is the same thing where the container itself draws nothing; one that may not — a positioned layout, a row, or anything kept intact — moves whole, and is reported unplaced where it fits no page at all.

What it deliberately does not do, and reports instead

  • lr-tb, and rl-tb, rl-row. The first wraps its children onto lines, which needs their widths and a line-breaking rule; the last two fill from the right, which needs the container's width. Only the first child of an lr-tb is placed, at the container's origin.
  • Text measurement. A field whose template writes no height has no height until its text is measured — and under a stack, neither has anything below it, because where the next child begins is the height of this one.
  • Breaking one container in two across a page boundary, as above.
  • Borders. A child's origin is the inside of its parent's margin, not the inside of its parent's border.

Each of those leaves its elements in Layout.Unplaced with the reason written out. Nothing is dropped: every field and draw of the form's body comes back in one list or the other.

A nil form, or one with no outermost subform, lays out nothing.

func (*Layout) Fields added in v0.5.0

func (l *Layout) Fields() int

Fields counts the placed boxes that are fields rather than static drawing.

type Measure

type Measure float64

A Measure is a length, in points.

XFA writes lengths as a number and a unit — "62mm", "9pt", "0.25in" — and mixes them freely within one form: the corpus's simplest template gives its page in points, its content area's origin in inches and its fields' widths in millimetres, all in the same subform.

func ParseMeasure

func ParseMeasure(s string) (Measure, error)

ParseMeasure reads a length. A bare number is points, which is what the specification says and what the corpus writes for a page's height.

func (Measure) Points

func (m Measure) Points() float64

Points converts to the unit a PDF is drawn in.

type Node

type Node struct {
	// Kind is the element's name, without its namespace: "subform", "field",
	// "draw", "pageArea".
	Kind string
	// Attr are its attributes, by name without namespace.
	Attr map[string]string
	// Text is the character data directly inside it, with surrounding space
	// trimmed. A <text> element's caption lives here.
	Text string
	// Kids are the elements inside it, in order. Order is not decoration: a
	// subform laid out top-to-bottom places its children in it.
	Kids []*Node
}

A Node is one element of a template, with the children it contains.

The tree is kept whole rather than reduced to the elements this package understands today. XFA has some hundreds of element types and a form uses a few dozen; throwing the rest away at parse time would mean re-parsing to add each one, and would lose the ordering that layout depends on.

func ParseDatasets added in v0.2.0

func ParseDatasets(r io.Reader) (*Node, error)

ParseDatasets reads the datasets part of an XFA package — what has been filled in — and returns the data under it.

The tree mirrors the template's names. A form whose root subform is called form1 and whose field is called Number1 keeps its value at <data><form1><Number1>1.00</Number1></form1></data>, which is why the values can be found without laying the form out.

What comes back is the <data> element, not the <datasets> wrapper: the wrapper carries the package's plumbing, and every path into the form starts below it.

func ParseTemplate

func ParseTemplate(r io.Reader) (*Node, error)

ParseTemplate reads the template part of an XFA package.

It is lenient in one direction and strict in the other. Namespaces are dropped, because a template writes the same element under xfa-template and under no namespace at all depending on who produced it, and the difference carries nothing. Processing instructions and comments are skipped: a template written by Adobe's designer carries hundreds of them recording what the designer did, which is not part of the form.

A document whose XML does not close is refused. Half a template is not a form, and laying one out would put half a form on paper without saying so.

func (*Node) Child

func (n *Node) Child(kind string) *Node

Child is the first child of that kind, or nil. Most of the template is singular — a field has one ui, one border, one caption — so looking one up by name is how it is read.

func (*Node) Children

func (n *Node) Children(kind string) []*Node

Children are every child of that kind, in order.

func (*Node) Get

func (n *Node) Get(name string) string

Get returns an attribute, or the empty string.

func (*Node) Measure added in v0.5.0

func (n *Node) Measure(name string) (m Measure, ok bool, err error)

Measure reads one of a node's attributes as a length.

It answers three ways, not two, and the third is the point of it. ok is false when the attribute is not there at all; err is non-nil when it is there and is not a length. XFA's "unspecified" and its "zero" are different things — a field with no width has no width until its text is measured, which is not the same as a field nought wide — and a layout that collapses them draws the second when it meant to report the first.

pdf.js keeps the distinction as the empty string and then loses it in measureToString (html_utils.js:35-41), which turns any string, meant or mistaken, into "0px".

func (*Node) Walk

func (n *Node) Walk(visit func(*Node))

Walk calls visit on the node and everything under it, depth first, in document order.

type Page added in v0.5.0

type Page struct {
	// Width and Height are the sheet, with a landscape medium already
	// swapped. Both are zero when the page area writes no medium, which
	// pdf.js also declines to guess at (template.js:4108).
	Width, Height Measure
	// Areas are the content areas the page offers the body, in order: the
	// boxes the form's body is laid out in, as against the furniture the page
	// area draws around them. Nearly every page area in the wild holds one.
	Areas []Rect
	// Boxes are the elements placed on it, in the order the form places them.
	// The page area's own furniture comes first and is drawn again on every
	// sheet that page area makes; the body follows.
	Boxes []Box
}

A Page is one sheet, with what this package could put on it.

type Rect added in v0.5.0

type Rect struct {
	X, Y, W, H Measure
}

A Rect is a box on the page, in points.

It is measured in XFA's own frame — from the TOP-LEFT corner, with Y increasing downwards — and not in PDF's, which counts up from the bottom left. The flip belongs to whatever draws the page, because it needs the page height to do it and because leaving it here would make every coordinate in this package disagree with the template it was read from.

type Result added in v0.3.0

type Result struct {
	// Fields are the form's value-carrying containers, in the order the form
	// places them.
	Fields []Binding
	// Unsupported are the <bind> expressions that were not followed. Each one
	// leaves its field unbound.
	Unsupported []Unsupported
	// Truncated says binding stopped early because the form produced more
	// containers than this package will hold. It is a defence against a file
	// built to make a reader work forever, not something a real form does.
	Truncated bool
}

A Result is what a form holds once its template and its data are joined.

func Bind added in v0.3.0

func Bind(template, data *Node) *Result

Bind joins a template to the datasets that fill it and returns each of the form's fields with the value bound to it.

How a field finds its value

XFA does not put the value under the field's own name. The template names a field for the layout and the data names it for the record, and the two need not agree — of fourteen dynamic forms measured here, two have the same count of fields and values and not one path in common. What joins them is either an explicit <bind ref="..."> or, far more often, a walk in which each container consumes the next unconsumed data node of its own name. Both are implemented, following Mozilla's pdf.js, which is the only complete free implementation of this.

The <bind> element's match attribute is honoured in all four forms: once (the default), global, dataRef and none.

Which SOM expressions are read

A ref is a SOM expression. These forms are read:

Name.Sub.Leaf      a path from the current data node, walking up to the
                   parent and its parents if the first name is not found
Name[2]            the third sibling of that name
Name[*]            every sibling of that name
$data.Name         rooted at <data>
$record.Name       rooted at the first record under <data>
$.Name             rooted at the current data node
!.data.Name        rooted at <datasets>
Parent..Leaf       Leaf anywhere below Parent
Parent.#field      by element name rather than by name attribute
Name.attr          an attribute reads like a child

These are NOT read, and each one is reported in Result.Unsupported rather than guessed at:

Name.[expr]        a FormCalc subexpression
Name.(expr)        a JavaScript predicate
Name[-1]           a negative index
$template, $form, $layout, $host, $event, $connectionSet, $dataWindow,
$xfa               references outside the data, which name no value

Measured over 560 real templates carrying 26 573 <bind> elements, none of the unsupported forms occurs: every ref is a plain path, a $record path, a $ path, or one of those with [*].

Where this deliberately differs from pdf.js

It does not create data nodes. pdf.js, meeting a ref that matches nothing, invents the nodes the expression describes so that a person typing into the form has somewhere to put the answer. This reads a document rather than editing one, so the field is simply reported unbound — which is the same answer, since an invented node is empty.

It does not repeat a container to satisfy occur's initial count. pdf.js, merging into empty data, clones a subform until there are as many as the template asks for. Those clones carry no data; they change the layout, not the values, and this returns values.

It descends into pageSet and pageArea. pdf.js does not bind their contents at all, because it lays them out separately — but of one real form's 212 fields, every single one sits under a pageArea, and dropping them silently would lose the whole form.

It stops a global search that has begun to repeat. pdf.js's global lookup does not skip nodes it has already taken, so a container with no upper occur bound and match="global" asks for the same node forever; this stops at the repeat.

A nil template gives an empty result; a nil data tree binds nothing, which is what a document nobody has filled in should say.

func (*Result) Values added in v0.3.0

func (r *Result) Values() map[string]string

Values are the bound fields by their form path. Fields that were not bound are left out, so a caller filling a document gets what the data actually says and nothing invented.

A path repeated by two nameless branches keeps the first. Use Result.Fields where that matters; it keeps every one, in order.

type Unplaced added in v0.5.0

type Unplaced struct {
	// Node is the occurrence that was not placed.
	Node *FormNode
	// Kind is "field" or "draw".
	Kind string
	// Path is [FormNode.Path].
	Path string
	// Why says what stopped it, in words fit to show somebody.
	Why string
}

An Unplaced is one element of the form this package did not place, and why.

Every field and draw of the form's BODY is in exactly one of Page.Boxes and Layout.Unplaced. That is the point of the type: a layout that reaches four fifths of a form is useful, and one that silently drops the other fifth is not, because nothing downstream can tell a form that was laid out from a form that was half laid out.

A page area's own furniture is the one exception, and it is not a leak: a letterhead belongs to the sheet rather than to the form, so it is placed once on every sheet that page area makes, and appears in Layout.Unplaced only where its page area is never used at all.

type Unsupported added in v0.3.0

type Unsupported struct {
	// Field is the form path of the container carrying the <bind>.
	Field string
	// Ref is the expression as written.
	Ref string
	// Why names the construct, in words fit to show somebody.
	Why string
}

An Unsupported records a <bind> whose expression this package met and did not follow. It is reported rather than swallowed: a binder that quietly differs from Adobe on one construct is worse than one that says where it stops, because the caller cannot tell a field nobody filled in from a field whose value was not looked for.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL