Technical Article

Search and Replace Text in an Existing PDF with Delphi

A viewer's find box highlights "Acme Corp" on page 2 of an invoice, yet a byte search of the decompressed page stream for the same nine characters comes back empty. For the first word alone, the stream can hold something like <0024004600500048> Tj: two-byte glyph codes in an embedded subset font, with the gap between the two words produced by a positioning offset rather than a space character. Replacing that name means decoding those codes to Unicode, matching there, walking back to the exact bytes that produced the hit, and writing new codes the same font understands. When the subset never contained a glyph the new text needs, there are no codes to write

The requests behind this are ordinary document maintenance. A company renames itself and three thousand archived invoices still carry the old name. A contract template went out with last year's expiry date. A retired part number has to become its successor in every datasheet. In a word processor each of these takes thirty seconds; in a PDF each one runs into the way pages are actually stored

What a PDF page stores instead of text

A PDF page holds positioned glyphs, not editable text. Under ISO 32000-1 §9.4, the content stream drives text-showing operators such as Tj and TJ, which paint sequences of character codes at positions set by the text matrix. Those codes are indices into whatever encoding the current font declares. The route back to readable characters may run through a /ToUnicode CMap (§9.10.3), an /Encoding with a /Differences array, or a CID mapping chain for Type0 fonts. There is no paragraph object and no text flow, and nothing obliges a producer to store one visible word as one string: [(Ac) -12 (me)] TJ is a perfectly ordinary way to kern a word

Replacement adds a second requirement on top of decoding. A text extractor can throw away byte positions once it has the Unicode out. A replacer needs them, because it must know which bytes of which string operand produced each glyph, so it can rewrite exactly that range and leave everything else alone. That is why a plain StringReplace over the stream bytes is the wrong tool even on files that happen to use WinAnsi encoding. It has no idea which ( belongs to a string and which Tf selects the font that gives those bytes their meaning

Searching the decoded glyph sequence

HotPDF Delphi Component searches a loaded document with SearchLoadedPageText and SearchLoadedDocumentText, which match the needle against the decoded Unicode glyph sequence of each page, never against raw stream bytes. A hit is therefore a hit however the font encoded it. While decoding, every glyph keeps a record of the string operand, the TJ array item and the byte offset it came from, which is what the replace step relies on later. The same glyph interpreter drives the API covered in extracting text from a loaded PDF in Delphi; search simply keeps the source positions that extraction discards

How HotPDF search in Delphi tracks StartOfs and EndOfs byte spans while decoding glyphs to Unicode for THPDFTextMatch results
HotPDF search works on the decoded glyph sequence while keeping the byte provenance replacement needs

Each hit comes back as a THPDFTextMatch record: PageIndex, the inclusive glyph range in GlyphStart and GlyphEnd, the user-space origin in X and Y, the hit's Width, the source TokenIndex and ItemIndex, and the matched Text. PageIndex is zero-based. A needle that does not occur gives an empty array and a True result, so the calling code needs no special case for "nothing found"

var
  Pdf: THotPDF;
  Matches: THPDFTextMatchArray;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    if Pdf.LoadFromFile('invoices-2025.pdf') > 0 then
      if Pdf.SearchLoadedDocumentText('Acme Corp', False, Matches) then
        for I := 0 to High(Matches) do
          WriteLn(Format('page %d at (%.1f, %.1f), width %.1f: "%s"',
            [Matches[I].PageIndex + 1, Matches[I].X, Matches[I].Y,
             Matches[I].Width, Matches[I].Text]));
  finally
    Pdf.Free;
  end;
end;

Whether that loop prints anything depends, before anything else, on spaces. The search text is built from the glyphs the page actually paints, one character per glyph, and a TJ offset that visually separates two words is a number in an array rather than a glyph. A producer that sets word gaps with offsets instead of a space character yields "AcmeCorp" in the glyph sequence, and the needle "Acme Corp" will not match it. When a visible phrase refuses to match, search for its longest single word first and look at the Text of what comes back

Case is the other thing to check. With CaseSensitive set to False, builds from Delphi XE2 onward compare characters through the Unicode simple lowercase mapping, which is locale-independent, so É matches é and Greek or Cyrillic capitals match their lowercase forms. Builds with older compilers fold A–Z only. The mapping is one character to one character, which keeps each needle position aligned with exactly one glyph; the consequence is that ß does not match SS. For whole-word UI flows, SearchLoadedPageTextWholeWord drops hits that sit inside a longer word, and GetLoadedSearchHitRect turns a match into a single rectangle for drawing a highlight

Search and replace both work on the page's own /Contents streams. Text painted inside a Form XObject, which is where many tools put stamped headers and footers, lives in a separate stream that the page invokes with Do, and it is outside both operations

Rewriting matched bytes with ReplaceLoadedDocumentText

ReplaceLoadedPageText and ReplaceLoadedDocumentText rewrite every occurrence of a needle by running the font decoding backwards. Each replacement character is looked up through the same chain the decoder uses, in reverse: /ToUnicode bfchar and bfrange entries, CID mappings for Type0 fonts, identity mappings, and the predefined WinAnsi and MacRoman tables. The resulting char codes are written back as a literal string, or as a hex string when any byte falls outside printable ASCII, following the same escaping rules the content-stream parser reads

Only the bytes covered by the match change. Unmatched bytes in the same operand, the whitespace between tokens, comments and every surrounding operator pass through untouched. Replacing bca inside abcabc yields a + replacement + bc. The replacement may be shorter or longer than the needle, and each stream in a page's /Contents array is processed on its own so the page stays well-formed. When a match straddles several string operands, such as Hello stored as [(He) -20 (llo)] TJ, the replacement is written into the operand where the match begins and the matched bytes are removed from the operands that follow

How HotPDF replace in Delphi reverses the decoding chain with HPDFEncodeUnicode and splices only the matched byte range of the string operand
Reverse encoding rebuilds the font's char codes, then only the matched byte range inside the operand is rewritten
var
  Pdf: THotPDF;
  Rewrites: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    if Pdf.LoadFromFile('contract-draft.pdf') > 0 then
    begin
      if Pdf.ReplaceLoadedDocumentText('2025-12-31', '2026-12-31',
        True, Rewrites) then
        WriteLn(Format('%d operand rewrites', [Rewrites]));
      Pdf.SaveLoadedDocument('contract-final.pdf');
    end;
  finally
    Pdf.Free;
  end;
end;

The page is not re-typeset. PDF has no reflow, so a replacement that is wider than the original simply takes more horizontal room and can run into whatever was painted to its right; the next glyph's position was fixed by the producer and does not move. Dates, version strings, part numbers and spelling corrections of similar length are the work this method is built for. Rewording a paragraph would need to re-typeset everything downstream, so that change belongs in the source document

Why can't a font subset take characters it never contained?

A replacement character the embedded subset never included has no char code to reverse to. When a producer subsets a font, its /ToUnicode CMap and encoding cover only the glyphs the original document used, and the glyph outlines for everything else are simply not in the file. If the document never printed a capital E in that font, no byte sequence selects one. That limitation sits in the file, not in the tool doing the replacement

ReplaceLoadedDocumentText treats an unencodable replacement conservatively: if any single character cannot be re-encoded, that occurrence is skipped whole. There is no exception and no half-replaced string, and the original text stays readable. In the date example above, the digit 6 has to exist somewhere in that same font for the rewrite to succeed. Suppose the font only ever printed "2025" and a few order totals with no 6 in them: the dates stay as they are

Why HotPDF skips a whole Delphi PDF text replacement when the embedded font subset lacks a needed character, verified via ReplaceCount
Replacement characters the font subset cannot re-encode skip the whole occurrence, so a ReplaceCount shortfall is a real signal

ReplaceCount reports operand rewrites, and a match spread across several operands can account for more than one rewrite. A count lower than the number of hits still means something was skipped, but the exact answer comes from searching again after the replace. Whatever the second search finds is what stayed behind, with page and position attached

procedure ReplaceAndAudit(Pdf: THotPDF; const OldText, NewText: UnicodeString);
var
  Before, After: THPDFTextMatchArray;
  Rewrites, I: Integer;
begin
  // Re-searching only works when NewText does not itself contain OldText
  Pdf.SearchLoadedDocumentText(OldText, True, Before);
  Pdf.ReplaceLoadedDocumentText(OldText, NewText, True, Rewrites);
  Pdf.SearchLoadedDocumentText(OldText, True, After);
  WriteLn(Format('%d found, %d operand rewrites, %d left',
    [Length(Before), Rewrites, Length(After)]));
  for I := 0 to High(After) do
    WriteLn(Format('  left on page %d at (%.1f, %.1f)',
      [After[I].PageIndex + 1, After[I].X, After[I].Y]));
end;

When the subset is short: preview and apply with a new font

For occurrences the byte-level method cannot encode, PreviewLoadedPageTextReplacement and ApplyLoadedPageTextReplacement take a different route: they remove the matched glyphs and draw the replacement in place with a font you choose, at the original size and on the original baseline. The default THPDFLoadedTextReplacementOptions uses Arial at the matched text's font size, sizes the box to the width of the matched text, and keeps Atomic on. A single rejected match on the page then rolls back the others. The preview returns a plan with one result per match, each carrying a Status and, when rejected, a Reason

var
  Opts: THPDFLoadedTextReplacementOptions;
  Plan, Applied: THPDFLoadedTextReplacementPlan;
  I: Integer;
begin
  // Pdf is a loaded THotPDF; PageIndex is a zero-based page the audit flagged
  Opts := THPDFLoadedTextReplacementOptions.Default;
  Opts.Appearance.FontName := 'Arial';
  Opts.Appearance.OverflowPolicy := ltopShrinkToFit;
  Opts.Appearance.MinFontSize := 6;
  if not Pdf.PreviewLoadedPageTextReplacement(PageIndex, 'Acme Corp',
    'Apex Corporation', True, Opts, Plan) then
    for I := 0 to High(Plan.Results) do
      if Plan.Results[I].Status = ltrsRejected then
        WriteLn(Format('match %d at (%.1f, %.1f): %s',
          [I, Plan.Results[I].X, Plan.Results[I].Y, Plan.Results[I].Reason]));
  if (Plan.RejectedCount = 0) and (Plan.ReadyCount > 0) then
  begin
    Pdf.ApplyLoadedPageTextReplacement(Plan, Applied);
    WriteLn(Format('%d of %d matches applied',
      [Applied.AppliedCount, Applied.MatchedCount]));
  end;
end;

The rejection reasons are worth printing because they map directly to page geometry. A match that crosses from one text line to the next is rejected, and so is vertical text. With the default ltopReject overflow policy, a replacement that does not fit the matched width is rejected too. ltopShrinkToFit steps the size down toward MinFontSize instead, which is why the example sets it for a replacement five characters longer than the needle. A replacement containing characters the chosen font cannot show is rejected as well

The plan carries a fingerprint of the page content and fonts. If anything changes the page between preview and apply, ApplyLoadedPageTextReplacement raises EInvalidOpException instead of writing to a page the preview never saw. Pages with unbalanced q/Q or BT/ET pairs, and documents that contain signature fields, raise EArgumentException; signed documents call for incremental updates so the signed revision stays intact

Byte-level replacement goes first, and the font-swap path runs only on pages where the audit still finds the old text. The byte-level rewrite keeps the original font, its metrics and its kerning, so the edited text matches its neighbors on the line. The preview path draws in a different typeface, and on a line set in a condensed or serif font a careful reader will see the change. When the goal is to make text disappear rather than reword it, true content removal is the better tool; redacting and restructuring loaded PDFs in Delphi covers that path

What changes in the saved file

A content stream edited by ReplaceLoadedPageText is saved uncompressed. The stream is decoded for editing, and when the rebuilt bytes are written back its /Filter and /DecodeParms entries are dropped and /Length is refreshed. The PDF is valid and renders normally; the cost is a larger file for every edited stream. A batch job over thousands of invoices should budget for that growth or run a compression pass afterwards

The preview-and-apply path changes a little more. An applied page gets a single new uncompressed content stream in place of its original /Contents, plus its own copy of the resource dictionary with the replacement font added. Everything else in the document is left alone: untouched streams keep their compression, existing fonts and images are not rewritten, and pages without hits are never opened for writing. How rewritten objects land in the cross-reference structure on save is covered in object streams and incremental updates in HotPDF

Search, byte-level replace, preview-and-apply replacement, extraction and redaction all run on the same content-stream interpreter, from Delphi 5 through current RAD Studio, without external dependencies. Method references, the replacement options and a trial build are on the HotPDF Delphi Component product page