Technical Article

Rich Text in Delphi PDFs with HotPDF TextOutHTML

An inspection report already has its headings and signature box in place, but one instruction still needs bold text, a chemical formula, and a clickable link. HotPDF THPDFPage.TextOutHTML draws that fragment at a known position on the PDF page and returns the Y coordinate where whatever follows can start. That return value does half the work.

A short HTML fragment on a PDF page

THPDFPage.TextOutHTML takes an X and Y position, a WideString fragment, and three optional defaults for font family, font size, and color, which are Arial, 12, and clBlack when you leave them out. The overload with MaxWidth also takes a line width. Both forms draw on the page you call them on. The console program below starts an inch from the top and left. That is 72 at the default resolution of 72 drawing units per inch. BeginDoc creates it as the first page of a new document. The coordinates adapt easily to an existing report. The signature box, the drawing calls, and the note can all share one page coordinate system.

program InspectionNote;

{$APPTYPE CONSOLE}

uses
  HPDFDoc,
  Vcl.Graphics;

var
  Pdf: THotPDF;
  Page: THPDFPage;
  NextY: Single;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.FileName := 'inspection-note.pdf';
    Pdf.AutoLaunch := False;
    Pdf.BeginDoc;
    Page := Pdf.CurrentPage;

    NextY := Page.TextOutHTML(72, 72,
      '<b>Tank inspection</b><br>' +
      'The indicator confirms H<sub>2</sub>O is present.',
      'Arial', 12, clBlack);
    Writeln('NextY = ', NextY:0:1);

    Page.TextOutHTML(72, NextY + 8,
      'Record the result under <i>Water checks</i>.',
      'Arial', 11, clBlack);
    Pdf.EndDoc;
  finally
    Pdf.Free;
  end;
end.

The heading uses a dedicated <br> so it stays above the instruction even if the Delphi source is reformatted, since a raw newline inside the fragment counts only as a space. In the formula, the <sub> scope shrinks the numeral to 70% of the surrounding size and drops it below the baseline. The closing tag restores the enclosing style. The following “O” returns to the normal size and baseline. <sup> gives the corresponding raised effect, as in cm<sup>2</sup>. Nesting builds on that: an <i> inside a <b> adds italic to bold, a <font> run can pick up a second color inside a black paragraph, and each closing tag hands back one style. The base face and size belong in the call, where the layout code can find them.

Inline markup for short report fragments
FragmentResult on the page
<b>Overdue</b> or <i>Estimated</i>Emphasis on a specific word within the line, with the surrounding text drawn at the base style
<u>Manual entry</u> or <s>Provisional</s>An underline for a label or a strikeout that keeps the superseded wording legible
<font face="Georgia" size="14" color="navy">Note</font>A change of typeface, size, and color for one span, with the size contributing to the line height
H<sub>2</sub>O or m<sup>3</sup>A smaller number moved below or above the baseline of the letters
Operator<br>SupervisorTwo lines starting at the same X coordinate, each with its own vertical advance
<a href="https://example.com/manual">Instructions</a>Blue underlined words, each carrying a link annotation that opens the target address
Pressure &lt; 5 or &#169;A literal less-than sign or the character identified by the decimal numeric entity

What does the returned Y coordinate mean?

THPDFPage.TextOutHTML returns the Y position where a following line can start after the fragment. The value is larger than the Y you passed. Page coordinates start at the top-left corner and grow downward. That makes the returned Y worth reusing whenever a heading and its paragraph can change size or wrap, instead of adding a constant to the original Y, which assumes the input fills a fixed number of lines. That assumption breaks as soon as a translated description gets longer or a larger font changes the line height. Expected output of InspectionNote: NextY = 100.8. The starting 72 is followed by two line advances of 14.4, one for the heading and one for the instruction. In NextY + 8, the 8 is extra space between two fragments. The line heights are already inside NextY. An empty string returns the starting Y. That suits an optional note that the application left empty. To reserve that row anyway, add its height at the call site, as the 8 does.

Mixed sizes on one line are a good reason to let the renderer measure the line. TextOutHTML uses the largest size on that line to place smaller runs around a common baseline and to choose the advance to the following line, which is 1.2 times that largest size. A 16-point word in a 12-point sentence therefore changes the advance after that line to 19.2 units instead of 14.4. A fixed row increment in the layout code cannot see the change. Each call starts from the defaults passed to it. The page font and fill color then stay at the last rendered run after the call. DrawMaintenanceNote sets both. It does so before its plain TextOut call.

MaxWidth sets the width a fragment may use

MaxWidth is the width available to the fragment. It is measured in the drawing units that X and Y use. For a column that runs between a left and a right margin, start with Page.UserWidth - LeftMargin - RightMargin. A sidebar note gets the interior width, after its padding is subtracted. At the default Resolution of 72, a drawing unit is a point. A margin of 72 is one inch. A report that draws at another Resolution has to state its margins and its width in that resolution’s drawing unit, because Page.UserWidth follows the drawing unit while Page.Width stays in points. The article on how HotPDF Resolution defines drawing units and UserWidth lists the page properties that move with that setting.

A positive MaxWidth lets TextOutHTML wrap at word boundaries, using the measured widths of the styled runs. Character counts are a poor fit for this job. The words “inlet valve” and “minimum fill” occupy different widths even before a new font or size enters the paragraph. For a deliberate break, <br> is still the tool. Wrapping never splits a word. An unbroken serial number gets a line of its own and can still run past the column, so give such an identifier a wider region or a <br> at a meaningful point. Links can show a short human-readable label. The complete target address travels in the attribute.

A note that spans a US Letter page with 72-point margins has a usable width of 468 points, the 612-point sheet width minus the two margins. In a 230-point panel with 10 points of padding on both edges, the same note gets a width of 210, and the X coordinate is the panel’s left edge plus 10. The old 468-point width in that second layout lets the note run through the panel border. The width has to come from the box at the call site, and it counts most when one template serves both a full-page report and a two-column version.

How does a wrapped PDF link stay clickable?

TextOutHTML paints the words inside an <a href> element in blue with an underline and registers a PDF link annotation over each segment of that anchor. With a positive MaxWidth a segment is one word together with the space that follows it, so an anchor that spans several lines becomes a series of small rectangles, one per linked word, that all carry one target. That is why the visible label in the procedure below can be as long as a sentence without making the surrounding text clickable. The color and the underline tell the person reading the report where the link is; the annotations supply the clickable regions and the URI action, and a viewer may still ask before opening an external site. The Link Annotation and URI Action clauses in ISO 32000-1:2008, §§ 12.5.6.5 and 12.6.4.7 define those two objects.

procedure DrawMaintenanceNote(Page: THPDFPage; X, Y: Single);
var
  NextY: Single;
begin
  NextY := Page.TextOutHTML(X, Y, 210,
    'Before restarting the pump, read the ' +
    '<a href="https://example.com/manual#refill">' +
    'instructions for refilling, checking the tank, and clearing air from the supply line</a> ' +
    'and record the water level.',
    'Arial', 11, clBlack);

  Page.SetFont('Arial', [], 10);
  Page.SetRGBFillColor(clBlack);
  Page.TextOut(X, NextY + 6, 0, 'Operator initials: __________');
end;

// In InspectionNote, declare the procedure above the main begin block and
// call it after Page := Pdf.CurrentPage; the panel starts at X = 72:
DrawMaintenanceNote(Page, 82, 150);

The 210-unit column gives the long label room to wrap, and the returned Y places the initials beneath the whole note. The initials follow the label. A single linked word instead of that sentence and they sit higher, with no change to the layout code. Expected in a PDF inspector: one /Subtype /Link object per linked word, each with a /Rect and an action whose /S is /URI. Expected in a viewer: the first and the last linked word open one address, and the plain text after the anchor does not react to a click. When the interactive area belongs over a hand-drawn label or a graphic rather than over text, the article on HotPDF hyperlinks, from PrintHyperlink to AddURILink hotspots covers that coordinate-based route.

Markup that stays in the report template

A report keeps the small amount of markup in a template of its own and escapes every value inserted between the tags. A name like “R&D <North>” has to reach the parser as R&amp;D &lt;North&gt; before the text and the angle brackets print as entered. The order of escaping matters. The ampersand goes first, before the less-than and greater-than signs turn into entity spellings that contain ampersands of their own. The parser resolves six spellings, &amp;, &lt;, &gt;, &quot;, &nbsp;, and the decimal &#N;. Anything else between an ampersand and a semicolon is dropped.

uses
  System.SysUtils;  // add to the uses clause of InspectionNote

function EscapeInlineText(const Value: string): string;
begin
  Result := StringReplace(Value, '&', '&amp;', [rfReplaceAll]);
  Result := StringReplace(Result, '<', '&lt;', [rfReplaceAll]);
  Result := StringReplace(Result, '>', '&gt;', [rfReplaceAll]);
end;

function DrawLocationLine(Page: THPDFPage; X, Y, MaxWidth: Single;
  const Caption, URL: string): Single;
begin
  if (Pos('"', URL) > 0) or (Pos('<', URL) > 0) or (Pos('>', URL) > 0) then
    raise Exception.Create('Could not draw the link: the URL is not safe inside the href attribute');
  Result := Page.TextOutHTML(X, Y, MaxWidth,
    '<b>Location</b>: ' + EscapeInlineText(Caption) +
    ' <a href="' + URL + '">Open the site procedure</a>',
    'Arial', 11, clBlack);
end;

// In InspectionNote, after Page := Pdf.CurrentPage:
NextY := DrawLocationLine(Page, 72, 72, 468,
  'R&D <North>', 'https://example.com/procedure?site=7&lang=en');
HotPDF diagram of one TextOutHTML call: the b tag makes a bold run, EscapeInlineText keeps the ampersand and angle brackets of the caption intact, and an a href element draws its words in blue with an underline and a link annotation over each one, with /Rect, /Subtype /Link and /S /URI
A bold tag, an escaped caption and an anchor all turn into styled words on the page, and the anchor leaves one link annotation over each of its words, all pointing at the same target

EscapeInlineText covers values that go between tags. A URL is a different case. Nothing inside a tag is decoded: the attribute reader takes the text between the quotes as it is and keeps the target as an AnsiString, so the parameter wants a serialized URI, with non-ASCII characters percent-encoded. The last two lines of the block show a call. Its caption prints with the ampersand and angle brackets intact, and its query string keeps its own ampersand.

Short fragments suit a report that already owns the page layout. A call draws into the current page and hands back the position to continue from. TextOutHTML wraps lines, but it never moves to a new page: the returned Y keeps growing line after line, whether or not it has passed the bottom margin. A field that can run to several pages needs its space planned before the first call. An entire HTML document with stylesheets, tables, or paged layout belongs in the HotPDF HTML5 paged-media importer, which lays the document out from its own structure and breaks the pages itself. A fixed report note that needs emphasis or a link, and may grow by a line as its wording changes, is the natural first candidate. The HotPDF Delphi PDF Component page has the component downloads and the documentation.