A support callout in a PDF looks fine in English, then a longer label drops below its background and the original click target stays put. The label's final width was never measured. With PDFlibPas you measure the wrapped label at its final font and width, reserve that space before anything is drawn, and hand one box to both the background and the web link.
What makes a PDF callout fit its text?
Three numbers decide whether a callout fits (the position of the baseline, the width of the text, and the height of the whole block), and all of them come before the first stroke of the background. A 12-point font size is only a scale. A run of glyphs at that size still has a width and a height of its own: the Helvetica labels III and WWW each have three characters, yet at 12 points the first advances about 10 points and the second about 34. That gap is enough to decide whether a short label fits beside an icon, which is the kind of question GetTextWidth answers with the advance under the font, size, and spacing that are selected when the call is made. A callout that may borrow as much width as it needs can take that advance as its width for a short left-aligned label, whereas a report callout gets a maximum width instead, so that an unexpectedly long name or an extra phrase grows down the page rather than sideways.
GetTextBound(2) gives the top of the selected font box as a distance above the baseline. GetTextBound(4) gives the bottom as a signed offset. Those are font-wide bounds, not the extent of any one string. Think about the capitals in HELP against the descender in Help paying: with one font and size, both labels can share a vertical start and a height even though their visible outlines occupy different regions. The ascent and the font box top are different distances. Helvetica at 12 points has an ascent of about 8.6 points, whilst the top of its font box sits about 11.2 points above the baseline. An ascent metric is what aligns adjacent text along a design guide. The font box is what leaves room for the wider range of glyphs a variable label might contain.
One coordinate system has to carry the whole calculation. ISO 32000-1 §8.3.2.3 describes the default PDF user space with an upward y-axis and a default unit of 1/72 inch, subject to the page's UserUnit and rotation. The examples here author new, unrotated pages and call SetOrigin(1) with SetMeasurementUnits(0), so coordinates increase down the page and the layout is measured in points. SetTextSize takes points even when the placement unit is millimetres. In that top-left convention the text anchor goes at the callout top, plus the inner padding, plus the font's upper bound. The wrapped drawing routine puts the first baseline on that anchor, whatever the text alignment. Room below the text block still has to be reserved. The example keeps eight points of padding around a 12-point font. The ISO 32000-1 standard hosted by Adobe has the normative wording of §8.3.2.3 and the rest of the coordinate system chapters if you ever need to cite it.
The wrapped height is measured before anything is drawn
Call GetWrappedTextHeight at the inner width, the width that remains once the left and right padding have been taken out, and pass that identical width on to DrawWrappedText when the text is painted. The returned height covers the wrapped lines and any additional spacing between them, so with blank space around the block the geometry can change from one line to three without changing how the background and the link are placed. Keep the font, size, alignment and spacing fixed from measurement through painting, as the code below does with left alignment, zero additional line spacing, and one width for both calls. For a diagnostic build, GetWrappedTextLineCount is a convenient value to log when a localisation team reports a sudden change of page count.
const
CalloutPadding = 8.0;
type
TCalloutLayout = record
InnerWidth: Double;
FontTop: Double;
BoxHeight: Double;
end;
procedure SelectCalloutFont(PDF: TPDFlib; FontID: Integer);
begin
if PDF.SelectFont(FontID) <> 1 then
raise Exception.Create('Unable to select the callout font');
if PDF.SetTextSize(12) <> 1 then
raise Exception.Create('Unable to set the callout font size');
PDF.SetTextAlign(0);
PDF.SetTextSpacing(0);
end;
function MeasureCallout(PDF: TPDFlib; BoxWidth: Double;
const Caption: WideString): TCalloutLayout;
var
TextHeight: Double;
begin
Result.InnerWidth := BoxWidth - 2 * CalloutPadding;
if (Caption = '') or (Result.InnerWidth <= 0) then
raise Exception.Create('A callout needs text and a positive inner width');
TextHeight := PDF.GetWrappedTextHeight(Result.InnerWidth, Caption);
if TextHeight <= 0 then
raise Exception.Create('Unable to measure the wrapped callout text');
Result.FontTop := PDF.GetTextBound(2);
Result.BoxHeight := TextHeight + 2 * CalloutPadding;
end;
A customer-facing caption can be a short phrase such as "Open the service checklist for your model," whilst its destination is a much longer URL with a path or a query string that plays no part in the layout. Only the caption is measured and wrapped. If the literal URL has to appear on the page, check its break points with GetWrappedText, which returns every wrapped line followed by the delimiter you pass, so give it a delimiter that never occurs in the URL, a vertical bar for instance, and split the result on that. A run of capitals or an unbroken identifier can produce a very different layout from a sentence with just as many characters. Leave enough inner width for a single displayed character, since a positive wrapped height can still include a character wider than an extremely narrow column, and if a diagnostic shows such a line, widen the box, choose a smaller font, or shorten the visible label; continuous prose with hyphenation or column balancing is a different layout problem. Hyphenation and balanced text columns cover that case.
How do you align the clickable area with the box?
A PDF web link uses a page annotation with a rectangle and a URI action (ISO 32000-1 §12.5.6.5 describes link annotations and §12.6.4.7 describes URI actions), whilst the filled background and the visible label belong to the page's content. The two are independent. A viewer can therefore display the callout and still have a smaller active area if the annotation received the bounds of the first line, and, in the other direction, a link rectangle drawn all the way to the right edge of a column may make unrelated white space clickable. For this layout the callout itself is the target, so the ink can change width from line to line whilst the clickable area stays attached to the callout.
In the normal PDF drawing path with a font selected, AddLinkToWeb applies a font-top adjustment to its vertical anchor, so the direct way to align the annotation to the top of a rectangle is to pass the rectangle top plus GetTextBound(2) for the top-left coordinates used here. Pass the same padded Y argument used for DrawWrappedText and the link will start one padding distance below the desired top edge. The example keeps left alignment active because the helper also adjusts the horizontal anchor for centre and right alignment, so with a fresh document and no text rise the two arguments are the callout's left edge and a link anchor one font-top offset from its upper edge. The AddLinkToWeb reference lists the border and highlight options of its last argument.
procedure DrawCallout(PDF: TPDFlib; Left, Top, BoxWidth: Double;
const Layout: TCalloutLayout; const Caption, URL: WideString;
ShowLinkBorder: Boolean);
var
TextAnchorY: Double;
begin
if URL = '' then
raise Exception.Create('A clickable callout needs a URL');
PDF.SetFillColor(0.91, 0.95, 0.98);
PDF.SetLineColor(0.25, 0.43, 0.58);
PDF.SetLineWidth(0.8);
PDF.DrawBox(Left, Top, BoxWidth, Layout.BoxHeight, 2);
PDF.SetTextColor(0.10, 0.19, 0.27);
TextAnchorY := Top + CalloutPadding + Layout.FontTop;
if PDF.DrawWrappedText(Left + CalloutPadding, TextAnchorY,
Layout.InnerWidth, Caption) <> 1 then
raise Exception.Create('Unable to draw the wrapped callout text');
PDF.AddLinkToWeb(Left, Top + Layout.FontTop, BoxWidth,
Layout.BoxHeight, URL, Ord(ShowLinkBorder));
end;
DrawBox option 2 fills and strokes the rectangle, and because the stroke is centred on the path, the 0.8-point outline protrudes about 0.4 points beyond each edge. I'd keep the annotation on the path's boundary. Otherwise a designer adjusting the outline weight also changes where the mouse can activate the link. During layout review, a border of 1 on the annotation lets you compare the two outlines in a PDF viewer, whilst a border of 0 keeps the callout's own artwork visible without an extra annotation outline. For a small directional icon inside that rectangle, StartPath, AddLineToPath, ClosePath, and DrawPath let you draw it as vector art, and vector graphics in PDF with Delphi: paths and gradients shows how those four calls fit together.
A callout moves to the next page as one block
The page comes first. DrawWrappedText lays out text on the selected page, and the link annotation also belongs to that page; the example starts with 12 points of usable space below an existing line of text, which is what moves the callout to a fresh A5 page. If the whole callout is taller than the content area between the top and bottom margins of a fresh page, moving it forward can't make it fit. At that point, shorten the label or design multiple blocks with their own backgrounds and annotations on each page; the example reports the oversized callout instead, so that each callout keeps one rectangular target. A successful NewPage selects the new page and returns its page number, and the measured text settings have to be reapplied on that page before drawing.
procedure WriteCalloutPDF(const OutputFile: WideString);
const
Margin = 36.0;
BoxWidth = 180.0;
Caption = 'Open the service checklist for this unit before scheduling a visit';
URL = 'https://example.com/service-checklist';
var
PDF: TPDFlib;
FontID: Integer;
CursorY: Double;
Layout: TCalloutLayout;
begin
PDF := TPDFlib.Create;
try
if PDF.NewDocument = 0 then
raise Exception.Create('Unable to create the callout PDF');
if PDF.SetPageSize('A5') <> 1 then
raise Exception.Create('Unable to set the A5 page size');
PDF.SetOrigin(1);
PDF.SetMeasurementUnits(0);
FontID := PDF.AddStandardFont(4); // Helvetica
if FontID = 0 then
raise Exception.Create('Unable to add Helvetica');
SelectCalloutFont(PDF, FontID);
CursorY := PDF.PageHeight - Margin - 12;
if PDF.DrawText(Margin, CursorY - 14, 'Service information follows.') <> 1 then
raise Exception.Create('Unable to draw the introductory line');
Layout := MeasureCallout(PDF, BoxWidth, Caption);
if Layout.BoxHeight > PDF.PageHeight - 2 * Margin then
raise Exception.Create('The callout is taller than the page content area');
if CursorY + Layout.BoxHeight > PDF.PageHeight - Margin then
begin
if PDF.NewPage = 0 then
raise Exception.Create('Unable to add a page for the callout');
SelectCalloutFont(PDF, FontID);
CursorY := Margin;
end;
DrawCallout(PDF, Margin, CursorY, BoxWidth, Layout, Caption, URL, False);
if PDF.SaveToFile(OutputFile) <> 1 then
raise Exception.CreateFmt('Unable to save the callout PDF (PDF error %d)', [PDF.LastErrorCode]);
finally
PDF.Free;
end;
end;
After the three blocks are copied in order into a Delphi unit that uses SysUtils and PDFlibrary, the expected result of WriteCalloutPDF('service-callout.pdf') is one line near the bottom of page 1 and a boxed, wrapped label near the top of page 2. Three clicks in a PDF viewer settle it. A click on the padding just inside the upper border and one just below the last line should both reach the callout's URI action, subject to the viewer's policy for external links; a click just outside the callout should have no callout action. If the viewer detects links in page text as an extra convenience, a descriptive caption such as the one in this example makes it easier to tell that the hit came from the annotation.
The saved PDF can confirm the arithmetic. Call the page height H, use X, Y, W, and B for the top-left callout position, width, and height from the example, and in the page's default user space the expected annotation /Rect is [X, H - Y - B, X + W, H - Y]. For the fixed 180-point callout at X = 36 the horizontal coordinates are 36 and 216 irrespective of line count, whilst the y coordinates use the measured height and the selected page's actual height. If the upper edge of /Rect lands eight points lower than the visual top, check whether the annotation was given the padded Y argument that went to the text drawing call.
To check the saved file programmatically, select page 2 before reading its annotations, then compare the link rectangle with the planned position and width and check that the action stores the expected URL, because the AddLinkToWeb return value alone gives no information about the shape or location of the saved annotation. Reading the rectangle back is what separates a rectangle that landed in the wrong spot from a viewer that asks before opening external websites, and the companion guide to reading PDF bookmark and annotation actions in Delphi covers the read side. The PDF Library for Delphi product page links to the full drawing, text, and annotation references.