Take a filled form with two fields: a multi-select list box where the user picked Delphi and PDF, and a multi-line Notes box where somebody typed Delphi on one line and PDF on the next. Read both values back as strings and they are identical, two words separated by a carriage return. Export them to XFDF and they must not be identical. ISO 19444 wants the list box as two <value> elements and the Notes box as one value with a line break inside it, and an exporter that guesses from the text gets one of them wrong. The reliable signal is the MultiSelect flag in the field dictionary
"Form data" in a PDF means at least three unrelated things: the values typed into AcroForm fields, the review comments sitting on the pages, and, in older documents, a complete XFA application stored as XML. Each has its own exchange format, its own encoding rules and its own way of going wrong when the file comes from another tool
FDF, XFDF and XFA carry different data
PDF Library for Delphi keeps those three on separate API families, and every method comes in a file variant and a string variant: ExportFormDataToXFDF and ImportFormDataFromXFDF (plus the FDF pair) for field values, ExportAnnotationsToXFDF and ImportAnnotationsFromXFDF (plus the FDF pair) for comments, and SetXFAFromString with GetXFAToString for the XFA packet. The list-box case above is settled inside ExportFormDataToXFDF, which checks the MultiSelect flag of each choice field before deciding how many <value> elements to write
FDF and XFDF describe the same information in two syntaxes, and XFA belongs to a different world entirely. FDF (ISO 32000-2 §12.7.8) is a miniature PDF file: a /Fields array of << /T (name) /V (value) >> dictionaries whose strings follow the PDF literal-string rules, including backslash escapes and three-digit octal codes for non-printable bytes (§7.3.4.2). XFDF (ISO 19444) is the XML version, a <fields> tree that most form back ends already know how to produce. XFA is an XML Forms Architecture template plus its data, bundled as an XML Data Package (XDP) and referenced from /AcroForm/XFA. It is not a field-value format at all
Inside FDF and XFDF there is a second split. The form-data methods read and write the field tree and nothing else. The annotation methods read and write the page /Annots arrays, which is what Acrobat calls Export Comments. On export the annotation family skips Widget annotations, since those are the visible faces of form fields and already travel with the field values. So exporting fields never sweeps up a reviewer's sticky notes, and importing comments never touches a value the user typed. What a field does when it is clicked or recalculated is yet another layer, covered in the note on interactive form actions and JavaScript
For anything that crosses a system boundary, XFDF is the safer choice. The FDF writer produces the compact byte-string form, with every value escaped as a PDF literal, and the FDF reader picks up /V entries written as literal strings. XFDF is UTF-8 end to end, expresses multiple selections as repeated elements, and carries rich text and the fuller set of comment attributes. FDF remains a good fit when both ends are your own code and the values are plain text
How do you fill a PDF form from XFDF in Delphi?
Load the document, call one import method, check the count, save. ImportFormDataFromXFDF reads the file as UTF-8, walks the <field> elements, matches each one to an existing AcroForm field by its fully qualified name, and returns how many fields it actually set. A name the form does not define is skipped, which is deliberate: a data file from a case-management system, or one somebody edited by hand, should never be able to add fields to a form you designed
var
Lib: TPDFlib;
FieldsSet: Integer;
begin
Lib := TPDFlib.Create;
try
if Lib.LoadFromFile('application-blank.pdf', '') <> 1 then
raise Exception.Create('Cannot open the blank application form');
if Lib.FormFieldCount = 0 then
raise Exception.Create('This PDF has no AcroForm fields to fill');
// XFDF exported by the case-management system, UTF-8 on disk
FieldsSet := Lib.ImportFormDataFromXFDF('applicant-1042.xfdf');
if FieldsSet = 0 then
raise Exception.Create('No XFDF field name matched this form');
if Lib.SaveToFile('application-filled.pdf') <> 1 then
raise Exception.CreateFmt('Save failed, error %d', [Lib.LastErrorCode]);
finally
Lib.Free;
end;
end;
The two checks around the import are there because a return value of 0 has two causes. The document may have no AcroForm, in which case the importer has nowhere to write. Or every name in the XFDF may be spelled differently from the PDF, for example because the sending system flattened Applicant.FullName into FullName. Testing FormFieldCount first separates the two, and only the second is worth keeping the XFDF file around to diagnose
Encoding is the other place values go wrong. The file-based methods read and write XFDF as UTF-8, which is what the XML declaration promises and what an accented surname, a currency sign or a CJK address needs. If you generate XFDF yourself, declare UTF-8 and actually write UTF-8 bytes; a Windows-1252 file with a UTF-8 header turns every non-ASCII character into garbage before the library ever sees it. The export side behaves symmetrically: ExportFormDataToXFDF returns 1 after writing the file, and returns 0 without creating a file when the document has no form fields to export
Hierarchy, multi-select and rich text in XFDF
Nested field names are where hand-rolled exporters break first. AcroForm addresses a child field by a dotted full title such as Applicant.FullName. ISO 19444 nests the same thing as <field name="Applicant"><field name="FullName">. The XFDF exporter in PDF Library for Delphi splits the dotted title into nested elements, and the importer joins nested names back into the dotted title, so a file you export can be imported again without renaming anything. Parent nodes are skipped on export because an AcroForm parent only contributes a level of the name; writing it out would add an empty value that matches nothing on the form
Multi-select is the case from the opening. A list box with the MultiSelect flag set (bit 22 of the choice-field flags, ISO 32000-1 Table 230) holds several selections at once, and the export writes one <value> per selection. On import, repeated values are combined into a multi-selection only when the target field really is a multi-select list box; for any other field the first value is used. A multi-line text field therefore keeps its line breaks on export and never gets split into fake selections
Rich text is the third trap. A formatted text field keeps its markup in the RV entry as XHTML, and XFDF carries it inside <value-richtext>. The exporter writes that markup as live XML, not as escaped text, so the receiving tool sees a <b> element instead of the literal characters <b>. On import the raw markup goes into RV while the plain <value> goes into V. If a field arrives with rich text and no plain value, the text content of the markup becomes V, so viewers that ignore RV still show something sensible
var
Lib: TPDFlib;
Applied: Integer;
const
XFDF =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">' +
'<fields>' +
' <field name="Applicant">' +
' <field name="FullName"><value>Alice Example</value></field>' +
' </field>' +
' <field name="Skills">' +
' <value>Delphi</value><value>PDF</value>' +
' </field>' +
' <field name="Notes">' +
' <value>See attachment</value>' +
' <value-richtext><body><p>See <b>attachment</b></p></body></value-richtext>' +
' </field>' +
'</fields></xfdf>';
begin
Lib := TPDFlib.Create;
try
Lib.LoadFromFile('intake.pdf', '');
// Applicant.FullName is rebuilt from the nested elements;
// Skills keeps both selections only if it is a multi-select list box;
// Notes gets V from <value> and RV from <value-richtext>
Applied := Lib.ImportFormDataFromXFDFString(XFDF);
// Applied is 3 when all three names exist on intake.pdf
Lib.SaveToFile('intake-filled.pdf');
finally
Lib.Free;
end;
end;
When the rich text exists to carry document structure for screen readers, the formatting alone will not do that job. Reading order and structure belong in the tag tree, as described in the note on tagged PDF and accessibility structure
Why do imported comments show up twice?
Because comment import always adds. ImportAnnotationsFromXFDF creates a new annotation for every recognised element and appends it to the page; it does not search the page for an existing comment with the same name or position. Run the same merge job twice against one file and every sticky note appears twice. That is the behaviour you want when several reviewers send separate XFDF files for one master copy, and the wrong one when a scheduled job retries after a timeout
The XFDF comment path carries the attributes that survive a round trip cleanly: the subtype element (text, highlight, square, stamp, freetext and the other standard markup names), the rectangle, the 0-based page index, author, subject, name, creation and modification dates, flags, opacity, border width, style and dashes, colour as an #RRGGBB attribute mapped to the DeviceRGB /C triple, and plain-text contents. The importer accepts known element names only. An entry with no usable rectangle, or a page index beyond the target document's page count, is skipped and not counted. Highlight quadpoints, ink paths, polygon vertices, rich-text contents (RC), popups and custom appearance streams stay with the source document, so highlight geometry and branded stamps need a different route
A retry-safe merge needs a guard of its own. The code below counts the non-widget annotations already on the destination and refuses to import into a copy that has some. Pages are matched by index, so the clean copy has to have the same page order as the reviewed file
// CountComments is a helper you add yourself; it is not part of the library
function CountComments(Lib: TPDFlib): Integer;
var
Page, Annot: Integer;
begin
Result := 0;
for Page := 1 to Lib.PageCount do
begin
Lib.SelectPage(Page);
for Annot := 1 to Lib.AnnotationCount do
if Lib.GetAnnotType(Annot) <> 'Widget' then
Inc(Result);
end;
end;
var
Src, Dest: TPDFlib;
Xfdf: WideString;
Added: Integer;
begin
Src := TPDFlib.Create;
Dest := TPDFlib.Create;
try
Src.LoadFromFile('reviewed.pdf', '');
Xfdf := Src.ExportAnnotationsToXFDFString; // <annots> only, widgets skipped
Dest.LoadFromFile('clean-copy.pdf', '');
if CountComments(Dest) > 0 then
Exit; // already merged once; do not double up
Added := Dest.ImportAnnotationsFromXFDFString(Xfdf);
if Added > 0 then
Dest.SaveToFile('clean-copy-commented.pdf');
finally
Dest.Free;
Src.Free;
end;
end;
Compare Added with the number of elements in the XFDF if you need to know whether anything was dropped for a bad page index. To see exactly what landed and where, walk the page annotations or the wider element tree described in text search and page element enumeration
Writing a full XFA XDP packet with SetXFAFromString
XFA is the outlier, and SetXFAFromString writes the whole packet in one call. It takes a complete XML Data Package, the <xdp:xdp> document with its template and datasets, stores it as a stream, and points /AcroForm/XFA at it. Any XFA entries the form already had are removed first, so the call replaces rather than merges. When the document has no AcroForm yet, the library creates one; you do not need a throwaway field just to give the packet a home. The file version is raised to PDF 1.5 if it is lower, because /XFA requires it. In PDF/X mode the method returns 0 and leaves the document alone, because PDF/X files are meant for print exchange rather than interactive filling
Encoding is less predictable here than in XFDF. XDP packets from some form designers arrive as UTF-16, with or without a byte-order mark. When the library parses the stored packet it checks for a UTF-16 little-endian or big-endian BOM, and for the < character encoded as two bytes, before falling back to UTF-8. Per-field access then goes through Scripting Object Model paths: GetXFAFormFieldValue and SetXFAFormFieldValue accept form1.FullName, $data.form1.FullName and xfa.datasets.data.form1.FullName as the same data node, and the template side accepts $template and xfa.template prefixes. Generators that always emit fully qualified paths work without string surgery
var
Lib: TPDFlib;
const
Xdp =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">' +
' <template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">' +
' <subform name="form1">' +
' <field name="FullName"><ui><textEdit/></ui></field>' +
' </subform>' +
' </template>' +
' <xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">' +
' <xfa:data><form1><FullName>Alice Example</FullName></form1></xfa:data>' +
' </xfa:datasets>' +
'</xdp:xdp>';
begin
Lib := TPDFlib.Create;
try
if Lib.SetXFAFromString(Xdp, 0) <> 1 then
Exit; // 0 in PDF/X mode
// same data node, two spellings of the SOM path
if Lib.GetXFAFormFieldValue('xfa.datasets.data.form1.FullName') = 'Alice Example' then
Lib.SetXFAFormFieldValue('form1.FullName', 'Bob Example');
Lib.SaveToFile('xfa-packet.pdf');
finally
Lib.Free;
end;
end;
ISO 32000-2 deprecates XFA, and we would not start a new form on it. Where XFA earns its place is in maintaining forms that were designed in XFA years ago and are still filled by systems you cannot change; for anything new, an AcroForm with XFDF exchange is simpler to produce, easier to validate and readable by far more software. The SOM path rules, including indexed and relative paths, are covered in more depth in the note on XFA SOM path expressions
Picking the method for the job
Field values that leave your application go out through ExportFormDataToXFDF and come back through ImportFormDataFromXFDF, with the count checked against FormFieldCount. Reviewer comments use the annotation pair, behind a guard if the merge can ever run twice. An XFA form gets its packet through SetXFAFromString and its values through SOM paths. The full parameter lists for every import and export method, including the string variants used above, are in the reference for losLab PDF Library for Delphi and C++Builder