An empty Comments box on an XFA claim form reopens holding one line feed. Save and reopen it again and the box holds two. A customer name typed with U+1F642, the slightly smiling face, comes back as U+F642, a private-use code point that most fonts draw as an empty rectangle. All three effects live in the XML that an XFA save writes into the datasets packet, and a save path that gets them right has to keep layout whitespace out of field values, carry supplementary-plane characters as complete surrogate pairs, and report a failed write through the save result instead of through a damaged file
Which PDFium runtime saves XFA values?
Only pdfium.v8.dll saves XFA values, because it is the only PDFium Component build that carries both the V8 JavaScript engine and the XFA form runtime. Once an edit is committed (the field lost focus, or ClearFormFieldFocus forced the commit), that runtime exports the live XFA data into the datasets packet on save, with no packet editing in your code. Each Windows architecture also ships pdfium.dll, built without V8 and XFA, which writes the stored packets back exactly as it read them. What happens to a value written while the field still has focus is covered in why XFA field edits vanish on save
The Delphi wrapper tries to pick the right library for you. When EnableV8Engine is still False and no PDFium library has been loaded yet, TPdf looks at the file it is about to open, and if it finds XFA markers (an /XFA entry in the AcroForm dictionary, or /NeedsRendering true in the catalogue) it switches EnableV8Engine on before loading. That switch only works once per process. If an ordinary pdfium.dll is already resident because the first document of the session was a plain PDF, the process stays committed to it, and TPdf.OnXfaRuntimeMissing fires when an XFA document arrives later
The default search order is the other half of the problem. Without a directory in LibraryName, the loader starts with a DLLs\Win32 or DLLs\Win64 folder under the application folder or one of its parents, so an older pdfium.v8.dll may be found first. A LibraryName that contains a directory pins exactly that file, and if it is missing, loading fails
uses
System.SysUtils, PDFium;
procedure SelectXfaRuntime;
begin
// A directory in LibraryName pins this exact file;
// a missing file makes LoadLibrary fail instead of searching elsewhere
{$IFDEF WIN64}
PDFium.LibraryName := ExtractFilePath(ParamStr(0)) + 'DLLs\Win64\pdfium.v8.dll';
{$ELSE}
PDFium.LibraryName := ExtractFilePath(ParamStr(0)) + 'DLLs\Win32\pdfium.v8.dll';
{$ENDIF}
PDFium.EnableV8Engine := True;
PDFium.LoadLibrary; // fail at startup, not at the first XFA save
end;
After a document is open, TPdf.XFA says the file contains XFA, and TPdf.XfaRuntimeAvailable says the loaded library could actually start the XFA engine for this document. Static and dynamic forms are told apart through TPdf.FormType, which returns ftXfaFull for a dynamic form and ftXfaForeground for a static one. Packet-level probing on a machine without the V8 runtime is the subject of detecting XFA forms and extracting XFA packets in Delphi
Why can saved XFA fields gain extra line feeds?
Saved XFA fields gain line feeds when the writer pretty-prints its XML with a newline after each start tag. Two writers are involved in an XFA save, the generic XML element writer and the form packet serializer, and both habitually format output that way. In most XML documents that whitespace is cosmetic. In XFA data it is the value: when the datasets packet is parsed again, every character between <Comments> and </Comments> belongs to the field, newline included
An empty field therefore reopens holding a single LF. Each further save formats around the LF already there, so a field nobody touched grows by one line per round of review
Trimming values on load looks like a cheap repair, and it would corrupt real data. People type leading spaces, trailing spaces and deliberate line breaks into XFA fields; an address block must keep its line structure, and a fixed-width reference code must survive byte for byte. The XFA writers in PDFium Component instead drop only the whitespace that the serializer itself synthesises around tags. User values, text nodes that were already in the file and CDATA sections pass through unchanged, so " indented" stays indented and an intentionally empty field stays empty
Emoji, surrogate pairs and a 16-bit wchar_t
An emoji comes back as a different character when a decoding path stores a full Unicode scalar value in a single wchar_t, which on Windows is 16 bits wide. Two places in an XFA load are exposed to this: the UTF-8 stream decoder, and the parser for numeric character references such as 🙂. U+1F642 needs 17 bits. Squeeze it into 16 and the top bit falls away, leaving U+F642 in the Private Use Area
A form serializer can fail in the opposite direction. Filtering characters one wchar_t at a time, it sees two surrogate code units, D83D and DE42, each of which is invalid on its own, and drops both. The emoji disappears from the form packet, with no replacement character left behind
In PDFium Component the decoder consumes each scalar value completely and emits a proper surrogate pair, including when the output buffer has room for only one more unit and when a four-byte UTF-8 sequence is split across two read blocks. On the way out, the form exporter keeps valid surrogate pairs together, and numeric character references decode to correct pairs too
Latin-1 test data never touches any of these paths. A round-trip test for an XFA form needs at least one character above U+FFFF in a text field, and checking the saved bytes for the four-byte UTF-8 sequence F0 9F 99 82 is more telling than looking at the rendered field
Single-stream XFA and the save result
A single-stream XFA document keeps its edits only if the save path can rewrite one XDP stream in place, and any input it cannot rewrite has to fail the save. ISO 32000-1 §12.7.8 allows the /XFA entry of the interactive form dictionary to be either an array that alternates packet names and streams or a single stream holding the whole XDP document. A save path written only for arrays turns single streams down, and if the caller ignores that result, the PDF is written with the form data at its old values
The V8 runtime in PDFium Component handles a defined single-stream subset in three steps. It exports both live packets, datasets and form, into a staging area and validates them. Only then does it replace the matching packets inside the original XDP, keeping the other packets and the root namespace declarations. If staging fails, the persistent XFA stream is never touched and the document keeps its modification mark, so a later save can try again
XML comments and processing instructions need extra care, because the parser used for the rewrite drops them. Each one is swapped for a unique marker before parsing and put back afterward, and the stream is written only if every marker appears exactly once, so comments outside the live packets keep their text and order
Some inputs are refused outright, and each refusal reaches you as a failed save:
- Comments or processing instructions inside the live
datasetsorformpackets, since there is no way to map their original positions into freshly exported content - DTD declarations and XMLDSig signatures, since rewriting the XDP cannot keep an XML signature valid
- Invalid UTF-8 or UTF-16, incomplete tags, invalid character references, unknown entities and malformed processing instructions, which are rejected instead of repaired on the fly
Refusing is the better trade here. A save that returns False can be retried, logged or handed to a person, while an XDP that was quietly normalised might break a signature or a downstream importer weeks later, far from the code that changed it. What the single-stream path does preserve is the XML content model, written as UTF-8; the original byte layout and the encoding declaration of the source stream are not carried over
The last buffered block
The final trap sits below XFA, in the generic PDF writer. A file writer that buffers output in fixed-size blocks has to push out the last partial block at the end. If that happens in cleanup code after the document writer has already reported success, a full disk or an I/O error on the last block never reaches the caller, and the file on disk is short. In both PDFium Component runtimes the final flush is part of the save result, and the XFA modification mark is cleared only after the write really succeeded
The Delphi side adds one more layer. TPdf.SaveAs writes into a temporary file next to the target and moves it over the target only when the stream save returns True. A False result leaves the previous file exactly as it was, and a failure of the final replace raises an OS error instead of returning quietly
Why does a dynamic XFA form reopen with fewer pages?
A dynamic XFA form reopens with fewer pages when its root subform does not declare restoreState="auto", and that decision belongs to the form author. In XFA 3.3, restoreState on the root subform defaults to manual. Under manual, the XFA processor restores only limited state from the saved form packet and leaves the rest to the form's own scripts. Field values and the instance counts of repeating subforms come back; geometric properties set at run time do not
Suppose a three-page form whose script grows a subform to h="450pt" while the user fills it in. The saved form packet holds the new height, the field values and the instance counts. On reopen, the layout is rebuilt from the template heights, the subform shrinks back, and the content reflows onto two pages. That is the behaviour the XFA specification asks for when the template never requested automatic restoration. Declaring it on the root subform changes the reopen:
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form1" layout="tb" restoreState="auto">
<pageSet>
<pageArea name="Page1">
<contentArea x="0.25in" y="0.25in" w="8in" h="10.5in"/>
<medium stock="letter"/>
</pageArea>
</pageSet>
<subform name="Details" layout="tb" w="7.5in">
<!-- fields; scripts may change h or add instances at run time -->
</subform>
</subform>
</template>
If you do not own the template, leave it alone: a form built for manual mode expects its own initialization scripts to rebuild state, and switching the mode underneath them changes what those scripts were written around. Live repagination while the user types is a different mechanism, described in how PDFium Component tracks dynamic XFA page counts and moved fields
Checking an XFA round trip from Delphi
An XFA save is verified by reopening the saved file in a fresh TPdf instance and reading the stored data back, since a True from SaveAs only says the file was written. TPdf.GetXfaDatasets returns the datasets packet as it is stored in the document, not the live data model, so reading it before the save shows the values from the last load. After a reopen it shows exactly what was written. A single-stream document has no separately named packets: PDFium reports the whole XDP as one packet with an empty name, so GetXfaPacketByName('datasets') and GetXfaDatasets both return an empty array, and the code below falls back to the complete stream from GetXfaFormPackets
uses
System.SysUtils, PDFium, FPdfXfa;
function ReadSavedXfaData(const FileName: string): string;
var
Pdf: TPdf;
Packets: TXfaPacketList;
Bytes: TBytes;
begin
Pdf := TPdf.Create(nil);
try
Pdf.FileName := FileName;
Pdf.Active := True;
Bytes := Pdf.GetXfaDatasets; // packet-array layout
if Length(Bytes) = 0 then
begin
Packets := Pdf.GetXfaFormPackets; // single stream: one unnamed packet
if Length(Packets) = 1 then
begin
SetLength(Bytes, Length(Packets[0].Content));
if Length(Bytes) > 0 then
Move(Packets[0].Content[0], Bytes[0], Length(Bytes));
end;
end;
Result := TEncoding.UTF8.GetString(Bytes); // saved XDP output is UTF-8
finally
Pdf.Free;
end;
end;
The save routine commits the pending edit, checks the SaveAs result and compares the reopened value. TPdf.ClearFormFieldFocus removes form focus, which is when PDFium commits the edit buffer of the focused field. TPdf.SetFocusedFormFieldText can fill the focused field from code, but it relies on focus tracked through widget annotations, which a dynamic XFA page usually lacks; there it returns False, and text normally arrives through keyboard input in TPdfView
// XmlText is a helper you add yourself; it is not part of PDFium Component
function XmlText(const S: string): string;
begin
Result := StringReplace(S, '&', '&', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
end;
procedure SaveXfaAndVerify(Pdf: TPdf; const FileName, FieldTag,
Expected: string);
var
Saved: string;
begin
// Optional scripted fill; False means no tracked field has focus
if (Pdf.FocusedFormFieldIndex >= 0) and
not Pdf.SetFocusedFormFieldText(Expected) then
raise EPdfError.Create('Could not write the focused field');
Pdf.ClearFormFieldFocus; // commit the edit buffer
if not Pdf.SaveAs(FileName) then // False: previous file left in place
raise EPdfError.CreateFmt('Saving %s failed', [FileName]);
// Reopen in a fresh TPdf and look for the exact element text
Saved := ReadSavedXfaData(FileName);
if Pos('<' + FieldTag + '>' + XmlText(Expected) + '</' + FieldTag + '>',
Saved) = 0 then
raise EPdfError.CreateFmt('%s did not survive the round trip', [FieldTag]);
end;
The substring test is only a smoke test. An empty element may be written as <Tag/>, data elements can carry attributes, and escaping beyond & and < is up to the serializer, so production checks belong in a real XML parser. Run the routine twice in a row with the same input, because newline drift only shows its full shape in the second generation
Host applications that drive the XFA runtime directly also need the callback layout it expects, which is the topic of FPDF_FORMFILLINFO version 2 and the XFA ABI in Delphi. Both Windows runtimes for Win32 and Win64, the Delphi and C++Builder wrapper and the TPdfView viewer control come with PDFium Component for Delphi and C++Builder