Find Where an Amount Sits on a PDF Page

appears twice in a single statement 1,200.00: once in the payable amount field, and once in the description text. A full-text search can locate both, but it can

If you check figures such as payable amounts in PDF statements or forms, a plain text search often returns more than one hit. For example, 1,200.00 may appear once in the payable amount field and again in the description text. Search finds both, but it cannot tell you which one is the business field. Taking the first match is a hard-to-detect error: the amount looks right, but it may have come from the wrong field.

This guide shows you how to locate an amount by its position on the page. You will define a known region, extract words with their coordinates, and handle zero and multiple matches as explicit results rather than making a silent choice. A short test setup and a table of outcomes with suggested actions are included.

If your form layout is fixed, define a known region first and then search for text inside it. This is often easier to interpret than adding more regular expressions. Treat both zero matches and multiple matches as results to report, so the program does not decide on the business's behalf.

How do you find where an amount sits on a PDF page? The short answer

Define a known rectangle on the page, extract words with their coordinates, keep only the matches that sit fully inside that rectangle, and report zero or multiple matches explicitly.

Your situationWhat to doWhy
Your form has a fixed layoutDefine a rectangle around the field and search for the text inside itThis is often easier to interpret than adding more regular expressions
A search returns two or more matchesReturn all candidates and resolve them with tags or manual reviewThe program should not choose which field is the business field
A search returns no matchRecord the possible causes and check the original page; do not pad with zerosThe area may be wrong, the amount may be split, or the text layer may be missing
The amount is split or has adjacent tagsTreat it as a non-match and send it for revalidationSilently joining fragments can create an amount that looks valid but is not
The page is scannedExtract usable text and its coordinates firstA page can have a text layer and still contain errors

Why a plain search is not enough

A full-text search can locate every occurrence of an amount, but it cannot decide which occurrence matters. You need the position of each match to make that decision.

  • Several matches are normal. The same figure can appear in a field and in a description.
  • Taking the first match hides the problem. The output looks plausible, so the error is hard to spot.
  • Zero matches and multiple matches are both signals. Report them rather than guessing.

Read words with their positions

PyMuPDF's page.get_text("words") returns a record for each word, including its position. Common fields are (x0, y0, x1, y1, text, block_no, line_no, word_no). The example below uses only the first five fields and leaves the last three out of the region filtering.

Keep in mind that a "word" here is a fragment supplied by the extractor. It is not always a linguistic word, and an amount such as 1,200.00 may be split into pieces or carry adjacent tags. This method matches only complete segments. It is better to send non-matching records for revalidation than to join them into a value that looks correct.

Test with two composite pages

To check the logic, create a PDF page in memory and place the same amount near vertical coordinates 120 and 420. The query region covers only the amount above.

Note that the text insertion point is the baseline, not the top-left corner of the text box. The real height and width of a box depend on the font and font size, so do not hard-code coordinates as if they must equal a particular value.

A correct result should meet two conditions:

  • One candidate: the query region returns exactly one match.
  • Full containment: the candidate rectangle lies completely inside the query region.

Next, expand the query to cover the whole page. You should get two candidates, which triggers the ambiguity branch. Finally, search for a string that does not appear on the page to confirm that zero hits are handled. Testing against the contract the interface must meet is more useful than showing one successful lookup.

Code: pass the candidate count to the caller

Install the dependency pymupdf in your test environment and lock its version. The code below does not access the network, write files, or modify existing customer documents. It generates a PDF for demonstration only.

import pymupdf

def locate(page, target, query):
    query = pymupdf.Rect(query)
    candidates = []
    for word in page.get_text("words"):
        x0, y0, x1, y1, text = word[:5]
        box = pymupdf.Rect(x0, y0, x1, y1)
        if text == target and query.contains(box):
            candidates.append(tuple(box))
    return candidates

def decide(candidates):
    if len(candidates) == 0:
        return "missing"
    if len(candidates) > 1:
        return "ambiguous"
    return "unique"

with pymupdf.open() as doc:
    page = doc.new_page(width=595, height=842)
    page.insert_text((80, 120), "1,200.00", fontsize=11)
    page.insert_text((80, 420), "1,200.00", fontsize=11)
    query = pymupdf.Rect(72, 100, 300, 150)
    local = locate(page, "1,200.00", query)
    assert decide(local) == "unique"
    assert query.contains(pymupdf.Rect(local[0]))
    assert decide(locate(page, "1,200.00", page.rect)) == "ambiguous"
    assert decide(locate(page, "999.99", query)) == "missing"
    print("unique / ambiguous / missing cases passed")

contains requires the candidate to lie fully inside the target area, not merely touch its edges. If the query box is too tight, amounts near the border may fall into the zero-hit case. Do not expand the box to the whole page to fix this automatically. First check the coordinate system you used to define the area, then decide whether to adjust it.

If your business rules allow a candidate whose centre point lies inside the boundary, write that as a separate rule and test boundary overlaps separately. Do not quietly change the meaning inside the same function.

Three outcomes, three ways to handle them

ResultPossible causesSuggested action
Exactly one matchOne fully matching fragment lies within the regionStore the page number, original text, rectangle, and rule version
Zero matchesThe area is wrong, the amount is split, or the text layer is missingRecord the candidate causes, check the original page, and do not pad with zeros
Multiple matchesThe same amount appears in the region, or the template has changedReturn all candidates and resolve them with tags or manual review
A match exists but the value is wrongThe text layer itself is faulty, or the wrong target was matchedCheck the original page and do not accept substituted coordinate values
The box appears offsetDisplay coordinates and extracted coordinates are mixedDefine the transformation chain for rotation, cropping, and render scaling explicitly

In production, do not rely on assert to catch problems, because optimised modes can remove assertions. The example uses assertions for regression checks. When you actually queue tasks, use explicit conditional branches and business states.

This is not a general-purpose amount extractor

The code does not parse currency symbols, thousands separators, or decimal rules. It also cannot tell that "current period payable" differs from "prior period balance." A single candidate is not the same as a single business meaning.

Scanned documents must first yield usable text and spatial coordinates. A page with a text layer that contains errors should not be approved just because its text can be copied.

This example uses unrotated composite pages. For real rotated pages, decide whether the query box comes from the displayed screen or from extracted coordinates, and convert as needed. Do not multiply by a matrix without knowing where the values came from. Also keep track of whether page numbers are zero-based or human-readable. Otherwise a reviewer may open the neighbouring page and wrongly conclude that the evidence is missing.

Check the key numbers after translation

Translating a document involves more than making sentences fluent. Amounts, dates, and quantities need to be checked one by one.

OmniDoc (Product Entry) offers several entry points for document translation. The bilingual comparison on the official website can serve as a verification reference. The coordinate-locating script helps you keep evidence of the original text and pinpoint problem areas.

Evaluate the workflow with desensitised samples that you have permission to upload. Translated text is often longer, so content may move. Do not treat "the old and new coordinates are exactly the same" as proof of a correct translation. More useful checks are:

  • Are the amounts preserved?
  • Is the currency clearly stated?
  • Do the tags still point to the same business meaning?

Dividing the work between technical checks and manual review gives you more reliable delivery than any claim of perfect fidelity.

Save a set of failed samples

Collect the zero-match and multiple-match pages from your real templates. Record the reason for each one separately. Then decide whether to add region rules, add tag constraints, or switch to another extraction route. Do not use an arbitrary percentage as the switching threshold for every business case.

Interface reference: PyMuPDF Page.get_text. The synthetic examples here are not an accuracy test on real invoices.

📊 At a glance

ApproachWhen it fitsWhat to watch for
Fixed-region searchThe form layout is stable and you know where the field sitsAmounts near the border can fall into the zero-match case if the box is too tight
Plain full-text searchYou only need to know whether a figure appears somewhere on the pageMultiple matches cannot be assigned to a business field
Regular expressions added to the searchYou want to match a pattern rather than a fixed positionAdding more rules can be harder to interpret than a defined region

🎯 Which approach fits you?

If you check amounts on a fixed-layout form

Define a region around the field and report any zero or multiple matches. This keeps the check tied to the field you care about.

If you work with scanned documents

Confirm that usable text and coordinates can be extracted before you rely on position-based search.

If your pages are rotated

Settle whether your query box uses screen or extracted coordinates, and convert them consistently before you search.

❓ FAQ

1. Why can't I just take the first match of an amount?

The first match may be in the wrong field, such as a description rather than the payable amount. The result looks plausible, which makes the error hard to detect.

2. What should happen when no match is found?

Record the possible causes, such as a wrong area, a split amount, or a missing text layer. Check the original page and do not fill in a value with zeros.

3. Does a single match mean the amount is correct?

Not necessarily. The code finds one candidate, but it does not check currency, number format, or business meaning.

4. Why not use assert in production?

Optimised modes can remove assertions. Use explicit conditional branches and business states for real task handling.

📝 Summary

Locate amounts by their position on the page, and report zero or multiple matches rather than choosing one yourself. Test the logic against the interface's contract before you rely on it with real documents.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-04