Skip to content

feat(reader): extract text from simple fonts - #417

Merged
Tim81 merged 5 commits into
mainfrom
feat/98-text-extraction-api
Sep 7, 2026
Merged

Tim81 merged 5 commits into
mainfrom
feat/98-text-extraction-api

Conversation

@Tim81

@Tim81 Tim81 commented Sep 6, 2026 •

Copy link
Copy Markdown
Owner

Refs #98. Does not close it: #98 covers text and image extraction, and the text half still needs Type0 and Type3 fonts and its pdftotext oracle.

PR 5 of the v2.4 sequence. The content-stream interpreter (#402) and the simple-font decoder (#407) shipped with no caller; this is the caller.

What ships

PdfDocumentReader.ExtractText() and PdfReadPage.ExtractText(), each with an options overload, returning the text a page draws in content order with a newline where the baseline moves. Simple fonts only — Type1, MMType1, TrueType — and page content only. Annotation appearance streams are excluded, pinned by a test.

Positioning implements ISO 32000-2 §9.4.4 directly. Lines are grouped by a baseline key projected onto the baseline direction, so a rotated page keeps one physical line in one run rather than splitting per glyph, and rise enters the painted matrix without moving the pen (§9.3.7), so a superscript does not fabricate a line break.

A TJ array's numeric element follows Table 107's prose as a standalone translation rather than §9.4.4's algebraically equivalent fold into the next glyph, because the prose form is also defined for a number at the end of an array and for two in a row.

What review round 2 changed

Fonts bound at the wrong time, losing text silently. The font was resolved when text was shown, against whatever stream was current. Inside a form XObject with its own /Resources that never re-set its font, that meant the text vanished with no diagnostic, or resolved against a different font when the form reused the same resource name. §9.3.1 Table 103 binds Tf to the resource dictionary in effect where Tf executes. The graphics state now captures those resources at that point. Two fixtures cover both manifestations.

The TJ wiring had no end-to-end coverage. Deleting the text-matrix write-back, flipping the adjustment's sign, or dropping the malformed-element report each left the whole suite green, while a test comment asserted a known-answer test covered the trailing-number case. It did not exist. Five tests now drive numeric elements between, before, after and doubled through the real interpreter, asserting exact run positions.

The non-finite test exercised nothing. Its fixture used exponent notation, which PDF's real-number grammar does not accept, so the operands were discarded and the page laid out at the identity matrix. Replaced with a literal that genuinely overflows. The same guard's mirror risk is fixed too: a non-finite first key would have stuck and collapsed the page into a single run.

Rotated pages produced one run per glyph. The line key read the painted translation, which is only the cross-baseline coordinate when unrotated. Fixing it introduced an overflow to NaN for components that are large but individually finite, which the new regression test caught on its own; the formulation now divides before multiplying and has its own known-answer test.

The differential could not catch what this PR claimed it caught. It compared only the translation components, so a misplaced horizontal scaling was structurally invisible to it. It now compares the linear part as well, and a known-answer test exercises a non-default scaling under a rotated transform.

The budget was unit-tested but never charged. Removing any of the four production charge sites left the suite green. Three integration tests now drive real extraction against tightened glyph, character and run ceilings; the fourth site (the per-page reset) still only had a hand-rolled copy of production's own loop at this point — round 4 below closes that gap.

Also: the fuzz bound went back to four, which measurement shows is exactly tight rather than slack by one; the leading-equivalence test for ' now pins the baseline magnitude rather than the run count, so a doubled move fails (round 4 below makes the " test symmetric to it); and the options type validates its separator where it is set, so one object no longer behaves differently at document and page level.

What review round 4 changed

Three reviewers, five mediums, eleven lows. Every fix below claimed a test that fails when the fix is reverted; two of those claims were false, which round 6 below found: ComputeLineKey's a == 0/b == 0 and magnitude == 0/!IsFinite(magnitude) guard pairs each had a test for only one half.

gs silently dropped text with no diagnostic. Table 57 requires an ExtGState's own /Font array element to be an indirect reference to a font dictionary. HandleExtGState stored whatever was there unchecked; a bare /Resources name in that slot looked resolved to TextExtractionVisitor.ResolveFont (which reads a non-PdfName operand as already-resolved) but pointed at a null resources dictionary the same method had just cleared, so the lookup failed with nothing reported. A non-conforming shape is now rejected with an OperandStackMalformed diagnostic, and the font a prior Tf (or an earlier, conforming gs) already bound is left in place rather than replaced with a guaranteed-unresolvable one. The comment this fed into, claiming the interpreter's own ValidateFontResource already covered every case ResolveFont sees as null, was true for Tf and false for gs; it now says so. (Round 6 below found this rejection itself too broad — it also caught a legal direct font dictionary — and gave the diagnostic its own code, since this one turned out to collide with an unrelated defect's.)

The overflow fix's central line was dead under the whole suite. GlyphPositioner.Hypot's scaling branch never ran, because every call site in the tree has A or B exactly zero; return a; in that branch's place passed every existing test. A known-answer test at a 45° angle now pins the exact value 700, not merely equality between two glyphs (return a; keeps two glyphs equal to each other while landing both at the wrong ≈990). Three related gaps in the same formula, found in the same review pass: 0 × ∞ produced NaN on an unrotated page when a component overflowed while its partner stayed zero (each product is now skipped outright when its own factor is exactly zero); an overflowing magnitude produced a deceptively finite key of 0 instead of propagating non-finiteness (now forced to NaN); and a negative font size flipped the key's sign for glyphs on the identical physical baseline, splitting one line into two (the baseline direction is now sign-canonicalised before the projection, which also makes the "reduces to plain F when unrotated" claim in the method's own doc true regardless of the sign of Tfs, not only true up to a sign as it was before). A fourth gap, a rotated line and an unrelated horizontal line keying to the same value when their perpendicular offsets coincide, is documented rather than fixed: resolving it needs the key to carry more than one number.

The fourth budget charge site was still never exercised from production. Deleting budget.BeginPage() from PdfDocumentReader.ExtractTextFromPageCore left the whole suite green, because the one test that name-checked it called BeginPage() itself and drove a hand-rolled copy of the per-page loop, not production's own. ExtractText(PdfTextExtractionOptions) now forwards to an internal overload taking a pre-built DiagnosticSink/TextCallBudget, and a new test drives that seam directly across two real pages with a glyph ceiling of 3, confirming page two still yields its own text once page one trips the ceiling.

The font memo's comparer was unexercised in both halves, and the PR's own claim about it was false. The claim that a fixture "pins the font memo's resources key" was wrong: every existing form fixture has the form inherit its font without issuing its own Tf, so only one (Font instance, Resources) pair was ever memoized and the comparer never had two entries to tell apart. Investigating the resources half: every Tf operand is a freshly lexed object, never reused across two occurrences, so it is captured into GraphicsState.Font together with the exact FontResources in effect at that one Tf, and a q/Q restores both as one unit; a gs-bound font never even reads the resources parameter ResolveFont receives. The resources component could not be exercised because nothing can make it diverge from what the Font instance alone already determines, so it is deleted along with the comment asserting it was load-bearing. A new fixture now discriminates the font half instead: a form that issues its own /F1 12 Tf, bound through its own /Resources to a font different from the invoker's /F1, with both shown on the page — a memo that collapsed those two distinct operand instances would reuse whichever font resolved first for both.

The shipped capability table contradicted the code in the same commit. Round 2 implemented rotation-aware line grouping and, in the same commit, left every "not implemented yet" list — the changelog, the reader guide's prose and capability row, the per-package README's matching row, and PdfDocumentReader.Text.cs's own public XML doc — still saying it wasn't. All five now say what is actually missing: word- and paragraph-aware grouping, specifically that no space is synthesised for a positioning gap. That "concretely" sentence had also drifted to point at the wrong antecedent after round 2's edit (it read as describing paragraph-aware grouping, which isn't what synthesises a space); it now names the word-aware gap directly instead of "that last gap".

Eleven low findings, briefly: PdfDocumentReader.ExtractText's internal seam above also fixed the fourth charge site's test coverage. Hypot's zero-times-infinity, overflow-to-zero and sign-flip gaps are covered above. Orientation collision (a 270°-rotated line and a horizontal line keying to the same value) is documented, not fixed, per the same reasoning as the fourth Hypot gap. ContentInterpreter.CurrentResources's widening to span every operator, added on the theory that text extraction's own Tf handling would need it, had no consumer once that handling moved to GraphicsState.FontResources; reverted to its original scope (set only around OnInlineImage/OnImageXObject), with the tests that pinned the wider scope rewritten to pin the narrower one instead. Two stray §8.10.2 citations (the StreamContext declaration and InvokeForm) are now §7.8.3; the actual fallback-behaviour question they touch on is tracked separately and untouched here. (Round 6 below found two more §8.10.2 citations this sweep had missed, plus a new wrong one this same round added — see below.) DoubleQuoteOperator_equalsTwAndTcThenQuote now asserts baseline magnitude the same way its ' counterpart does, not text alone. GlyphPositionerTests's two CaseGen.Sample calls gained threads: 1: an instrumented run measured 2,959 of 3,000 cases actually landing at the default versus exactly 3,000 with it set, the same class of lost-update hazard FontFuzzTests already works around for a different reason. A stray §404 (that's a diagnostic code, not a clause) lost its section sign, and a §9.4.1 citation for the text-object operator-category list is now §8.2 Table 50, where that list actually lives. The FontResources = null line in HandleExtGState's conforming branch is not load-bearing — deleting it changes nothing observable, since a later Tf overwrites the field regardless — and its comment now says so instead of claiming otherwise; the line stays as cheap defence against a future change to ResolveFont.

What review round 6 changed

Round 5 (review) returned four mediums and eight lows against round 4's own fixes — again a mix of a genuine defect and a fresh instance of the same class round 4 had just introduced. This round is deliberately narrow: two behaviour changes, everywhere else tests or prose.

gs rejected a legal, resolvable shape. Round 3 already extracted text through a direct font dictionary in an ExtGState's /Font array; round 4's rejection lumped that shape in with a bare name. A direct font dictionary has no object number of its own (FontCache's own doc treats this as legal, if unusual, under §7.8.2) and PdfDocumentReader.GetFontReader resolves it exactly the way it resolves an indirect reference, so rejecting it discarded a font this reader could otherwise use — with a preceding valid Tf in scope, the stale binding then decoded glyphs through the wrong widths instead of the ExtGState's own ones. HandleExtGState now accepts PdfIndirectReference or PdfDictionary, still reporting the Table 57 deviation for the dictionary case. A new fixture asserts the text comes through.

The rejection diagnostic was silently absorbed by an unrelated, common defect. It reported OperandStackMalformed, which DiagnosticSink dedupes on (code, object, page); an unbalanced Q — one of the commonest producer defects — reports that same code first, so a page mixing the two defects reported only the Q and lost the font problem entirely, defeating round 4's own "no longer silent" fix. The malformed shape now reports its own code, ExtGStateFontMalformed (310), with an explicit severity arm, and a new fixture pins both diagnostics surviving on the same page. OperandStackMalformed's own doc opened by saying every case it groups shares one remedy, "drop the offending operator" — already false for the clause it had absorbed, since that clause dropped one dictionary entry, not the operator — so removing the clause fixes the doc too.

Two guards round 4 added were pinned on only one side. ComputeLineKey's sign-canonicalisation short-circuits both a == 0 and b == 0, but only the b == 0 half had a test; deleting a == 0 ? 0.0 : alone left the whole suite green. A 90°-family rotation with an overflowing vertical translation now pins it, both in isolation — ComputeLineKey(new Matrix(0, 12, -12, 0, 100, +∞)) returns -100 with the guard, NaN without — and end to end, through two lines reached the same all-digit-literal overflow way the existing fixtures reach one, which the mutant merges into a single run. The magnitude == 0 clause had the identical gap: !double.IsFinite(magnitude) alone still passed the whole suite, load-bearing only because round 4's short-circuits removed the natural NaN propagation that used to cover it. BT /F1 12 Tf 100 700 Td (A) Tj /F1 0 Tf (B) Tj /F1 12 Tf (C) Tj ET — an ordinary zero font size mid-line, which §9.3.1's own note permits — now pins that one too: one run with the guard, three without.

Prose and citations. ComputeLineKey's doc cited §9.6.2.1 Table 109 ("Entries in a Type 1 font dictionary") for permitting a negative font size; the actual text is §9.3.1 Table 103's Tf row, "size shall be a number representing a scale factor." Two more §8.10.2 citations for the §7.8.3 page-inheritance rule survived round 4's own sweep — RunFormXObject's page parameter doc and IContentVisitor.OnImageXObject — and are now §7.8.3. A third site, the form-resources fallback comment in InvokeForm, needed both clauses for two different halves of its own sentence: §8.10.2 Table 93 for "optional but strongly recommended," §7.8.3 for what actually makes an absent /Resources harmless. Hypot's own comment claimed NaN/Infinity propagates through it unchanged whenever either argument already is one; Hypot(0, NaN) actually returns 0, because the comparison meant to put the larger-magnitude argument first is always false for a NaN operand, so the zero check fires on the untouched first argument regardless of the second — harmless today only because ComputeLineKey's own magnitude == 0 check already covers the case, but misleading to a future change to that guard. ComputeLineKey's doc claim that a zero-magnitude baseline "naturally propagates" to NaN stopped being true the moment round 4's short-circuits landed; only the explicit guard produces it now. HandleExtGState's own comment had round 4's mechanism backwards: a bare name is a PdfName, so it took the unresolved-name branch and found nothing because the resources were nulled — not the "looking resolved" the comment described. The ExtractText internal seam's comment claimed option validation belongs entirely to the public overload; the page-range check that overload's own <exception> doc describes actually throws from inside this internal method, on every call through either overload. The changelog's own gap list was missing predefined CMaps and /ReversedChars, present in the four other places that list the same set.

Test message pins. Both gs-rejection tests asserted only the diagnostic code, so rewriting the message text would have left them green; both now assert the exact string.

Reported, not fixed. Table 57 enforcement on an ExtGState's /Font array is still partial past this round: a non-numeric size silently becomes 0, collapsing every glyph's scale and advance; a one- or three-element array is ignored outright; a non-array /Font is ignored outright. Worth a behaviour change, but this round is capped at two; filed separately rather than folded in here.

Every guard touched or kept in this round has a test that fails when that guard alone is removed, verified by actually removing it, running the suite, and reverting.

That claim was false. Round 7 review found three guards, from this round and earlier ones, with no such test: ComputeLineKey's own sign-canonicalisation disjunct (a == 0 && b < 0, distinct from the a == 0/b == 0 short-circuits fixed above, which stay correctly pinned), the ExtGState /Font array's own length check (fontArray.Count == 2), and ResolveFont's null-entry check (and not PdfNull). This is the third time a claim of this shape has been made and then falsified by the round that reviewed it — round 4 made the same claim about its own guards, and this round found two of those false. Round 8 below does not repeat the claim; it lists exactly what was verified, guard by guard.

What review round 8 changed

Round 7 (review) returned three mediums and six lows against round 6's own fixes. This round makes exactly one behaviour change, a single line; everything else is a test or a comment.

A new diagnostic suppressed itself. ExtGStateFontMalformed (310) has two arms — an accepted direct dictionary, and a rejected shape — and both reported against ctx.DiagObjectNumber, the CONTENT STREAM's own object number, not the ExtGState's. DiagnosticSink dedupes on (code, object, page), so two malformed ExtGStates named from the same stream collapsed into one report, and when the two arms disagree, the survivor's message asserts an outcome that is false for whichever one it ate: /GS0 gs with a bare name and /GS1 gs with a direct dictionary, on one page, produced one report claiming the font "was resolved and used anyway," with /GS1's dropped binding never mentioned. HandleExtGState now reports against the ExtGState object's own number — TryGetResource's resolved value, when it is an indirect reference — which keys the two apart under the same dedupe rule. Two direct ExtGState dictionaries still collapse, the same way FontTypeUnsupported already documents for two direct font dictionaries; both diagnostic doc comments now say so. A new fixture puts two differently-malformed, INDIRECT ExtGStates on one page and asserts both reports survive, each naming its own object and its own resource name, corroborated by the extracted text (the ignored one contributes nothing, the accepted one extracts normally).

Three guards, verified by removing each one, running the suite, and reverting — this time recording what actually happened.

  • ComputeLineKey's sign guard, a < 0 || (a == 0 && b < 0): the existing pin uses an identity CTM, which only ever drives a negative, so it never exercises the second disjunct. A 90°-family rotation ([0 1 -1 0 0 0]) makes a exactly 0 for both signs of Tfs, carrying the sign on b alone: hand-computed, Tfs=+12 gives Trm (A=0, B=12, ...) and Tfs=-12 gives (A=0, B=-12, ...), both correctly keying 700 with the guard. Deleting || (a == 0 && b < 0) and running the suite failed both the new isolated unit test (ComputeLineKey_signCanonicalized_negativeFontSizeUnderRotation_viaBAlone, "negative Tfs key, rotated, canonicalized to match: expected 700, got -700") and its end-to-end mirror (RotatedNegativeFontSizeMidLine_doesNotSplitTheLine_viaTheSecondSignDisjunct, which found 2 runs instead of 1). Reverted; suite green again.
  • The ExtGState /Font array's length check, fontArray.Count == 2: deleting it and running the suite threw ArgumentOutOfRangeException straight out of ExtractText for a one-element array fixture (fontArray[1] on a one-element PdfArray), breaking the "malformed document degrades, it does not throw" contract this interpreter's own remarks state elsewhere. A three-element array fixture did NOT throw — fontArray[0] and fontArray[1] both exist, so the guard's absence instead let the reader silently ACCEPT a shape Table 57 does not define (the fixture's extracted text went from empty to "A"). Both fixtures are kept, and the three-element one's own doc records this as the array-length guard's own gap: it stops the crash, not every non-conforming shape, consistent with round 6's "Reported, not fixed" note above. Reverted; suite green again.
  • ResolveFont's null-entry check, is { } entry and not PdfNull: ISO 32000-2 §7.3.9 makes a null dictionary value "equivalent to omitting the entry entirely," so /Font << /F1 null >> must report the same single ResourceMissing (306) an absent /F1 entry already reports. Deleting and not PdfNull and running the suite let fontDict.Get(fontName)'s PdfNull.Instance pass the pattern as a non-null PdfObject, reach GetFontReader, and produce a second, spurious FontUnreadable (400) alongside the correct 306 (Assert.Single() Failure: The collection contained 2 items). Reverted; suite green again.

Prose. TextExtractionVisitor.ResolveFont's own comment said HandleExtGState "rejects a non-conforming ExtGState /Font array outright" — true through round 4, false since round 5 accepted a direct font dictionary; it now says HandleExtGState never stores a bare name, which is the clause this method actually depends on. The zero-font-size test cited "§9.3.1's own note" for permitting a zero size; read against docs/iso/ISO_32000-2_sponsored_EC3.pdf, that note reads "Negative text font size is permitted" and says nothing about zero — zero is Table 103's own Tf row, "Zero sized text shall not mark or clip any pixels." That row is a rendering rule, not an extraction one, so the comment now argues the extraction choice on the same grounds InvisibleRenderModeText_isIncluded already argues for 3 Tr: this reader reports what the file contains, not what a renderer would show. Two misquotes of that same Tf row, "shall be specified explicitly USING Tf," are now "BY using Tf," matching the spec text exactly; every other direct quotation added or touched in this feature's own new files was re-checked the same way against the licensed PDF and found accurate. The rotated-overflow test's doc called a 90°-family rotation composed with an enormous scale in D "a fresh 90-degree-family rotation," and called the resulting astronomically large but finite E "an ordinary finite E" — both now say what they are instead of what they merely resemble; the arithmetic they describe was already correct. The weakest test from round 6, pinning an unbalanced Q and a malformed ExtGState font surviving on the same page, asserted only bare containment on each code with no message and no text; it now pins one diagnostic per code, its exact message, and the resulting empty text.

Gate numbers, oracle set, and the guard-verification method above are all in the Gates section below.

Known gaps, stated plainly

No space is synthesized for a positioning gap, so [(Hello) -500 (World)] TJ extracts as HelloWorld. Also absent: /ToUnicode, predefined CMaps, Type0 and Type3 fonts, /ActualText, /ReversedChars, and word- and paragraph-aware grouping. Line grouping is rotation-aware, and the capability row and the reader guide now say so, alongside the gaps that remain.

Text for a font this PR cannot decode is omitted rather than replaced by a placeholder, and reported once per font through a new FontTypeUnsupported. A placeholder would fabricate a character count, and a fabricated advance would misplace every later glyph.

Property-test reach, measured

Every declared generator bound is reached: Tfs 1 to 144, Tz 10 to 400, Ts −50 to 50, Tc −5 to 20, Tw −2 to 15, glyphs per run 1 to 15. Joint cases are plentiful rather than incidental: roughly 99.8% of sampled cases carry a non-zero rise together with a non-diagonal transform. The identity transform is never generated. One measurement from round 2 didn't hold up under repetition: a horizontal scaling of exactly 100 was reported as appearing three times, but three single-threaded runs of the same generator produced 1, 2 and 4 — it's a seed-dependent count, not a property of the generator, so the ordinary case being rare in this corpus is real but the specific number wasn't.

GlyphPositionerTests's two Sample calls now pass threads: 1 (round 4, see above), which is also what made the seed-dependent count above measurable in the first place — the default multi-threaded sampler was losing updates in the coverage-measuring test, not only in the property test itself.

Gates

Re-measured after round 8's edits with REQUIRE_ORACLES=1 and REQUIRE_VERAPDF=1, against qpdf 12.4.1, poppler from MSYS2 and veraPDF 1.30.2.

Suite Result
Reader 1836 total, 0 failed, 12 skipped
Kernel 1398 total, 0 failed, 0 skipped
Conformance 1300 total, 0 failed, 0 skipped
Cli 908 total, 0 failed, 0 skipped

The Reader count going into round 8 (round 6's own measurement) was 1830 total with the same 12 skips; round 8 adds 6 net new tests (one isolated ComputeLineKey unit test for the sign guard's second disjunct, its end-to-end mirror, the two-ExtGStates dedupe fixture, the one- and three-element array fixtures, and the null-font-entry fixture). Build clean with warnings as errors, format clean, clean-room passing over the tree and every commit message, and the ahead-of-time smoke test passing.

Clause and table citations were checked against the licensed spec text across both the source and test trees — a claim this description has made before and been wrong about. Round 4 fixed one wrong citation (§404, §9.4.1) and added a different one in the same commit (§9.6.2.1 Table 109, fixed above); two stale §8.10.2 citations survived that sweep entirely. Round 6's citations were each read directly from docs/iso/ISO_32000-2_sponsored_EC3.pdf with pdftotext, clause by clause, rather than re-asserted from the previous round's own claim. Round 8's two citation fixes (the Tf row's exact wording, and the zero-font-size governing clause) were read the same way.

PdfDocumentReader.ExtractText and PdfReadPage.ExtractText return a page's
text in content order, with a newline where the baseline moves. This is
the first user-visible text extraction; the content-stream interpreter
and the simple-font decoder that shipped before it had no caller.

Positioning implements ISO 32000-2 9.4.4 exactly: the text rendering
matrix is the parameter matrix concatenated with Tm and the CTM, with
rise entering that matrix alone and never the text matrix, so a
superscript is painted offset without moving the pen. Horizontal scaling
multiplies the whole horizontal bracket including Tc and Tw per 9.3.4,
and word spacing applies only to a single-byte code 32 per 9.3.3. A TJ
array's numeric element follows Table 107's prose as a standalone
translation rather than 9.4.4's algebraically equivalent fold into the
next glyph, because the prose form is also defined for a number at the
end of an array and for two numbers in a row.

The line key is the baseline with rise forced to zero. Folding rise in
would break every superscript onto its own line, which 9.3.7 makes wrong.

ContentInterpreter.CurrentResources now spans the whole walk instead of
only the two image callbacks, so a visitor can resolve a Tf font name
against the resources actually in effect. The image walker reads it only
inside those callbacks, where the value is unchanged.

GetFontReader reported nothing for Type0 and Type3 because its only
callers were tests. Extraction makes that silence user-visible, so it now
reports FontTypeUnsupported once per font. Text for such a font is
omitted rather than replaced by a placeholder: a placeholder fabricates a
character count, and a fabricated advance misplaces every later glyph.

Scope is simple fonts and page content. Annotation appearances, Type0 and
Type3 fonts, ToUnicode, predefined CMaps, ActualText, ReversedChars and
rotation-aware grouping are later work, and the capability table says so.

Refs #98
@Tim81 Tim81 added this to the v2.4 — PDF content extraction milestone Sep 6, 2026
Review round 2 found the font resolved at show time against whatever
stream was current, so a form XObject with its own /Resources that never
re-set its font silently dropped that text, or silently resolved it
against a different font when the form's resources reused the key. ISO
32000-2 Table 103 binds Tf to the resource dictionary in effect where Tf
executes, so GraphicsState now captures those resources at Tf time and the
visitor reads them instead of the current stream's. Two fixtures cover
both manifestations; the second also pins the memo comparer's resources
half, which nothing exercised.

The TJ numeric adjustment had no end-to-end coverage at all: deleting the
write-back, flipping its sign, or dropping the malformed-element report
each left the suite green, while a test doc claimed a known-answer test
covered the trailing-number case that did not exist. Five tests now drive
numbers between, before, after and doubled through the real interpreter,
asserting exact run positions.

The non-finite fixture exercised nothing it named: it used exponent
notation, which PDF's real grammar does not accept, so the operands were
discarded and the page laid out at identity. Replaced with a literal that
genuinely overflows, and fixed the mirror risk in the same guard, where a
non-finite first key would have stuck and collapsed the page into one run.

Rotated pages produced one run per glyph because the line key read the
painted translation directly, which is only the cross-baseline coordinate
when unrotated. Now projected onto the baseline direction. Implementing
that introduced an overflow to NaN for components that are large but
individually finite, which its own new regression test caught; the
formulation now divides before multiplying.

The differential property test compared only the translation, so it could
not catch the misplaced horizontal scaling the PR body claimed it caught.
It now compares the linear part too. The budget guards were unit-tested
but never charged from the extraction path, so four integration tests now
drive them. The fuzz bound went back to four, which measurement shows is
exactly tight. The leading equivalence tests now pin the baseline
magnitude rather than only the run count, so a doubled move fails.

Options validate the page separator where it is set rather than at one of
two call sites, so the same object no longer behaves differently at
document and page level.

Clause citations corrected against the licensed text and swept across both
src and tests, which the previous round claimed and had not done.
…anch

Round-3 review found round 2 had reintroduced the defect it was opened to
fix. HandleExtGState accepted any two-element /Font array and stored a bare
name while clearing the captured resources, so a non-conforming file
produced no characters, no advance and no diagnostic, where round 1 had
extracted the text. Table 57 requires that element to be an indirect
reference; the interpreter now says so and leaves the previous binding
alone rather than replacing it with one that cannot resolve. The comment
claiming the interpreter had already reported a missing resource was true
for Tf and false for gs, and now says which.

The overflow fix added in round 2 was dead code under test: every call site
has a zero component, so Hypot always took its shortcut and returning the
larger term unchanged passed the whole suite. A 45 degree known-answer test
now pins the key at exactly 700, derived by hand rather than from the
implementation. It pins the absolute value, because the mutant keeps two
glyphs equal to each other while making both wrong.

Three further defects in that key. A zero component multiplied by an
infinite one gave NaN on unrotated pages that round 1 grouped correctly. An
overflowing magnitude produced a finite key of zero, which merges real
lines and which nothing downstream could detect. And the key carried the
sign of the font size, so a negative size mid-line split one physical line;
canonicalising the direction also makes the doc's claim that the key
reduces to the painted coordinate when unrotated true without qualification.

The per-page budget reset was verified against a hand-rolled copy of the
production loop rather than production, so deleting it passed. Extraction
now exposes an internal seam and a two-page fixture drives it.

The font memo's resources component is deleted rather than covered. Every
Tf operand is freshly lexed and captured together with the resources in
effect, and save-restore moves them as a unit, so the pairing cannot drift
and no fixture could distinguish it. The font component keeps its reference
comparison, now pinned by a form that binds the same name to a different
font.

Round 2 implemented rotation-aware line grouping and, in the same commit,
re-edited all five places that say it is not implemented, including the
public documentation. Those now describe what is actually absent.

The resources widening from round 1 is reverted. Round 2 removed its only
consumer, so it was carried for nothing while its documentation still cited
that consumer as the reason it existed.
Round-5 review found round 4's own fix had introduced a regression. The
gs check rejected anything that was not an indirect reference, which
lumped a direct font dictionary in with a bare name. Table 57 does require
a reference, so reporting is right, but a direct dictionary is fully
resolvable: FontCache documents it as legal, the Tf path accepts it, and
round 3 extracted its text correctly. Worse, with a preceding valid Tf the
old font and size stayed in effect, so glyphs decoded through the wrong
widths rather than merely vanishing. The element is now accepted when it
is a reference or a dictionary, and the non-conformance is still reported.

That report also had to move off OperandStackMalformed. The sink dedupes
on code, object and page, and an unbalanced Q reports the same code, so a
file with both lost the font diagnostic entirely and the no-longer-silent
half of the round-4 fix was defeated by an unrelated defect. It now has
its own code in the content block, with its own severity arm, and a
fixture puts both conditions on one page.

Round 4 added zero short-circuits to both terms of the line key and pinned
only one of them; deleting the other alone was silent, and end to end it
merged two genuinely distinct lines. The same round added a zero-magnitude
clause that its own short-circuits made load-bearing, since the natural
NaN propagation that used to cover the case was gone, and left that
unpinned too. A zero font size mid-line splits one line into three without
it. Both now have unit and end-to-end coverage.

Citations: the negative-font-size note cited a Type 1 font dictionary
table for a text-state parameter and now cites the Tf row. The form
resources sentence needed two clauses rather than one blanket replacement,
since its wording comes from the form dictionary table while the
inheritance rule lives with resource dictionaries. Two further sites still
citing the old clause for the inheritance rule are corrected.

Comments corrected where they described mechanisms that do not occur: the
helper's NaN propagation claim, which is false when one argument is zero;
the line key's claim that a zero magnitude propagates naturally, which
round 4 made untrue; the ExtGState note that had the resolution branch
backwards; and the seam comment on where option validation lives.
Round-7 review found the code added in round 6 suppressing itself. Both
its arms reported against the content stream's object number, and the
sink dedupes on code, object and page, so two malformed ExtGState fonts
named from one stream collapsed to a single report whose message asserted
an outcome false for whichever one it absorbed. It now reports against the
ExtGState object's own number, which separates them and is more accurate
anyway, since the defect is in that object rather than in the stream that
named it. Two direct ExtGState dictionaries still collapse, having no
object number to key on; that is documented the way the font-type code
already documents its own equivalent.

Three guards had no test that failed when that guard alone was removed.
Each was removed, run, and reverted rather than argued about. The sign
canonicalisation's second disjunct: without it a negative font size under
a 90 degree transform keys 700 against -700 and splits one baseline in
two. The array-length check: without it a one-element font array throws
out of ExtractText, breaking this interpreter's own promise that a
malformed document degrades rather than throws. The null-entry check:
without it an absent-by-null font resource reports a spurious second
diagnostic, where the specification makes a null value equivalent to an
absent one.

The array-length case is not symmetric and the tests say so. Removing the
guard crashes on a one-element array but silently accepts a three-element
one, so the guard prevents two different failures rather than one.

Prose: a comment describing the ExtGState check as rejecting every
non-conforming array, which stopped being true when round 6 began
accepting a direct dictionary; a citation resting on the clause note about
negative font size, which says nothing about zero, where the operator
table does; and two misquotes inside quotation marks, with every other
direct quotation in the new files checked against the licensed text.
@Tim81
Tim81 merged commit fd79437 into main Sep 7, 2026
4 checks passed
@Tim81
Tim81 deleted the feat/98-text-extraction-api branch September 7, 2026 06:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant