A brochure headline reading "Bold words" on screen comes out of a naive text extractor as "Bold wordsBold words". Every character decoded correctly, and the headline really does appear twice in the content stream: the producer had no bold face, so it showed the string, nudged the text position right by a few tenths of a point and showed it again. The only way to get a single "Bold words" back is to decide which of two perfectly valid glyphs is the copy, without also swallowing the second l in "fill" or the identical cells of a price table
That decision is a geometric one. Two copies of a letter sitting almost on top of each other amount to one painted character; two copies a full advance width apart are two letters. Everything below concerns where that line is drawn, together with a second extraction trap of a similar flavour, CID width arrays written out of order, which makes the ends of lines vanish
Why does fake bold produce doubled text in PDF extraction?
Fake bold doubles extracted text because both passes are genuine text-showing operations. Plenty of generators emulate bold by issuing the same string with Tj or TJ, moving the text position with a small Td and issuing it once more. On screen the two passes merge into a heavier stroke. In the content stream there are two complete runs of character codes, and ISO 32000-1 §9.4 offers an extractor no flag marking either run as decoration
Overprinted logos reach the same destination by a different road. A logotype may be painted once as a fill and again as a stroke or a slightly offset shadow, same font and same characters throughout. An extractor that walks the content stream in painting order emits the whole first run and afterwards the whole second run, which is why the output reads "Bold wordsBold words" and never "BBoolldd". A substring search across that text will still find the phrase, yet word counts, layout output and any comparison against a known value emerge wrong
Text rendering mode 2 (fill, then stroke, ISO 32000-1 §9.3.6) causes none of this. It is one text-showing operation and yields one set of glyphs. Duplicates only appear when the producer issues the text twice
The five tests a pair of glyphs must pass in HotPDF
HotPDF Delphi Component reads two glyphs as one painted character when they carry the same Unicode value, run in the same writing direction, lie within 5% of each other in size and sit no more than 0.1 of the glyph size apart along the baseline, nor more than 0.2 of the glyph size apart across it. The glyph painted first is kept; the later one is dropped. Each number has a job to do:
- Same Unicode, same direction. Only identical characters can be duplicates, and a horizontal glyph is never measured against a vertical (WMode 1) one
- Size within 5%. A large heading letter and a small caption letter that happen to overlap belong to different text altogether
- 0.1 of the size along the baseline. Fake bold offsets run to a few percent of a normal text size. Two genuine neighbours, even a tightly kerned "ll", sit about one advance width apart, roughly ten times this tolerance
- 0.2 of the size across the baseline. Shadow and outline passes often shift downwards as well as rightwards, so the vertical allowance is looser, and still far short of the next line
- First painted wins. The surviving glyphs come from the first run, so the extracted text keeps the order in which the producer wrote it
The offsets are measured in the first glyph's own baseline frame, so rotated text and text on a slanted baseline receive the same tolerances as an ordinary horizontal line. "Size" here means the size the glyph ends up at on the page: HotPDF scales the Tf size by how far the glyph's advance actually travels in user space, falling back to the height of the glyph's quad where there is no advance to go on. That matters for files that set Tf to 1 and do all their scaling through the text matrix. Measured against a raw size of 1, the along-baseline tolerance would shrink to a tenth of a point whatever the visible size, and a typical fake-bold offset would never match
Blank glyphs never take part. Every code point up to U+0020, the no-break space U+00A0 and the ideographic space U+3000 are skipped, because a space carries no ink worth duplicating and dropping one would glue two words together. A glyph whose code resolved to Unicode 0 is skipped as well, there being nothing to compare it on
Keeping the check quick on dense pages
Comparing each glyph against every other glyph would be correct yet far too slow. A page of small print can carry tens of thousands of glyphs, and the check runs on every text extraction call
The check sorts the non-blank glyphs by Unicode value, then by origin X, then by painting order, using a stable merge sort. After that, every possible duplicate of a glyph sits directly behind it in the sorted list, and the scan from each glyph walks forward only whilst the Unicode value matches and the X difference stays within 0.25 of the glyph size. That window is deliberately wider than the 0.1 along-baseline limit: on a slanted baseline a genuine pair can differ more in raw X than along the baseline itself, and it still has to land inside the window before the precise test runs. The whole pass costs about n log n
Triple strikes call for one more rule. If the scan starting at glyph A meets a matching glyph painted earlier than A, then A is the copy: A is dropped and its scan stops, and the earlier glyph carries on comparing against whatever lies further along. Three passes of the same headline therefore collapse to the first one, just as two do
The comparison rests on Unicode value, regardless of which font or character code produced it. A fill pass set in one embedded subset and a stroke pass set in another subset of the same face still collapse to one character, provided both map to the same code point. Glyphs that map to nothing are the weak spot, one more reason to watch the unresolved glyph count described in extracting text from loaded PDFs with HotPDF
Which HotPDF extraction calls strip duplicate glyphs?
Every call that produces page text removes duplicates; the raw glyph and search calls do not. The filter lives in THotPDF.ExtractVisibleLoadedPageGlyphs, which gathers the glyphs of the page and of the Form XObjects it paints, drops glyphs whose centre falls outside the visible box and then collapses overprints. ExtractLoadedPageText, ExtractLoadedPageTextLayout, ExtractLoadedPageTextColumns and the semantic text analysis all draw from it
THotPDF.ExtractLoadedPageGlyphs keeps every glyph the page content stream paints, overprints included, and SearchLoadedPageText matches against that full sequence. The split is deliberate. Highlighting, redaction and search-and-replace work on what was drawn, and each painted copy of a headline is its own operand in the content stream. A replacement that rewrote only the first pass of a fake-bold heading would leave the old wording showing through the second
For ordinary text work nothing changes in calling code. This loop finds the phrase once in the page text and also prints how many painted copies the search turns up:
uses
System.SysUtils, HPDFDoc, HPDFContentStream;
var
Pdf: THotPDF;
PageCount, I: Integer;
PageText: UnicodeString;
Hits: THPDFTextMatchArray;
begin
Pdf := THotPDF.Create(nil);
try
PageCount := Pdf.LoadFromFile('brochure.pdf');
for I := 0 to PageCount - 1 do
begin
// Page text: overprinted copies already collapsed
if Pdf.ExtractLoadedPageText(I, PageText) and
(Pos('Bold words', PageText) > 0) then
Writeln('Page ', I + 1, ': phrase found in page text');
// Search: one match per painted copy in the page content stream, so a fake-bold heading usually counts twice
if Pdf.SearchLoadedPageText(I, 'Bold words', True, Hits) and
(Length(Hits) > 0) then
Writeln('Page ', I + 1, ': ', Length(Hits), ' painted occurrence(s)');
end;
finally
Pdf.Free;
end;
end;
Layout and column output gain the most, since a duplicated run would otherwise shove the rest of the line sideways along the character grid. The filter runs before column splitting, so the gap multiplier of ExtractLoadedPageTextColumns behaves identically with or without overprinted text on the page:
var
Grid, Columns: UnicodeString;
begin
// Needs System.IOUtils for TFile
if Pdf.ExtractLoadedPageTextLayout(0, Grid) then
TFile.WriteAllText('page1-layout.txt', Grid, TEncoding.UTF8);
// A new column starts where a gap exceeds 3x the median glyph advance
if Pdf.ExtractLoadedPageTextColumns(0, Columns, 3.0) then
TFile.WriteAllText('page1-columns.txt', Columns, TEncoding.UTF8);
end;
Word spacing and line breaks are decided after the filter and remain unaffected by it; how HotPDF places word spaces and line breaks in page text covers those rules, and search and replace in an existing PDF covers the operand-level side
When a heading still comes out doubled
The tolerances are tight by design, and tight is the right default. A missed duplicate costs one doubled heading that anyone reading the output will spot. An over-eager merge deletes a letter from "fill" or collapses two identical table cells into one, and that sort of loss goes unnoticed until a lookup against the extracted data fails. So a second pass offset by more than 0.1 of the glyph size along the baseline, or drawn at a noticeably different size, extracts as its own text. Beyond that offset the effect stops looking like bold anyway and starts looking like misregistered print
The opposite case is a footer painted twice at exactly the same position. HotPDF reads it once. A glyph sitting precisely atop an identical glyph cannot be seen as a second character, so one copy is what the page shows. Text repeated elsewhere on the page, a running header in a hidden optional content layer for instance, is another matter entirely and stays in the output
When a heading does come out doubled, measure it. The painted glyph count set against the text glyph count tells you whether anything was filtered at all, and listing nearby same-character pairs shows how far apart the passes really sit:
// Reader-side diagnostic, not a library function: compares painted and
// text glyph counts, then lists same-character pairs close to each other
function GlyphHeight(const G: THPDFGlyphRecord): Double;
begin
Result := Sqrt(Sqr(G.QuadX[3] - G.QuadX[0]) + Sqr(G.QuadY[3] - G.QuadY[0]));
end;
procedure ReportOverprints(Pdf: THotPDF; PageIndex: Integer);
var
Painted, Visible: THPDFGlyphArray;
I, J: Integer;
H: Double;
begin
if not (Pdf.ExtractLoadedPageGlyphsWithForms(PageIndex, Painted) and
Pdf.ExtractVisibleLoadedPageGlyphs(PageIndex, Visible)) then
Exit;
// The difference also counts glyphs outside the crop box
Writeln(Format('%d painted, %d read as text',
[Length(Painted), Length(Visible)]));
// Quadratic on purpose: run it on one problem page, not a whole batch
for I := 0 to High(Painted) - 1 do
begin
H := GlyphHeight(Painted[I]);
if (Painted[I].Unicode <= 32) or (H <= 0) then
Continue;
for J := I + 1 to High(Painted) do
if (Painted[J].Unicode = Painted[I].Unicode) and
(Abs(Painted[J].X - Painted[I].X) < H) and
(Abs(Painted[J].Y - Painted[I].Y) < H) then
Writeln(Format('U+%.4X: dx=%.3f dy=%.3f, size %.2f',
[Integer(Painted[I].Unicode), Painted[J].X - Painted[I].X,
Painted[J].Y - Painted[I].Y, H]));
end;
end;
The painted side uses ExtractLoadedPageGlyphsWithForms because the text calls take in Form XObject glyphs too. A dx above a tenth of the size means the passes sit farther apart than a fake-bold offset, and the heading extracts twice by design
Why can line endings go missing in CID font text?
Line ends vanish from CID-keyed (Type 0) font text when the font's /W width array is not sorted by CID and the extractor looks widths up with a binary search. ISO 32000-1 §9.7.4.3 defines the /W format but prescribes no order for its entries, and some generators write them in the order the glyphs were first used in the document
A binary search over an unsorted /W misses most CIDs. Each miss falls back to the default width /DW, and a font that omits /DW gets 1000 units, a full em. Latin text is then laid out as though every letter were full width, the line runs far past the right edge of the page, and the glyphs landing outside the visible box are dropped from extraction. The page renders perfectly. The text output simply stops partway through each line, and a search for the last word of a sentence comes back empty
HotPDF sorts the /W ranges by first CID with a stable merge sort the moment it reads them, and skips the sort when the array is already in order. The sort being stable, entries that start at the same CID keep their file order. The page renderer keeps its own copy of the width data and scans it linearly, and the vertical metrics in /W2 are short enough that a linear scan is the simpler choice there too, so entry order never alters how the page looks
That mismatch is the tell. When a Type 0 page renders fine but its extracted lines come up short, inspect the /W array order before suspecting the /ToUnicode map
Collapsing overprinted glyphs and sorting CID widths on read are both built into the HotPDF Delphi PDF component. Text pulled from a loaded PDF in Delphi or C++Builder reads the way the page looks, and the same component covers PDF creation, editing and rendering