A gray square annotation whose /C array is [0.5] goes out to an XFDF file and comes back as [0.502 0.502 0.502]: three components where there was one, each a couple of thousandths off. That is the format working as designed. XFDF stores every color as an 8-bit #RRGGBB string, keeps polygon points in a child element, counts pages from zero and gives an importer no choice but to drop any element that lacks a page or a bounding box, and each of those conventions decides what survives a review round trip and what you can sensibly diff afterward
FDF or XFDF: which file to hand another tool
Both formats carry the same review payload, form field values in a <fields> tree and comments in an <annots> tree, so the choice comes down to who has to read the file. FDF is the Forms Data Format defined inside the PDF specification; it uses PDF object syntax, which means the receiving side needs a PDF-aware parser just to find the comments. XFDF is the XML expression of the same data, standardized on its own as ISO 19444-1, and any XML library on any platform can open it, generate it or run it through a text diff. For a web service, a Java review server or a build script, XFDF is the one to send
HotPDF splits the two trees across separate calls on the loaded document. Form values go through ExportLoadedFormToXFDF and ImportLoadedFormFromXFDF, which follow the field rules of ISO 19444-1 clause 6.3. Comments go through ExportLoadedAnnotationsToXFDF and ImportLoadedAnnotationsFromXFDF, the pair this article covers. Neither annotation call rewrites the content streams of the pages the comments sit on. Export only reads the document, and import adds entries to each page's annotation list
Exporting annotations from a loaded PDF
THotPDF.ExportLoadedAnnotationsToXFDF walks every page of the loaded document, writes one XFDF element per supported annotation and returns how many it wrote. When that count is zero, the function returns before it creates the target file at all. The consequence catches people in batch jobs: a comments.xfdf left over from yesterday's run stays on disk, and the next step happily uploads stale comments. Delete the target first, or treat the return value as the only proof that a fresh file exists
var
Pdf: THotPDF;
Written: Integer;
begin
// A zero result creates no file, so clear the previous run's output first
if FileExists('comments.xfdf') then
DeleteFile('comments.xfdf');
Pdf := THotPDF.Create(nil);
try
if Pdf.LoadFromFile('report-reviewed.pdf') > 0 then
begin
Written := Pdf.ExportLoadedAnnotationsToXFDF('comments.xfdf');
if Written <= 0 then
ShowMessage('No supported annotations to export');
end;
finally
Pdf.Free;
end;
end;
The output is plain UTF-8 XML: an <xfdf> root in the http://ns.adobe.com/xfdf/ namespace with xml:space="preserve", one <annots> container, and one child per annotation. Every child carries a zero-based page index and a rect with the annotation's bounding box in PDF user space. Plain comment text shows up twice, as a contents attribute and as a <contents> child element (ISO 19444-1 §6.5.4), so a consumer that looks in either place finds it. A red line with a yellow arrowhead fill next to a light-blue polygon comes out like this
<?xml version="1.0" encoding="UTF-8"?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
<annots>
<line page="0" rect="66,694,226,706" contents="Baseline looks off"
color="#FF0000" interior-color="#FFFF00"
start="72,700" end="220,700" head="OpenArrow" tail="None">
<contents>Baseline looks off</contents>
</line>
<polygon page="0" rect="72,120,180,200"
color="#0000FF" interior-color="#CCE5FF">
<vertices>72,120;180,120;180,200;72,200</vertices>
</polygon>
</annots>
</xfdf>
Export can also stop with an exception, and that is deliberate. A link annotation round-trips when its action is URI, Named, GoTo or GoToR. A link that runs JavaScript, launches a file or chains several actions through /Next has no faithful XFDF form in this mapping, so ExportLoadedAnnotationsToXFDF raises EArgumentException instead of writing a link that would do something different on the far side. Refusing is the right default here. A comment file that quietly turns a scripted link into a dead rectangle is worse than an error you can catch and log
How do annotation subtypes map to XFDF elements?
Each subtype follows the element and geometry convention ISO 19444-1 assigns to it. Eighteen subtypes have a mapping: text notes, free text, line, square, circle, polygon, polyline, the four text markups (highlight, underline, strikeout, squiggly), stamp, ink, caret, file attachment, sound, redaction and link. Anything outside that set, a 3D or widget annotation for instance, is skipped on export and does not count toward the returned total. Popup windows are not exported as standalone entries; they ride along as a <popup> child of the markup annotation that owns them, with their own rect and open state
- Line: the
/Lendpoints becomestartandendattributes,/LEbecomesheadandtail, and leader lines and caption placement get their own attributes - Polygon and polyline:
/Verticesmoves into a<vertices>child asx,ypairs separated by semicolons - Ink:
/InkListbecomes an<inklist>with one<gesture>per stroke, so a three-stroke signature comes back as three strokes - Highlight, underline, strikeout and squiggly:
/QuadPointsbecomes acoordsattribute, eight numbers per marked span of text - Square, circle and caret: the
/RDinset becomesfringe - Text notes: the
openflag plus the reviewstateandstatemodel, so an "Accepted" or "Rejected" mark survives the trip - Border:
width,dashesandstyle, withstyle="cloudy"andintensitystanding in for the cloudy border effect
Color is where the format itself costs you precision, which brings back the gray square from the opening. XFDF has exactly one color syntax, #RRGGBB. A one-component gray /C is replicated across red, green and blue, so [0.5] becomes #808080, and on import the hex digits turn into three numbers of 128/255 each, about 0.502. A four-component CMYK color is converted to RGB on the way out. If your own test compares annotation dictionaries before and after a round trip, compare colors as 8-bit hex values. Comparing the raw arrays will fail on gray and CMYK input every time, even though the comment looks identical on screen
Why does an import add fewer annotations than the file contains?
THotPDF.ImportLoadedAnnotationsFromXFDF parses the file, creates one annotation per element it can place and returns that count. An element is skipped when its name is not one of the eighteen subtypes, when it has no page attribute or a negative one, or when its rect holds fewer than four numbers. That last rule is the usual reason a hand-written or script-generated XFDF imports nothing. Generators that only emit geometry, a start and end or a <vertices> list, leave out rect because the shape seems to define itself. ISO 19444-1 treats rect as required, so emit it from your generator rather than expecting the reader to infer one
Two further cases end in an exception rather than a short count. A stamp whose <appearance> element contains anything except base64 text, or a link with an action outside URI, Named, GoTo and GoToR, raises EArgumentException. And when the PDF was opened with a user password whose permissions clear the "modify annotations" bit (bit 6 of the /P entry, ISO 32000-1 Table 22), the import raises EInvalidOpException. In every one of these cases the call runs as a single transaction: annotations created before the failure are rolled back, and the loaded document is exactly what it was before the call. A missing file or input with no XML element in it simply returns zero
var
Pdf: THotPDF;
Added: Integer;
UserPassword: AnsiString;
begin
UserPassword := 'reviewer';
Added := 0;
Pdf := THotPDF.Create(nil);
try
if Pdf.LoadFromFile('report.pdf', UserPassword) > 0 then
begin
try
Added := Pdf.ImportLoadedAnnotationsFromXFDF('comments.xfdf');
except
on E: EInvalidOpException do
// Permissions or an existing signature policy refuse annotation changes; nothing was added
ShowMessage('Not allowed: ' + E.Message);
on E: EArgumentException do
// A stamp or link element could not be read; nothing was added
ShowMessage('Rejected XFDF: ' + E.Message);
end;
if Added > 0 then
Pdf.SaveLoadedDocument('report-annotated.pdf');
end;
finally
Pdf.Free;
end;
end;
The imported annotations live only in memory until SaveLoadedDocument writes them out, which is why the save sits behind the count check. If you build or edit annotation objects directly in code rather than exchanging them as files, the article on how HotPDF creates and edits PDF annotation objects from Delphi covers that side of the API
Merging several reviewers without doubling the markup
Import never checks whether an equivalent annotation already exists on the page. Every element produces a new annotation, and that is the behavior you want when two reviewers drop similar notes on the same paragraph. It also means the classic mistake doubles everything: someone exports the comments from report-reviewed.pdf, edits the XFDF, then imports it back into report-reviewed.pdf instead of the clean original. Every untouched comment now appears twice. Merge onto the unannotated base file, every time
var
Pdf: THotPDF;
Total, I: Integer;
Files: array[0..1] of string;
begin
Files[0] := 'alice-comments.xfdf';
Files[1] := 'bob-comments.xfdf';
Total := 0;
Pdf := THotPDF.Create(nil);
try
// Start from the clean base, never from a copy that already holds comments
if Pdf.LoadFromFile('master.pdf') > 0 then
begin
for I := Low(Files) to High(Files) do
Inc(Total, Pdf.ImportLoadedAnnotationsFromXFDF(Files[I]));
if Total > 0 then
Pdf.SaveLoadedDocument('master-merged.pdf');
end;
finally
Pdf.Free;
end;
end;
Because each element names its own page, the order of the files does not matter for placement. Reply threads behave differently. An element with an inreplyto attribute is linked to its parent through the parent's name, and that lookup runs over the annotations created by the same import call. A reply Bob wrote to one of Alice's notes, delivered in Bob's own file, therefore lands as a standalone note at the right spot. If threading matters to your reviewers, have the review tool export the whole conversation into one file, or concatenate the <annots> children of both files into a single XFDF before importing it
Text, rich text and the characters in between
Comment text is where hand-rolled XFDF writers break most often, and the cause is usually on the PDF side. Annotation text in a PDF is a text string under ISO 32000-1 §7.9.2.2: UTF-16BE with a byte order mark, or PDFDocEncoding without one. A writer that guesses UTF-8 for any byte run that happens to be valid UTF-8 gets this wrong in a sneaky way. The bytes C3 A9 in PDFDocEncoding are the two characters "é", and turning them into "é" changes what the author typed. HotPDF decodes annotation strings by their PDF syntax, the byte order mark and the PDFDocEncoding table, then writes the result as UTF-8
On the XML side, text and attribute values are escaped per ISO 19444-1 §5.8.2. Ampersands, angle brackets and quotes become entities, line feeds, carriage returns and tabs become character references, and other control bytes become PDF-style octal escapes such as \007. Import reverses exactly those escapes and leaves any other backslash alone, so a Windows path pasted into a note comes back intact. The parser is built into the library with no MSXML or other external XML dependency, which keeps the same code path on every Delphi and C++Builder version HotPDF supports
Rich text gets its own element. A note's styled body from the /RC entry is written as XHTML inside <contents-richtext>, and import reads it back with text and child elements in document order, so <b>Total</b> is off by one row keeps both the bold word and the plain tail. What XFDF does not carry for a note is a rendered appearance, so the receiving application lays out the popup with its own fonts. Count on the words and their styling arriving intact; the exact on-screen layout is up to the viewer. Stamps are the exception, since their appearance travels base64-encoded in an <appearance> element. Styled content in XFA form data follows different rules, covered in how HotPDF handles XFA exData, rich text and hyperlinks
A typical review cycle chains several loaded-document calls: import the reviewer's XFDF onto the clean base, edit the document metadata to record the review round, save, then export a fresh XFDF for the next reviewer. The annotation and form-data XFDF functions are both part of the HotPDF Delphi Component for Delphi and C++Builder, and its reference lists the per-subtype attributes in full