A highlight annotation that FPDFPage_CreateAnnot returned a moment ago reports FPDFAnnot_CountAttachmentPoints = 0, and FPDFAnnot_SetAttachmentPoints(Annot, 0, Quad) returns 0 against it whatever coordinates you pass. The coordinates are not the problem. Index 0 means "replace existing quad number 0", a new annotation has no quads at all, and the call that creates a slot is FPDFAnnot_AppendAttachmentPoints
That fits in one paragraph, yet it is easy to lose hours on, because the natural reaction to a false return is to distrust the geometry. People transpose the corners, flip the Y axis, convert to device space and back. None of that changes the result. What follows covers what the quads must contain according to ISO 32000-1, how to write them through the component API and through the raw C functions, multi-line selections, and an indexing trap that differs between Delphi, Free Pascal and C++Builder. It is the creation-side companion to the article on reading and reviewing existing annotations, which walks the same structures in the other direction
What QuadPoints mean in ISO 32000-1 §12.5.6.10
QuadPoints is a required entry on the four text markup subtypes, Highlight, Underline, Squiggly and StrikeOut: an array of 8×n numbers giving n quadrilaterals in default user space, where each quadrilateral encompasses a word or a group of contiguous words in the text under the annotation. The annotation still carries a Rect, which every annotation needs, but for markup subtypes the quads say which glyphs are marked and Rect only bounds them. Quadrilaterals are used instead of rectangles because text can be rotated or sheared on the page, so each corner is stored as an independent point: x1 y1 x2 y2 x3 y3 x4 y4
The corner order is where the specification text and the files in circulation part ways. §12.5.6.10 says the four vertices are given in counterclockwise order, and adds that the text is oriented with respect to the edge from (x1, y1) to (x2, y2). Acrobat, and the long line of tools built to read what Acrobat writes, use a Z pattern instead: point 1 top-left, point 2 top-right, point 3 bottom-left, point 4 bottom-right. That layout still honors the orientation sentence, since the 1–2 edge runs along the top of the text, but it is not a counterclockwise walk around the shape. Write the Z order. A literal counterclockwise list (top-left, bottom-left, bottom-right, top-right) is defensible on paper, but a reader that walks the points as a Z gets top-left, bottom-left, top-right, bottom-right, and those edges cross into a bow tie
All coordinates are page coordinates in points, origin at the bottom-left of the page, Y growing upward. A line of text near the top of an A4 page therefore has Y values around 700 to 800, and its top edge has the larger Y. The specification also gives an appearance stream (AP) precedence over QuadPoints when both are present, so the quads matter most for viewers that generate the markup themselves
Why does FPDFAnnot_SetAttachmentPoints return false?
FPDFAnnot_SetAttachmentPoints returns false on a new annotation because it only replaces a quad that already exists. The PDFium header states the contract directly: the quad_index "needs to be within the result of FPDFAnnot_CountAttachmentPoints()". Every annotation made by FPDFPage_CreateAnnot starts with a count of zero, so there is no index 0 to replace. FPDFAnnot_AppendAttachmentPoints adds a slot and grows the count by one; after that, index 0 exists and Set will accept it. Both functions are marked experimental in the PDFium headers, and both also widen the bounding box of an existing appearance stream when the new quad reaches further than the old one
The PDFium Component surfaces all FPDFAnnot_* entry points in PDFium.pas, and the FS_QUADPOINTSF record and the size_t alias live in FPdfView.pas. If you hold an annotation handle yourself, route on the count before every write:
uses
SysUtils, PDFium, FPdfView;
// Writes Quad at QuadIndex on annotation AnnotIndex of the active page:
// replaces the slot if it exists, otherwise appends a new one
procedure WriteQuad(Pdf: TPdf; AnnotIndex: Integer; QuadIndex: size_t;
var Quad: FS_QUADPOINTSF);
var
Annot: FPDF_ANNOTATION;
Count: size_t;
Ok: Boolean;
begin
Annot := FPDFPage_GetAnnot(Pdf.Page, AnnotIndex);
if Annot = nil then
raise Exception.CreateFmt('No annotation at index %d', [AnnotIndex]);
try
Count := FPDFAnnot_CountAttachmentPoints(Annot);
if QuadIndex < Count then
Ok := FPDFAnnot_SetAttachmentPoints(Annot, QuadIndex, Quad) <> 0
else
Ok := FPDFAnnot_AppendAttachmentPoints(Annot, Quad) <> 0;
if not Ok then
raise Exception.Create('PDFium rejected the quad');
finally
FPDFPage_CloseAnnot(Annot);
end;
end;
A second trap sits in the same function family. FPDFAnnot_CountAttachmentPoints returns size_t, which is unsigned, so the familiar for I := 0 to Count - 1 on an annotation with no quads computes 0 − 1 in unsigned arithmetic and wraps to the largest possible value. Test Count > 0 before entering any loop over quads, or cast to a signed type first. Markup from other tools almost always arrives with at least one quad. A freshly created annotation arrives with zero
Creating a highlight with TPdf.CreateAnnotation
With the component API you never pick between Append and Set. TPdf.CreateAnnotation and TPdf.SetAnnotation both check how many quads the annotation already holds, replace the slots that exist and append the rest, so the creation path appends and the update path replaces. What you supply is a TPdfAnnotation record with Subtype, color, the quad and a Rectangle
Two record details matter here. Initialize the record with Default(TPdfAnnotation). The record holds strings and dynamic arrays, and FillChar over one that already carries a string simply leaks it, so Default is the safer habit for every record you reuse. And always fill Rectangle: the component writes it as the annotation's Rect on every create and update, so a zeroed record produces a Rect of [0 0 0 0] even when the quads are correct. CreateAnnotation works on the active page, which AddPage sets for a new page and PageNumber sets for an existing document, and it raises 'Unsupported annotation subtype' when PDFium cannot create the requested subtype
var
Pdf: TPdf;
A: TPdfAnnotation;
begin
Pdf := TPdf.Create(nil);
try
Pdf.CreateDocument;
Pdf.AddPage(0, 595, 842); // A4, becomes the active page
A := Default(TPdfAnnotation);
A.Subtype := anHighlight;
A.HasColor := True;
A.Color := clYellow;
A.ColorAlpha := $80; // alpha is passed along with the color
A.HasAttachmentPoints := True;
A.AttachmentPoints[1].X := 50; A.AttachmentPoints[1].Y := 700; // top-left
A.AttachmentPoints[2].X := 250; A.AttachmentPoints[2].Y := 700; // top-right
A.AttachmentPoints[3].X := 50; A.AttachmentPoints[3].Y := 680; // bottom-left
A.AttachmentPoints[4].X := 250; A.AttachmentPoints[4].Y := 680; // bottom-right
A.Rectangle.Left := 50; A.Rectangle.Top := 700; // encloses the quad
A.Rectangle.Right := 250; A.Rectangle.Bottom := 680;
A.ContentsText := 'Highlighted region';
Pdf.CreateAnnotation(A);
Pdf.SaveAs('highlighted.pdf');
finally
Pdf.Free;
end;
end;
Switching the decoration costs one line. anUnderline, anStrikeout and anSquiggly take the identical record, quads and all; ISO 32000-1 describes the four together, and they differ only in how the quad region is painted. Subtypes outside that family, such as anSquare, anCircle and anText, position themselves from Rectangle alone; leave HasAttachmentPoints at False and AttachmentPointSets empty for those, and no quad is written
Multi-line selections: one annotation, several quads
A selection that wraps across three lines needs three quads, one per line, because a single quadrilateral spanning all three would also paint the right end of line one and the left end of line three. TPdfAnnotation carries every quad in AttachmentPointSets, a dynamic array of TQuadrilateralPoint; the single AttachmentPoints field remains as an alias for the first entry. When AttachmentPointSets is non-empty, CreateAnnotation writes all of its entries in order and the single field is ignored
You could instead create one annotation per line. It renders the same, but a reviewer then sees three comments, three popups and three items to delete for what was one highlight. Put the lines in one annotation. The geometry is easy to get from a search, because TPdf.CreateDocumentSearch returns each match with a Rectangles array holding one rectangle per run of text on a line, already in page coordinates:
function QuadFromRect(const R: TPdfRectangle): TQuadrilateralPoint;
begin
Result[1].X := R.Left; Result[1].Y := R.Top; // top-left
Result[2].X := R.Right; Result[2].Y := R.Top; // top-right
Result[3].X := R.Left; Result[3].Y := R.Bottom; // bottom-left
Result[4].X := R.Right; Result[4].Y := R.Bottom; // bottom-right
end;
// Your own helper, not part of the library: union of the line rectangles
function UnionRect(const Rects: TPdfRectangles): TPdfRectangle;
var
I: Integer;
begin
Result := Rects[0];
for I := 1 to High(Rects) do
begin
if Rects[I].Left < Result.Left then Result.Left := Rects[I].Left;
if Rects[I].Right > Result.Right then Result.Right := Rects[I].Right;
if Rects[I].Top > Result.Top then Result.Top := Rects[I].Top;
if Rects[I].Bottom < Result.Bottom then Result.Bottom := Rects[I].Bottom;
end;
end;
procedure HighlightMatches(Pdf: TPdf; const Needle: WString);
var
Search: TPdfDocumentSearch;
Match: TPdfDocumentSearchResult;
Found: array of TPdfDocumentSearchResult;
A: TPdfAnnotation;
I, J: Integer;
begin
// Collect every match before editing any page
Search := Pdf.CreateDocumentSearch(Needle, [seWholeWord]);
try
while Search.Next(Match) do
if Length(Match.Rectangles) > 0 then
begin
SetLength(Found, Length(Found) + 1);
Found[High(Found)] := Match;
end;
finally
Search.Free;
end;
for I := 0 to High(Found) do
begin
Pdf.PageNumber := Found[I].PageNumber;
A := Default(TPdfAnnotation);
A.Subtype := anHighlight;
A.HasColor := True;
A.Color := clYellow;
A.ColorAlpha := $80;
SetLength(A.AttachmentPointSets, Length(Found[I].Rectangles));
for J := 0 to High(Found[I].Rectangles) do
A.AttachmentPointSets[J] := QuadFromRect(Found[I].Rectangles[J]);
A.Rectangle := UnionRect(Found[I].Rectangles);
A.ContentsText := Found[I].Text;
Pdf.CreateAnnotation(A);
end;
end;
The search rectangles are axis-aligned, four numbers each, so on rotated text the resulting quad covers the bounding box of the run rather than following the slant. For straight horizontal text, which is most of what gets highlighted, the box and the glyph area coincide. If you need per-character geometry instead, the guide to text extraction with the PDFium Component covers CharacterRectangle and the related text-page calls, and the text measurement and word wrap article shows how to compute line extents for text you are about to generate
Editing an existing markup annotation goes through Pdf.Annotation[Index] := A, which calls SetAnnotation; the subtype in the record must match the stored one, or the call raises 'Incorrect annotation subtype'. Quads are rewritten index by index, and extra entries in AttachmentPointSets are appended. PDFium exposes no call that removes a single quad, so going from three quads down to two leaves the third one in the file. To shrink a highlight, delete it with DeleteAnnotation and create it again with the shorter array
AttachmentPoints counts from 1, except in C++
TQuadrilateralPoint is declared as array [1..4] of TPdfPoint, and the numbering matches the corner numbers in the specification: element 1 is (x1, y1), element 4 is (x4, y4). Code written from memory with zero-based habits gets this wrong in a way the compiler does not always catch. A loop such as for I := 0 to 3 do A.AttachmentPoints[I] := ... compiles in both Delphi and Free Pascal, because the index is only known at run time. With range checking off, which is the Delphi project default, the write for index 0 lands on the bytes just in front of the array, inside the preceding record fields, and the quad itself keeps a zero corner. Nothing raises
A constant index is another matter. The compiler can compare it with the declared bounds before anything runs, and fpc, for one, rejects a literal AttachmentPoints[0] with a range error. The computed index is the form that slips through. Build annotation code at least once with {$R+} in Delphi, or through fpc, before you trust it; with range checking on, the run-time loop above raises ERangeError at index 0
C++Builder turns the rule around. The generated PDFium.hpp declares TQuadrilateralPoint as System::StaticArray<TPdfPoint, 4>, and a C++ static array starts at zero whatever the Pascal lower bound was. In C++ the corners are therefore AttachmentPoints[0] through AttachmentPoints[3], still in Z order. Porting Delphi sample code line by line keeps indices 1 to 4, which shifts every corner by one and writes the last one past the end of the array
Reading the quads back
The quickest check that a markup annotation landed correctly is to read it back through the same API. Pdf.Annotation[Index] fills AttachmentPointSets with every quad stored on the annotation, and HasAttachmentPoints is True when there is at least one:
var
I, Q: Integer;
B: TPdfAnnotation;
begin
Pdf.PageNumber := 1;
for I := 0 to Pdf.AnnotationCount - 1 do
begin
B := Pdf.Annotation[I];
if B.Subtype in [anHighlight, anUnderline, anStrikeout, anSquiggly] then
for Q := 0 to High(B.AttachmentPointSets) do
Writeln(Format('annot %d quad %d: TL (%.1f, %.1f) BR (%.1f, %.1f)',
[I, Q,
B.AttachmentPointSets[Q][1].X, B.AttachmentPointSets[Q][1].Y,
B.AttachmentPointSets[Q][4].X, B.AttachmentPointSets[Q][4].Y]));
end;
end;
For the single highlight created earlier, the expected line is annot 0 quad 0: TL (50.0, 700.0) BR (250.0, 680.0); a top-left Y lower than the bottom-right Y means the corners went in upside down. The quads also travel with the annotation when you exchange markup with other tools: the coords attribute in XFDF holds all of them, eight numbers per quad, as described in the XFDF export and import article. After that, open the saved file in a second viewer and check that the color sits on the glyphs and not beside them, since a viewer that builds its own appearance from QuadPoints is the one that exposes a bad corner order
The annotation record, the multi-quad array and the count-aware writer used throughout this article ship in the PDFium Component for Delphi, C++Builder and Lazarus, where the full annotation API reference sits next to the text search and extraction calls these examples rely on