Escape a customer comment properly, so that <b>urgent</b> goes into your HTML template as <b>urgent</b>, hand it to a renderer that parses the markup twice, and the PDF can come back with the word urgent in bold. The escaping was correct. The renderer decoded it once per pass. Any HTML-to-PDF path that parses, writes the result back out as HTML and parses again has to decode entities exactly once over the whole trip
The help desk version of this story is ordinary. Tickets are exported to PDF, the customer comment sits inside a <p>, and somebody types angle brackets into the comment box. An unknown tag name just vanishes from the page. An escaped anchor becomes a clickable link annotation in a document your staff trusts. The file is valid and opens everywhere; it simply says something different from the data
Where escaped text turns back into markup
Escaped text turns into markup at the point where a two-pass renderer writes already decoded text back into HTML without escaping it again. Whatever the first parse decoded is then live syntax for the second parse
The two passes in DrawHTMLText and DrawHTMLTextBox of PDF Library for Delphi (PDFlibPas) exist for a good reason. The first parse splits the input into tags and words. The renderer then resolves the stylesheet cascade: rules from <style> blocks are matched against each tag, merged with inline style attributes, and the whole element list is written back out as one normalized HTML string with every tag carrying its final style. The layout pass parses that string. Selector matching, flexbox, grid and the rest of the CSS support described in flexbox, CSS grid and footnote layout in PDFlibPas HTML rendering all depend on that intermediate step
The danger sits in how words come back out. Tags can be written back from their source form, but words are held as decoded text, because that is what the line breaker measures. Append the word that came from <unsafe> to the normalized string as it is, and <unsafe> arrives at the second parse as an element. A design that decodes once has to close three smaller leaks too:
- If
&is not in the decoded set,R&Dprints literally and there is no way at all to put the spelling<on the page as text - If the drawing stage replaces
again after parsing has finished, a literal entity spelling disappears at the very last moment - If an HTML producer upstream, such as a Markdown converter or a dataset exporter, escapes only the angle brackets, an entity spelling inside a code sample or a cell value is decoded into markup
The table below lists what reaches the page for a handful of inputs, comparing a naive two-pass renderer with the PDFlibPas pipeline
| Input reaching the renderer | Naive two-pass renderer | PDFlibPas |
|---|---|---|
<unsafe> | Parsed as a tag, text never reaches the page | <unsafe> drawn as text |
<b>x</b> | x drawn in bold | <b>x</b> drawn as text |
R&D | R&D printed literally | R&D |
&lt; | &lt; printed literally | < |
Markdown code span containing | A non-breaking space | drawn as text |
Dataset cell value < | < | < |
How does PDF Library for Delphi decode each entity exactly once?
PDF Library for Delphi decodes each entity exactly once by following three rules together: the parser decodes & last, the drawing stage decodes nothing, and every place that turns decoded words back into HTML escapes them first. Drop any one of the three and one of the table rows above flips to the naive column
Start with what gets decoded. In text content the parser recognizes <, >, & and . Numeric references such as A and named entities such as " stay literal text. That short list decides how you should escape your own input, which comes up again further down
Order inside the decoder matters even within a single pass. Decode & first and the input &lt; becomes <, and the very next replacement turns it into <: a double decode without any second parse. The 8-bit word path therefore replaces <, > and first and & last, so the ampersand it produces is never looked at again. The UTF-16 word path takes a different route to the same result — one left-to-right scan in two-byte steps that rewrites each match in place and moves past it
The drawing stage gets no late replacement. A word that reaches the line breaker is final text, and decoding lives in the parser and nowhere else
The boundary rule carries the most weight. When the renderer writes the normalized HTML, it escapes &, < and > in every decoded word before appending it, and the second parse decodes it back to the same characters. Net effect over both passes: one decode. The continuation string that DrawHTMLTextBox returns follows the same rule. Words that did not fit are escaped before they go into the remainder, and the rest of the remainder is copied from the normalized HTML, which is already escaped. A box that takes everything returns an empty string
Why can't UTF-16BE escaping use a byte-level replace?
UTF-16BE escaping cannot use a byte-level replace because the two bytes of an ampersand can straddle two unrelated characters. The whole 16-bit code unit is the only safe unit of work
The renderer keeps Unicode words as big-endian UTF-16 packed into byte strings, high byte first, so an ampersand is 00 26. Take U+0100 (Latin capital A with macron, bytes 01 00) followed by U+2603 (the snowman, bytes 26 03). The buffer reads 01 00 26 03, and bytes two and three spell 00 26. A byte search for #0'&' finds an ampersand that no character contains, splices & into the middle of two code points, and shifts every later character by one byte
This is not an exotic corner. Any character whose low byte is zero can supply the first half, and U+4E00, one of the most frequent CJK ideographs, is such a character. The angle brackets are exposed the same way: 00 3C and 00 3E show up whenever such a character is followed by one from U+3C00 to U+3EFF in CJK Extension A. So PDFlibPas escapes Unicode words by unpacking them to a WideString, escaping character by character and packing the result again. The decoder is safe for the matching reason: it only tests patterns at even offsets
Your own code can hit the same wall. Once UTF-16 text lives in TBytes, for example after TEncoding.BigEndianUnicode.GetBytes, searching it for byte patterns is a bug waiting for the right pair of characters. Convert back to a string and work on characters
Markdown code and dataset cells: the ampersand goes first
Both HTML producers inside PDFlibPas, the Markdown converter and the dataset exporter, escape the ampersand before the angle brackets, so the one decode in the renderer restores the original text byte for byte
In MarkdownToHTML, inline code spans and fenced or indented code blocks map & to &, < to < and > to >. Spaces become and a tab becomes four of them, which keeps indentation intact. Ordinary prose escapes only the angle brackets: raw HTML typed in prose cannot inject tags, while an author who deliberately writes & still gets an ampersand, the way Markdown authors expect. DrawMarkdownText and DrawMarkdownTextBox run the same conversion, so a code block shows up exactly as typed:
uses
System.SysUtils, PDFlibrary;
procedure RenderCodeSample;
var
Lib: TPDFlib;
Md, Html: WideString;
begin
Md := 'Comparison helper:' + sLineBreak + sLineBreak +
'```' + sLineBreak +
'if (A < B) and (Flags <> 0) then' + sLineBreak +
' WriteLn(''<tag> & R&D'');' + sLineBreak +
'```';
Lib := TPDFlib.Create;
try
// Inspect the HTML: inside code, '&' becomes '&' and '<' becomes '<'
Html := Lib.MarkdownToHTML(Md);
Lib.SetOrigin(1); // top-left origin, Y grows downward
Lib.SetMeasurementUnits(0); // points
// The page shows the code exactly as typed, entity spellings included
Lib.DrawMarkdownText(50, 50, 495, Md);
Lib.SaveToFile('code-sample.pdf');
finally
Lib.Free;
end;
end;
The dataset exporter is where the tempting shortcut lives. If a renderer did not decode &, escaping the ampersand would print & in every cell that contains one, so escaping only the angle brackets looks like the friendlier choice. It falls apart on the first cell whose value happens to contain <, which then reaches the page as <. Because the renderer does decode &, the exporter behind PDFlibExportDataSet escapes & first, and a value such as R&D < & lands in the PDF verbatim. The rest of that exporter is covered in exporting a TDataSet to a PDF report in Delphi
Why first, and not just somewhere in the chain? Escape < first and you get <. Escape & second and that turns into &lt;, which a correct single decode displays as < rather than <. A sequential replace chain only works when the escape character itself is handled before any step that introduces it
How should you escape untrusted text for DrawHTMLTextBox?
Escape untrusted text content for PDFlibPas by replacing &, then <, then >, exactly once, and keep untrusted data out of attribute values altogether. The helper below is yours to add; it is plain RTL code:
uses
System.SysUtils, PDFlibrary;
// Your own helper (not part of the library): escapes untrusted text
// for PDFlibPas HTML text content. '&' must be replaced first,
// otherwise the ampersand inside a freshly produced '<' is
// escaped a second time
function EscapeHTMLText(const S: string): string;
begin
Result := StringReplace(S, '&', '&', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
end;
procedure RenderTicket(const CustomerComment: string);
var
Lib: TPDFlib;
Html: WideString;
begin
Lib := TPDFlib.Create;
try
Lib.SetOrigin(1);
Lib.SetMeasurementUnits(0);
Html := '<p><b>Customer comment</b></p>' +
'<p>' + EscapeHTMLText(CustomerComment) + '</p>';
Lib.DrawHTMLText(50, 50, 495, Html);
Lib.SaveToFile('ticket.pdf');
finally
Lib.Free;
end;
end;
Feed it the comment Try <a href="https://example.com">this</a> & <b> and the page shows those characters one for one. Under a renderer that decodes twice, the same escaped input becomes a live link annotation. That is the step from cosmetic glitch to security problem: a ticket comment should never be able to plant a clickable URL in a PDF that goes to your own staff
Notice what the helper leaves alone. General-purpose escapers also turn " into " and ' into ', which is right for a browser and wrong here — PDFlibPas text decoding knows only the four entities listed earlier, so those two would print literally as " and '. Do not reuse a browser escaper for this. Quotes are harmless in text content; they only matter inside attribute values, and the renderer does not decode entities in attributes at all. For attributes we would rather have a rule than a cleverer escaper, because no escaping scheme is checked there anyway: keep user values out of href, src and style. If a link target really must come from user input, validate it yourself against an allow-list of schemes and characters and reject anything containing quotes or angle brackets
Two habits follow directly from single-pass decoding:
- Always escape
&. Skip it, and user text containing<shows up as<— harmless, but not what the user typed - Escape at one point only. Text that passes through two escapers renders
<as the visible spelling<, so find the single place where your data enters the HTML string and escape there
Paginating with LeftOverText without breaking escapes
DrawHTMLTextBox returns the HTML that did not fit, usually called LeftOverText, and that remainder keeps literal entity spellings and escaped angle brackets intact when it goes into the next box. Pass it back exactly as you received it
const
BoxLeft = 50;
BoxTop = 50;
BoxWidth = 495; // sized for an A4 page in points
BoxHeight = 740;
MaxPages = 500; // your own safety cap
procedure RenderLongHTML(Lib: TPDFlib; const Html: WideString);
var
Rest: WideString;
Pages: Integer;
begin
Lib.SetOrigin(1);
Lib.SetMeasurementUnits(0);
Rest := Lib.DrawHTMLTextBox(BoxLeft, BoxTop, BoxWidth, BoxHeight, Html);
Pages := 1;
while (Rest <> '') and (Pages < MaxPages) do
begin
Lib.NewPage;
Inc(Pages);
// The remainder is already escaped HTML: never escape or unescape it
Rest := Lib.DrawHTMLTextBox(BoxLeft, BoxTop, BoxWidth, BoxHeight, Rest);
end;
if Rest <> '' then
raise Exception.CreateFmt('Content still left after %d pages', [MaxPages]);
end;
Treat the remainder as opaque. It is normalized HTML with styles already resolved onto each tag, so running it through your own escaper turns every < into &lt;, and decoding it hands the next box live tags. Splicing fresh user text into it has the same two failure modes. The page cap costs one comparison: if some element can never fit the box, an uncapped loop has no natural exit
Markdown has its own continuation. DrawMarkdownTextBox returns a remainder that begins with a marker comment, which tells the Markdown entry points to skip conversion on the next call. Hand it back to DrawMarkdownTextBox or DrawMarkdownText, the same way you would feed LeftOverText back to DrawHTMLTextBox. A Markdown remainder belongs to the Markdown entry points, so keep it on that side and route only DrawHTMLTextBox remainders through the HTML calls
The shape behind all of this — parse, write back into the same syntax, parse again — also turns up in template engines, HTML sanitizers and Markdown-to-HTML-to-PDF chains, and the failure comes in two directions. Too little re-encoding turns data into syntax. Too much encoding, or a decoder that runs twice, shows entity spellings to the reader or eats them. Patching one direction alone tends to break the other, which is why the PDFlibPas renderer treats & decoding, decoding it last, no late decode and re-escaping at every boundary as a single package. The export direction follows the same rule in PDF to Markdown and DOCX semantic export from Delphi, where each literal character is escaped for the target syntax exactly once
HTML and Markdown drawing, the dataset report exporter and the rest of the layout engine come as native Pascal source in PDF Library for Delphi, for both Delphi and Free Pascal. Editions, platform coverage and the trial download are listed on the PDF Library for Delphi product page